# Print Renderer Module data flow

## What It Does
- Summary: Coordinates sheet printing by rasterizing sheet content to canvases, handling pagination, charts and images, measuring text/wrap, and opening a print preview window. Implements page-splitting, row/column headers, gridline drawing and style-aware borders. See `src/spreadsheet/renderer/print.ts`.

## Entry Points (UI / Core)
- UI (Renderer):
  - `Print.print(spreadsheet, printOptions)` — main entry; starts printing for active sheet or workbook.
  - `Print.canvasPrint(spreadSheet, sheetIndex, printOptions)` — finalizes canvases and triggers browser print window.
  - `Print.destroy()` / `getModuleName()` — lifecycle and identification.
- Core (Worker/Utilities):
  - `Print.activeSheetPrint(...)` — prepares pagination and begins rasterization (`processCell`).
  - `Print.processCell(...)` — core raster loop: creates canvases, walks rows/columns, draws cells, borders, headers.
  - `Print.handleCharts(...)` / `Print.processImages(...)` — asynchronously load and render charts/images into canvases.
  - `Print.calculatePageCount(...)`, `calculateTextPosition(...)`, `wrapText(...)` — layout helpers for page splits and text wrapping.
  - `Print.drawBorder(...)`, `drawPath(...)`, `drawDoubleBorder(...)` — style-aware border rendering on canvas.

## Core Logic Flow (ASCII)
User triggers print → `Print.print()`
         ↓
If workbook: collect visible sheets and request data updates (`updateSheetFromDataSource`) if needed
         ↓
Compute page columns via `calculatePageCount` and row bounds via `updateChartRowAndColumnIndices`
         ↓
Rasterize by pages: `activeSheetPrint` → `processCell` loops rows → draws headers/cells/borders
         ↓
If cell contains chart/image: `handleCharts` / `processImages` load media asynchronously and re-enter `processCell` when ready
         ↓
Collect canvases as data URLs (`multipleCanvasDataURL`) and when done call `canvasPrint` to open preview and invoke `window.print()`

## Operations Handled (functions & implementation notes)
- `print()`:
  - Sets `isPrintingProcessing`, clears internal buffers, iterates visible sheets and optionally waits for data source updates.
- `updateChartRowAndColumnIndices()`:
  - Computes row/col used range and expands bounds to include charts positioned beyond usedRange.
- `activeSheetPrint()`:
  - Sets `pageCounts` (columns per page) then invokes `processCell` starting at row 0.
- `processCell()`:
  - Creates canvases sized to fixed page dimensions (1000×1100 in code), sets font baseline, and iterates rows until page height is exceeded.
  - Tracks `currentX/currentY` for each column and handles row/column headers, spans, hidden columns/rows, and gridlines.
  - On page overflow, serializes current canvas with `toDataURL()` and continues on a new canvas.
  - Calls `drawBorder` and `drawPath` to render complex styles (dashed/dotted/double) and handles per-cell style overrides via `setBorderStyle`.
- Media handling:
  - `handleCharts` clones chart DOM, converts SVG to blob URL, draws image into canvas and continues the raster when all charts/images finish loading.
  - `processImages` loads images with onload/onerror handlers; `imageLoadedCount` and `totalImages` prevent indefinite waits on failures.
- Pagination & layout helpers:
  - `calculatePageCount` determines column breakpoints to fit a fixed canvas width.
  - `wrapText` and `calculateTextPosition` measure and wrap text using canvas metrics and DPR-aware sizing utilities.

## Validation & Safety
- Async media guards: tracks `totalCharts`/`chartLoadedCount` and `totalImages`/`imageLoadedCount` to resume processing only when all media are ready.
- Image error handling: `onerror` increments counters so printing proceeds even if images fail to load.
- Hidden rows/columns: respects `hidden` flags when computing widths/heights and when deciding to draw headers or cells.
- Page overflow handling: splits content across canvases and adjusts `currentY` offsets to avoid lost content.
- Data synchronization: for workbook prints with data-sources, notifies `updateSheetFromDataSource` and delays printing (uses a short timer) to ensure data is applied.

## Desired Outputs
- User-Facing:
  - Printed pages showing gridlines, row/column headers (if enabled), charts/images, wrapped text, and styled borders.
  - Browser print preview with one canvas per printed page; clean page breaks and preserved visual fidelity.
  - Non-blocking UX: print process updates `isPrintingProcessing` and recovers on media load errors.
- System-Level:
  - Internal buffers: `multipleCanvasDataURL` (page images), `pageCounts`, `chartElements` (temporary DOM overlay ids), `currentPrintSheetIndex`.
  - Flags and counters: `isChartLoaded`, `isImageLoaded`, `totalCharts`, `totalImages`, `chartLoadedCount`, `imageLoadedCount`.
  - DOM interactions: clones chart elements and may insert overlays via `parent.insertChart`; will remove overlays after printing.
  - Events/Notifications: uses `parent.notify(updateSheetFromDataSource, ...)`, `getRowIdxFromClientY`, `getColIdxFromClientX` to compute layout; sets `spreadsheet.isPrintingProcessing` to coordinate UI state.
  - Undo/Redo: printing is read-only; no undo/redo records required, but model-updating operations triggered prior to print (e.g., `updateSheetFromDataSource`) should generate their own records.