Skip to content

Commit 5d9197b

Browse files
✨ feat(preview): PowerPoint/LibreOffice backend abstraction + engine sync
- preview/backend.py: unified PresentationBackend interface - preview/autofit.py: autofit processing extracted - preview/__init__.py: refactored to use backend abstraction - converter/pipeline.py: refactored to use backend abstraction - pptx_builder.py: export_pdf() one-liner replaces inline AppleScript/PowerShell
1 parent 749b8d1 commit 5d9197b

11 files changed

Lines changed: 632 additions & 303 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,3 +57,4 @@ skill/assets/material/
5757
*.tsbuildinfo
5858
.ash/
5959
?/
60+
skill/sdpm/.cache/

‎skill/scripts/pptx_builder.py‎

Lines changed: 4 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
from sdpm.preview import (
5151
_is_wsl,
5252
check_layout_imbalance,
53+
export_pdf,
5354
get_tmp_project_dir,
5455
refresh_autofit,
5556
unlock_height_constraints,
@@ -256,58 +257,17 @@ def cmd_preview(args):
256257
import shutil
257258
shutil.rmtree(png_dir, ignore_errors=True)
258259
else:
259-
# macOS / WSL: PDF + pdftoppm pipeline
260+
# PDF + pdftoppm pipeline (macOS / WSL / Linux)
260261
pdf_path = output_dir / "slides.pdf"
261262
pre_generated_pdf = getattr(args, '_pdf_path', None)
262263

263264
if pre_generated_pdf and Path(pre_generated_pdf).exists():
264-
# PDF already generated by _refresh_autofit — skip PowerPoint
265265
import shutil
266266
if str(Path(pre_generated_pdf).resolve()) != str(pdf_path.resolve()):
267267
shutil.copy2(pre_generated_pdf, pdf_path)
268268
else:
269-
if _is_wsl():
270-
win_pptx = subprocess.run(["wslpath", "-w", str(pptx_path)], capture_output=True, text=True).stdout.strip() # nosec B603 # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-audit
271-
win_pdf = subprocess.run(["wslpath", "-w", str(pdf_path)], capture_output=True, text=True).stdout.strip() # nosec B603 # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-audit
272-
ps_cmd = (
273-
f"$app = New-Object -ComObject PowerPoint.Application; "
274-
f"$prs = $app.Presentations.Open('{win_pptx}', "
275-
f"[Microsoft.Office.Core.MsoTriState]::msoTrue, "
276-
f"[Microsoft.Office.Core.MsoTriState]::msoFalse, "
277-
f"[Microsoft.Office.Core.MsoTriState]::msoFalse); "
278-
f"$prs.SaveAs('{win_pdf}', 32); "
279-
f"$prs.Close(); $app.Quit()"
280-
)
281-
result = subprocess.run(
282-
["/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe", "-Command", ps_cmd],
283-
capture_output=True, timeout=60) # nosec B603 # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-audit
284-
result = subprocess.CompletedProcess(
285-
result.args, result.returncode,
286-
stdout=result.stdout.decode("cp932", errors="replace") if result.stdout else "",
287-
stderr=result.stderr.decode("cp932", errors="replace") if result.stderr else ""
288-
)
289-
else:
290-
from sdpm.preview import (
291-
_mac_open_pptx_background,
292-
_mac_restore_pptx_focus_async,
293-
)
294-
pptx_name = Path(pptx_path).name
295-
restore_info = _mac_open_pptx_background(pptx_path)
296-
_mac_restore_pptx_focus_async(restore_info)
297-
import time
298-
time.sleep(2)
299-
script = f'''
300-
tell application "Microsoft PowerPoint"
301-
set theDoc to presentation "{pptx_name}"
302-
set outPath to (POSIX file "{pdf_path}") as text
303-
save theDoc in outPath as save as PDF
304-
close theDoc saving no
305-
end tell
306-
'''
307-
result = subprocess.run(["osascript", "-e", script], capture_output=True, text=True) # nosec B603 # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-audit
308-
309-
if result.returncode != 0 or not pdf_path.exists():
310-
print(f"Error: PDF export failed: {result.stderr}", file=sys.stderr)
269+
if not export_pdf(pptx_path, pdf_path):
270+
print("Error: PDF export failed", file=sys.stderr)
311271
sys.exit(1)
312272

313273
# Parse pages to export

‎skill/sdpm/assets/__init__.py‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,24 @@ def _load_extra_sources() -> list[dict]:
6363
_manifest_cache: Optional[list[dict]] = None
6464

6565

66+
def _check_recolor_protected(cfg, item: dict) -> bool:
67+
"""Check if an icon entry is recolor-protected based on config."""
68+
if cfg is True:
69+
return True
70+
if isinstance(cfg, dict):
71+
when = cfg.get("when", {})
72+
types = when.get("type", [])
73+
if types and item.get("type") in types:
74+
return True
75+
return False
76+
77+
6678
def _load_manifest_file(
6779
manifest_path: Path,
6880
source_override: Optional[str],
6981
all_assets: list[dict],
7082
files_dir: Optional[Path] = None,
83+
recolor_protected=None,
7184
) -> None:
7285
"""Load a single manifest.json and append entries to all_assets.
7386
@@ -83,9 +96,11 @@ def _load_manifest_file(
8396
data = json.load(f)
8497
source = source_override or data.get("source", manifest_path.parent.name)
8598
resolved_dir = files_dir or manifest_path.parent
99+
recolor_cfg = recolor_protected or data.get("recolorProtected", False)
86100
for item in data.get("icons", []):
87101
item["_source"] = source
88102
item["_dir"] = resolved_dir
103+
item["_recolor_protected"] = _check_recolor_protected(recolor_cfg, item)
89104
all_assets.append(item)
90105

91106

@@ -113,7 +128,10 @@ def _load_manifests() -> list[dict]:
113128
manifest_path = Path(entry["manifest"]).expanduser()
114129
source_name = entry.get("source")
115130
files_dir = Path(entry["files_dir"]).expanduser() if "files_dir" in entry else None
116-
_load_manifest_file(manifest_path, source_override=source_name, all_assets=all_assets, files_dir=files_dir)
131+
_load_manifest_file(
132+
manifest_path, source_override=source_name, all_assets=all_assets,
133+
files_dir=files_dir, recolor_protected=entry.get("recolorProtected"),
134+
)
117135

118136
# Auto-detect legacy icons/ directory (sibling of assets/)
119137
legacy_icons = ASSETS_DIR.parent / "icons"
@@ -203,6 +221,28 @@ def check_asset_exists(ref: str, theme: str = "light") -> bool:
203221
check_icon_exists = check_asset_exists
204222

205223

224+
def is_recolor_protected(ref: str) -> bool:
225+
"""Check if an asset is recolor-protected (e.g. brand icons).
226+
227+
Args:
228+
ref: Asset reference — `assets:source/name` or `icons:name`.
229+
230+
Returns:
231+
True if the asset should not be recolored.
232+
"""
233+
if ref.startswith("assets:"):
234+
name = _strip_ext(ref.split(":", 1)[1].split("/", 1)[-1])
235+
elif ref.startswith("icons:"):
236+
name = _strip_ext(ref.split(":", 1)[1])
237+
else:
238+
return False
239+
for item in _load_manifests():
240+
file_stem = item["file"].rsplit(".", 1)[0]
241+
if file_stem == name:
242+
return item.get("_recolor_protected", False)
243+
return False
244+
245+
206246
def resolve_asset_path(ref: str, theme: str = "light") -> Path:
207247
"""Resolve asset reference to file path.
208248

‎skill/sdpm/builder/elements/image.py‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from sdpm.utils.effects import apply_effects
1010
from sdpm.utils.svg import _recolor_svg, get_svg_dimensions, generate_qr_svg, add_svg_to_slide
1111
from sdpm.utils.text import _expand_styled_newlines
12+
from sdpm.assets import is_recolor_protected
1213

1314
_DEFAULTS = ELEMENT_DEFAULTS["image"]
1415

@@ -91,10 +92,14 @@ def _add_image(self, slide, elem):
9192
svg_bytes = None
9293
if is_svg:
9394
svg_bytes = img_path.read_bytes()
94-
effective_icon_color = icon_color or self.theme_colors["text"]
95-
recolored = _recolor_svg(svg_bytes, effective_icon_color)
96-
if recolored:
97-
svg_bytes = recolored
95+
if src and is_recolor_protected(src):
96+
if icon_color:
97+
print(f"Warning: iconColor ignored (recolor-protected asset): {src}", file=sys.stderr)
98+
else:
99+
effective_icon_color = icon_color or self.theme_colors["text"]
100+
recolored = _recolor_svg(svg_bytes, effective_icon_color)
101+
if recolored:
102+
svg_bytes = recolored
98103
elif icon_color:
99104
print(f"Warning: iconColor ignored (not SVG): {img_path.name}", file=sys.stderr)
100105

‎skill/sdpm/converter/pipeline.py‎

Lines changed: 4 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -12,97 +12,10 @@
1212
from sdpm.utils.io import write_json
1313
from sdpm.schema.defaults import sort_element_keys
1414

15-
def _is_wsl():
16-
try:
17-
return 'microsoft' in open('/proc/version').read().lower()
18-
except Exception:
19-
return False
20-
2115
def _refresh_autofit_pptx(pptx_path):
22-
"""Open PPTX in PowerPoint, apply 'resize shape to fit text' on spAutoFit textboxes, return temp path."""
23-
import shutil
24-
import subprocess
25-
import tempfile
26-
from pptx import Presentation as _Prs
27-
from pptx.oxml.ns import qn as _qn
28-
29-
# Find textboxes (txBox="1") to apply resize
30-
prs = _Prs(str(pptx_path))
31-
targets = [] # list of (slide_idx_1based, shape_idx_1based)
32-
for si, slide in enumerate(prs.slides, 1):
33-
for shi, shape in enumerate(slide.shapes, 1):
34-
sp = shape._element
35-
nvSpPr = sp.find(_qn('p:nvSpPr'))
36-
if nvSpPr is None:
37-
continue
38-
cNvSpPr = nvSpPr.find(_qn('p:cNvSpPr'))
39-
if cNvSpPr is None or cNvSpPr.get('txBox') != '1':
40-
continue
41-
targets.append((si, shi))
42-
43-
if not targets:
44-
return None # nothing to refresh
45-
46-
tmp_dir = tempfile.mkdtemp()
47-
tmp_pptx = Path(tmp_dir) / pptx_path.name
48-
shutil.copy2(pptx_path, tmp_pptx)
49-
50-
if sys.platform == "darwin":
51-
from sdpm.preview import _mac_open_pptx_background, _mac_restore_pptx_focus_async
52-
# Build AppleScript lines for each target shape
53-
resize_lines = "\n".join(
54-
f' try\n'
55-
f' tell text frame of shape {shi} of slide {si} of pres\n'
56-
f' set auto size to shape to fit text\n'
57-
f' end tell\n'
58-
f' end try'
59-
for si, shi in targets
60-
)
61-
pptx_name = tmp_pptx.name
62-
restore_info = _mac_open_pptx_background(tmp_pptx)
63-
_mac_restore_pptx_focus_async(restore_info)
64-
import time
65-
time.sleep(2)
66-
script = f'''
67-
tell application "Microsoft PowerPoint"
68-
set pres to presentation "{pptx_name}"
69-
{resize_lines}
70-
delay 1
71-
save pres
72-
close pres
73-
end tell
74-
'''
75-
cmd = ["osascript", "-e", script]
76-
elif sys.platform == "win32" or _is_wsl():
77-
# PowerShell COM: TextFrame.AutoSize = 1 (ppAutoSizeShapeToFitText)
78-
# targets is list of (slide_1based, shape_1based)
79-
resize_lines = "; ".join(
80-
f"$prs.Slides[{si}].Shapes[{shi}].TextFrame.AutoSize = 1"
81-
for si, shi in targets
82-
)
83-
ps_cmd = (
84-
f"$app = New-Object -ComObject PowerPoint.Application; "
85-
f"$prs = $app.Presentations.Open('{tmp_pptx}'); "
86-
f"{resize_lines}; "
87-
f"$prs.Save(); $prs.Close(); $app.Quit()"
88-
)
89-
if _is_wsl():
90-
win_path = subprocess.run(["wslpath", "-w", str(tmp_pptx)], capture_output=True, text=True).stdout.strip() # nosec B603 # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-audit
91-
ps_cmd = ps_cmd.replace(str(tmp_pptx), win_path)
92-
cmd = ["/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe", "-Command", ps_cmd]
93-
else:
94-
cmd = ["powershell.exe", "-Command", ps_cmd]
95-
else:
96-
shutil.rmtree(tmp_dir)
97-
return None
98-
try:
99-
result = subprocess.run(cmd, capture_output=True, timeout=60) # nosec B603 # nosemgrep: python.lang.security.audit.dangerous-subprocess-use-audit
100-
if result.returncode == 0:
101-
return tmp_pptx
102-
except (subprocess.TimeoutExpired, FileNotFoundError):
103-
pass
104-
shutil.rmtree(tmp_dir)
105-
return None
16+
"""Re-save PPTX with autofit applied via detected presentation backend."""
17+
from sdpm.preview import refresh_autofit_for_convert
18+
return refresh_autofit_for_convert(pptx_path)
10619

10720
def pptx_to_json(pptx_path: Path, output_dir: Path = None, no_autofit: bool = False, use_layout_names: bool = True, minimal: bool = False):
10821
"""Convert PPTX to JSON. Output is a project folder with slides.json + images/."""
@@ -111,7 +24,7 @@ def pptx_to_json(pptx_path: Path, output_dir: Path = None, no_autofit: bool = Fa
11124
if not no_autofit:
11225
tmp_pptx = _refresh_autofit_pptx(pptx_path)
11326
if tmp_pptx:
114-
print("Autofit refreshed via PowerPoint")
27+
print("Autofit refreshed via presentation backend")
11528

11629
actual_path = tmp_pptx or pptx_path
11730
prs = Presentation(str(actual_path))

‎skill/sdpm/diff/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ def load_slides_json_or_pptx(path):
172172
for slide_def in data.get("slides", []):
173173
builder.add_slide(resolve_override(slide_def, id_map))
174174
builder.save(tmp_pptx)
175-
# Apply autofit via PowerPoint (same as generate flow)
175+
# Apply autofit via detected presentation backend
176176
from sdpm.preview import refresh_autofit, unlock_height_constraints
177177
refresh_autofit(tmp_pptx)
178178
unlock_height_constraints(tmp_pptx)

0 commit comments

Comments
 (0)