# Stage 6 — Pre-Conversion Slide Layout Editor

## Status

Implementation and acceptance hardening continued on 2026-09-14 without resetting data or removing multimedia changes. The additive Stage 6 migration is applied locally; Stage 5 acceptance remains separate. Stage 6 is **not fully accepted yet**.

Implemented: extraction contract v2 with paragraph-level/run-level resolution and explicit/inherited/mixed/unresolved states; per-property capabilities; renderer-backed family/style options and byte-preserving legacy alias enrichment; sparse slide-local corrections; centimetre geometry/margins; shared bilingual editor labels; eight resize handles, pointer cancellation, keyboard alternatives, zoom/pan, focus trap/restoration, serialized debounced saves, dirty-close/reload warnings, and desktop side-by-side/mobile switched comparison. Font warnings remain visible but do not block temporary layout previews; substitution acknowledgement remains part of final image generation. Latest successful previews are retained through subsequent rendering/failure. Active rendering shows a loading screen; retained outdated images are labelled when displayed.

Preview snapshot copies are hash-checked and unsuccessful requests roll back database writes. Duplicate jobs cannot claim a ready/rendering preview; publication uses conversion/preview locks, deletion prevents publication, failed outputs are cleaned, and two successful generations are retained. Final generation verifies the current source and saved correction snapshot; old images/packages remain until successful publication. Manual slide-review records are no longer required.

### Verified locally

Preview usability update: a prominent **Preview changes** action in the workspace header saves pending corrections and requests the isolated preview pipeline. The canvas shows loading while preparing, queued, rendering, and downloading the selected image; loading ends only after the image loads. Failed image downloads expose **Retry image**, and repeat corrected-preview requests are disabled while rendering. English/Arabic messages, accessible status announcements and reduced-motion styling are included.

Progressive preview update: the initial workspace preview includes every slide and publishes each JPEG as soon as it is ready. After layout edits, saved corrections are compared per slide with the latest compatible complete preview. **Preview changes** queues only slides marked **Needs preview** and copies cached images for every unaffected slide into the new generation. Font or rendering-setting changes make the cache incompatible and require a new all-slide progressive preview. Per-slide queued/rendering/ready/failed state drives the slide rail. Original comparison remains lazy and uses its separate cache key.

Selected-page PDF update: temporary previews now pass the ordered target slide numbers to LibreOffice's `impress_pdf_Export` `PageRange` filter. The resulting PDF contains only requested pages, so editing one slide no longer creates an all-slide PDF before rasterization. Requested order is preserved, allowing the selected slide to remain first. The helper verifies the PDF page count and falls back to the proven full-document PDF path when an older LibreOffice build rejects or ignores page-range filter options. Final course-image generation intentionally remains full-presentation and full-resolution.

Service boundary: layout previews and lazy original comparisons use `IsolatedSlidePreviewRenderer` and the helper's `preview` operation. **Generate images** and **Regenerate images** continue to use `IsolatedPresentationRenderer` and the helper's `render` operation, which always validates and publishes the complete slide and thumbnail sets. The preview optimization cannot change final-generation behavior.

Opening **Fix slide layout** automatically starts one current all-slide progressive preview when one is not already available. A current queued, rendering, or complete all-slide preview is reused. If an older partial preview is still running, the editor waits for it to finish before requesting the complete preview so two LibreOffice exports do not compete for the same project. This automatic request runs only once when the workspace opens; subsequent corrections continue to require **Preview changes**, preventing expensive rendering after every edit.

Preview images default to 1280px and JPEG quality 82. Configure these independently from final course images with `LAYOUT_PREVIEW_SIZE` and `LAYOUT_PREVIEW_QUALITY`. Final image generation remains full-presentation and unchanged.

- Backend: 47 tests, 389 assertions passed, including the real Arabic Windows Docker render/package integration test. Tests use SQLite in memory, not the user's project database.
- Frontend: build and 27 tests passed; lint has zero errors and four existing CoursePreview hook-dependency warnings.
- Linux helper in Windows Docker: 10 tests passed with the approved local OTF fixture, including full-name alias selection, conflicting-family concurrent isolation, mixed runs, paragraph/master/theme inheritance, unresolved values, sparse corrections, and XML ordering.
- Browser: repaired slide 3 on a separate owned copy of the supplied 85-slide presentation. Enabled wrapping and changed the three description box heights to 1.4 cm; autosaves, original/corrected previews, current review and final rendering succeeded. The test copy's preparation and rendered revisions both equal 3. A SCORM package was built from its final images. Original source bytes were verified identical; the original user project was not edited.
- English and Arabic desktop workspace/comparison were visually checked. Account language was restored to English afterward.

### Acceptance still pending

The **Needs review** filter, review button, review status, review API, and final-generation review gate were removed. Saved slides whose corrections differ from the compatible preview appear under **Needs preview** until their new image is ready.

Native Ubuntu rendering and Moodle learner acceptance were unavailable in this run. Mobile viewport emulation was unavailable through the connected browser; mobile visual checks and exhaustive keyboard/focus/zoom/pan/cancellation, offline/conflict and rapid-edit browser scenarios remain pending. Additional complex inheritance/unsupported-element fixtures and full save-coordinator interaction coverage remain required. No PowerPoint reference export was supplied for fidelity comparison. Do not infer complete acceptance from passing automated tests.

## Running the Preview Worker

Rebuild the existing renderer image after updating the helper, then run migrations and restart workers:

```bash
docker build -t docudeck-renderer:1 documents_generator_tools_backend/resources/font-renderer
# In the backend directory:
php artisan migrate
php artisan queue:restart
php artisan queue:work layout-previews --queue=layout-previews --timeout=2100 --tries=1
```

Run this worker separately from conversions and media workers. The `layout-previews` database queue connection has a 2,200-second reservation timeout, longer than its 2,100-second job timeout. Corrected preview work exports a target-page PDF and rasterizes the selected and changed pages progressively; original comparison pages are queued lazily on the same worker. `pdfinfo` and `pdftoppm` are both supplied by `poppler-utils`. Ubuntu uses the same Python helpers/dependencies directly; Windows requires the rebuilt Docker image. Uploaded fonts and working copies remain private.

## Summary

Add an optional, focused **Fix slide layout** tool during PowerPoint preparation. Authors can correct text-box positioning, dimensions, wrapping, and formatting before approving the final slide images.

```text
Upload PowerPoint → Upload fonts → Select rendering language/direction
→ Review font warnings → Inspect temporary previews → Fix slide layout
→ Refresh preview → Approve and generate final images → Author course → Generate SCORM
```

The saved original PowerPoint remains unchanged. Corrections are stored separately and applied to temporary working copies. Presentation content is never automatically translated.

Temporary preview rendering is necessary for accurate visual feedback. It is separate from publication of the final course images; this is not a browser-only PowerPoint renderer.

## Goals and First-Version Scope

- Make common repairs easy without requiring a full PowerPoint editing interface.
- Support ordinary, ungrouped, unrotated text boxes and text placeholders whose effective formatting can be resolved reliably.
- Allow moving and resizing supported boxes and changing font family/style, size, alignment, direction, wrapping, and paragraph spacing.
- Preserve authored text and mixed Arabic/English runs by default. Text rewriting is not required for the first version.
- Keep unsupported elements visible in previews but locked, with a clear explanation.
- Allow authors to skip layout editing and proceed through the existing preparation workflow.
- Reopen the same layout corrections later and regenerate from the original source.

Images, grouped or rotated elements, tables, charts, SmartArt, complex effects, and unsupported text transformations are out of scope for editing in the first version. Slide creation, deletion, reordering, source replacement, and a complete PowerPoint editor are deferred.

## Dependency: Correct Font Matching First

Resolve PowerPoint font names against uploaded font family, subfamily/style, full-name, and available alias metadata before diagnosing layout problems.

The inspected presentation requests `WinSoft Pro Medium`, while its uploaded font reports family `WinSoft Pro` and style `Medium`. The current renderer's matching can select a fallback for the full-name request. On slide 3, descriptions also explicitly disable wrapping, so wider fallback text can overflow into adjacent columns.

- Verify requested family/style selection in the actual isolated renderer, not only the browser sample.
- Explain missing fonts and substitutions before asking authors to repair boxes manually.
- Do not automatically enable wrapping, shrink text, or change all slides to compensate for font substitution.
- Correct matching improves rendering opportunities but does not guarantee Microsoft PowerPoint-identical output.

## User Experience

### Preparation screen

- Add an optional **Fix slide layout** action after fonts and rendering defaults are configured.
- Display slide thumbnails, the selected slide, rendering status, and font warnings.
- Generate previews on explicit request; show queued, rendering, ready, unavailable, and failed states.
- Clearly distinguish **Corrections saved**, **Preview needs refresh**, and **Final images need regeneration**.

### Simple editor

- Click or tap a supported text box to select it.
- Drag the box to move it and drag handles to resize it.
- Use a small inspector with font, font size, alignment, direction, and **Wrap text**.
- Keep paragraph spacing and precise numeric coordinates under Advanced settings.
- Offer Undo, Redo, Reset selected box, and Reset slide. Confirm destructive resets when changes exist.
- Offer **Refresh preview** and an original-versus-corrected comparison.
- Dragging updates selection geometry immediately. Accurate text layout is confirmed after rendering, not promised while dragging.
- Keep the last good preview visible while the next preview renders; display errors without discarding corrections.

The intended overlapping-text repair is: select a box → enable wrapping or resize/reposition it → refresh preview → approve final generation.

### Accessibility and Arabic/RTL

- Localize controls and messages in English and Arabic.
- Provide keyboard selection and movement, accessible resize alternatives, labelled numeric inputs, and visible focus.
- On narrow screens, use a stacked inspector and zoomable/pannable canvas rather than tiny handles alone.
- The editor interface follows application direction. Slide coordinates remain in the original slide coordinate system regardless of interface RTL.
- Never mirror the slide image, change slide order, or confuse paragraph RTL direction with right alignment.
- Isolate identifiers and font names where needed; retain authored Arabic/English text and explicit run languages.

## Element Extraction and Identity

- Parse PPTX XML safely using the existing renderer security boundaries and archive limits.
- Read slide dimensions, shape transforms, text bodies, paragraphs, runs, font references, wrapping, margins, alignment, and direction.
- Resolve effective values through slide → layout → master → presentation defaults and themes.
- Distinguish explicit properties from inherited values and show inherited settings honestly.
- Use stable identifiers combining the source slide part and shape ID, scoped to the unchanged original presentation.
- Record the source hash and extraction contract version so corrections cannot silently target a different source.
- Return capability flags and reasons for locked elements; do not guess transforms for unsupported shapes.
- Use PowerPoint EMU coordinates as canonical geometry; convert to canvas coordinates using the actual slide dimensions and displayed image rectangle.
- Account for letterboxing, zoom, and pan when mapping pointer positions. Do not assume every presentation is 16:9.
- Selection outlines identify text-box bounds, not individual glyph bounds.

## Corrections and PowerPoint Working Copies

- Store a conversion-owned layout document with a revision and sparse overrides keyed by stable element identity.
- Geometry and supported formatting edits must be validated server-side for type, range, ownership, and capability.
- Preserve all untouched package parts, text, relationships, positioning, and explicit formatting.
- Apply placeholder corrections locally on the selected slide rather than modifying a shared layout/master and affecting other slides.
- Font changes must use renderer-available or validated project fonts. Resolve style explicitly rather than guessing from filenames.
- Apply formatting at the appropriate paragraph/run level; preserve mixed runs and languages unless the author explicitly changes the supported property.
- Reset removes the override and restores the original or inherited value.
- Keep corrections across retries and regeneration. Undo/Redo is an editor-session history; persisted cross-session history is deferred.
- Never cover old text with white rectangles as the primary editing mechanism.

## APIs and Persistence

Proposed authenticated endpoints under `/api/v1/powerpoint-to-scorm`:

| Endpoint | Purpose |
| --- | --- |
| `GET /conversions/{id}/layout` | Extracted elements, effective properties, capabilities, corrections, layout/preparation revisions, and preview status |
| `PUT /conversions/{id}/layout` | Atomic, revision-checked correction save and reset operations |
| `POST /conversions/{id}/layout/previews` | Queue a temporary preview from a saved revision snapshot |
| `GET /conversions/{id}/layout/previews/{preview}` | Owner-only preview state and image references |

The existing explicit render endpoint publishes final images from the saved original plus font, rendering-setting, and layout snapshots.

- A layout PUT requires current layout and preparation revisions and increments both when corrections change.
- Use a serialized save coordinator with existing preparation/authoring saves. Edits made during saving remain dirty.
- Return `409` for stale revisions and forbidden active-operation conflicts rather than overwriting another tab.
- Preview records identify source, layout, preparation/font revisions, generation, processing state, errors, and private output paths.
- Preview creation takes an immutable snapshot under a conversion lock. New edits may continue afterward; a finished old preview is marked outdated and cannot be presented as current approval.
- Prevent font mutations from deleting files used by an active preview through a snapshot-copy or pinning policy.
- Require ownership on documents, operations, status, and preview image access; enforce archived/deleting restrictions.
- Bound preview frequency, concurrency, execution time, and retained generations to avoid unbounded rendering/storage.
- Font/settings changes invalidate previews. An approval is associated with the exact saved preparation/layout revision, never an unsaved canvas state.

## Rendering and Safe Publication

- Reuse the Stage 5 isolated Linux helper on Ubuntu and Windows Docker with a versioned layout-correction contract.
- Use private job directories, selected fonts, private Fontconfig/cache, a fresh LibreOffice profile, and resource-limited argument-array execution.
- Validate correction identities and the original source hash before modifying a working copy.
- Do not promise single-slide rendering until feasibility is verified. The safe baseline is rendering the working presentation and returning the requested preview slide; optimize selected-slide rendering later if inherited assets and relationships remain correct.
- Temporary previews must never replace published slides or invalidate a downloadable package by themselves.
- Saving changed corrections makes published images stale and blocks new package generation until final regeneration succeeds. Existing packages remain downloadable.
- Final generation saves all dirty edits first and snapshots fonts, rendering defaults, and corrections together.
- Preserve the last successful slides/package on failure. Publish only a verified, current generation under a conversion lock.
- Successful publication preserves course settings, questions, multimedia, and course flow and invalidates the old generated package.
- Warn that slide-attached media/hotspots stay at their existing slide coordinates; moving slide text does not automatically move media or triggers.
- Deleted or superseded jobs must exit safely. Project deletion removes correction metadata and temporary previews as well as existing project assets.
- Image-only SCORM packages still contain final images, not uploaded fonts or editable PowerPoint data. No learner-side slide editor is included.

## Implementation Order

1. Fix font-name/style alias resolution and prove real renderer selection with the supplied fonts.
2. Perform a read-only extraction feasibility study of text boxes, placeholders, inheritance, and slide-coordinate mapping.
3. Implement versioned correction storage and working-copy application with source-preservation tests.
4. Add isolated, revision-associated preview jobs and status/image APIs.
5. Build selection, drag/resize, the simple inspector, Undo/Redo, and reset controls.
6. Integrate final generation, stale-image blocking, automatic saving, and project restoration.
7. Complete Arabic/RTL, accessibility, renderer, regression, and Moodle acceptance.

## Tests and Acceptance

- Font aliases select the intended uploaded family/style, including `WinSoft Pro Medium`, without global installation.
- Extraction resolves explicit and inherited properties and reports unsupported elements accurately.
- Coordinate mapping works for non-16:9 slides, letterboxing, desktop/mobile, zoom, pan, and RTL interfaces.
- Drag/resize bounds and keyboard alternatives work without moving unrelated elements.
- Geometry-only edits preserve text, run languages, styles, and untouched PPTX parts.
- Font, wrapping, alignment, direction, and spacing corrections target only selected supported boxes.
- On the supplied Arabic presentation, repair slide 3's overlapping descriptions and compare original/corrected previews with a PowerPoint reference export where available.
- Test ownership, archives, revisions, invalid IDs/geometry, active jobs, rapid edits, stale previews, duplicate requests, offline saves, restoration, and resets.
- Test deleted projects, cleanup, failed previews/regeneration, successful publication, retained downloads, and stale-image package blocking.
- Run real isolated rendering on Ubuntu and Windows Docker, including conflicting-family concurrent projects.
- Verify English/Arabic UI, mixed text, keyboard focus, and responsive layouts visually.
- Preserve Stage 1–5 scoring, resume, multimedia, course-flow, and packaging behavior; verify corrected image-only SCORM output in Moodle.

Do not declare Stage 6 complete based only on selectable outlines or browser text overlays. Completion requires reliable working-copy corrections, renderer-confirmed previews, safe final publication, and the acceptance checks above.

## Deferred Work

Full PowerPoint authoring; text rewriting and rich-text editing; editing grouped/rotated shapes, images, tables, charts, or SmartArt; automatic overlap repair; automatic translation; source replacement; persistent edit history; downloadable corrected PowerPoint export; and guaranteed pixel-identical Microsoft PowerPoint rendering.
