import { EngineError, EngineErrorCode, pressPatchOf, takesImageOf, WIDGET_ACTION_EVENTS, type AnnotationRef, type WidgetPress, type FormFieldWidget, type PdfActionTree, type PdfDestination, type PressEvent, type PressWrite, } from '@embedpdf/engine-core/runtime'; import type { PdfRuntimeModule, Ptr } from '@embedpdf/engine-runtime'; import type { DocumentSession } from '../../../document-session/DocumentSession'; import { ActionReadBudgetTracker, readActionModel } from '../../actions/ActionModelReader'; import { writeWidgetActions } from '../../actions/internal/writeWidgetActions'; import { openAnnotRaw } from '../../annotations/internal/identity/resolveAnnotIndexRaw'; /** `EPDF_MK_ICON_I`: a push button's normal icon, the one its appearance draws. */ export const MK_ICON_NORMAL = 0; /** * Page indexes by page object number, for reading widgets raw from a field * read, which has the document and no session: the page list is read once, * on the first lookup, and only then. One lookup serves a whole read of the * form. */ export class PageIndexLookup { private indexes: Map | null = null; constructor( private readonly runtime: PdfRuntimeModule, private readonly docPtr: Ptr, ) {} /** The index of the page whose object number this is, or -1. */ indexOf(pageObjectNumber: number): number { if (!this.indexes) { const { fn } = this.runtime; const indexes = new Map(); const count = fn.FPDF_GetPageCount(this.docPtr); for (let index = 0; index < count; index++) { const objectNumber = fn.EPDFDoc_GetPageObjectNumberByIndex(this.docPtr, index); if (objectNumber > 0 && !indexes.has(objectNumber)) indexes.set(objectNumber, index); } this.indexes = indexes; } return this.indexes.get(pageObjectNumber) ?? -1; } } /** * Whether a push button holds an image: one of its widgets has an icon * (`/MK /I`, a form XObject of the document), whoever put it there. Each * widget is opened from its page's `/Annots` without loading the page; a * widget on no page shows nothing, so it holds none. */ export function readButtonHasImage( runtime: PdfRuntimeModule, docPtr: Ptr, widgets: readonly FormFieldWidget[], pages: PageIndexLookup, ): boolean { const { fn } = runtime; return widgets.some( (widget) => readWidgetRaw( runtime, docPtr, widget, pages, (annotPtr) => fn.EPDFAnnot_GetMKIcon(annotPtr, MK_ICON_NORMAL) !== 0, ) ?? false, ); } /** * What `read` says of a widget, opened from its page's `/Annots` without * loading the page; `null` for a widget that can't be opened that way: one * on no page, or stored inline in its page. */ function readWidgetRaw( runtime: PdfRuntimeModule, docPtr: Ptr, widget: FormFieldWidget, pages: PageIndexLookup, read: (annotPtr: Ptr) => T, ): T | null { const { fn } = runtime; if (!widget.page || widget.objectNumber <= 0) return null; const pageIndex = pages.indexOf(widget.page.objectNumber); if (pageIndex < 0) return null; const index = fn.EPDFPage_GetAnnotIndexByObjectNumberRaw(docPtr, pageIndex, widget.objectNumber); if (index < 0) return null; const annotPtr = fn.EPDFPage_GetAnnotRaw(docPtr, pageIndex, index); if (!annotPtr) return null; try { return read(annotPtr); } finally { fn.FPDFPage_CloseAnnot(annotPtr); } } /** An event's code is its place in `WIDGET_ACTION_EVENTS` (`EPDF_ANNOT_ACTION_*`). */ const eventCode = (event: PressEvent): number => WIDGET_ACTION_EVENTS.indexOf(event); /** How an action reads when its tree is past what one read takes: there, and not to be run. */ const UNREAD_ACTION: PdfActionTree = { root: null, incomplete: true, warnings: ['incomplete'], }; /** * Each widget's press, in `widgets` order: its activation action (`/A`) and * its mouse-up action (`/AA /U`), the two a click runs. `null` for a widget * that can't be opened ({@link readWidgetRaw}). The trees are read to * decide a fact and then dropped, so each widget has a budget of its own, * and a form with many buttons never runs out of one; an action past a * widget's budget reads as there and incomplete. */ export function readButtonPresses( runtime: PdfRuntimeModule, docPtr: Ptr, widgets: readonly FormFieldWidget[], pages: PageIndexLookup, ): (WidgetPress | null)[] { const { fn, mem } = runtime; return widgets.map((widget) => readWidgetRaw(runtime, docPtr, widget, pages, (annotPtr): WidgetPress => { const budget = new ActionReadBudgetTracker(); const press: WidgetPress = {}; for (const event of ['activate', 'mouseUp'] as const) { const model = fn.EPDFAnnot_GetActionModel(annotPtr, eventCode(event)); try { const tree = readActionModel(fn, mem, docPtr, model, budget); if (tree) press[event] = tree; } catch (error) { if (!EngineError.is(error) || error.code !== EngineErrorCode.MalformedPdf) throw error; press[event] = UNREAD_ACTION; } } return press; }), ); } /** * Whether a push button takes an image: it has a widget, and every widget's * press is Acrobat's import-icon script and nothing else (`takesImageOf`). A * widget whose press can't be read makes it none. */ export function readButtonTakesImage( runtime: PdfRuntimeModule, docPtr: Ptr, widgets: readonly FormFieldWidget[], pages: PageIndexLookup, ): boolean { return takesImageOf(readButtonPresses(runtime, docPtr, widgets, pages)); } /** * Write what a `takesImage` write does to one widget (`pressWriteOf`): the * import-icon script as its activation action, or the event that holds the * script emptied. The widget's other actions are left alone. */ export function writeWidgetPress( runtime: PdfRuntimeModule, session: DocumentSession, widget: AnnotationRef, write: Exclude, ): void { const annotPtr = openAnnotRaw(runtime, session, widget); try { writeWidgetActions(runtime, session.requireDocPtr(), annotPtr, pressPatchOf(write)); } finally { runtime.fn.FPDFPage_CloseAnnot(annotPtr); } } /** * Make a push button's widget show `drawing` as its icon (`/MK /I`) and draw * its look again from it, or, with `0`, take the icon out and draw its box * again. A widget without an icon is left as it is by `0`, and one that * names `drawing` already by `drawing`. The widget is opened from its page's * `/Annots`, without loading the page. */ export function setWidgetIcon( runtime: PdfRuntimeModule, session: DocumentSession, widget: AnnotationRef, drawing: number, ): void { const { fn } = runtime; const annotPtr = openAnnotRaw(runtime, session, widget); try { const current = fn.EPDFAnnot_GetMKIcon(annotPtr, MK_ICON_NORMAL); if (current === drawing) return; const written = drawing === 0 ? fn.EPDFAnnot_ClearMKIcon(annotPtr, MK_ICON_NORMAL) : fn.EPDFAnnot_SetMKIcon(annotPtr, MK_ICON_NORMAL, drawing); if (!written) { throw new EngineError( EngineErrorCode.Unknown, "the push button's icon (/MK /I) could not be written", ); } if (!fn.EPDFAnnot_GenerateFormFieldAP(annotPtr)) { throw new EngineError(EngineErrorCode.Unknown, "the push button's look could not be drawn"); } } finally { fn.FPDFPage_CloseAnnot(annotPtr); } } /** * The drawing a push button's widget shows as its icon (`/MK /I`), by object * number, or 0 for none. The widget is opened raw. */ export function readWidgetIcon( runtime: PdfRuntimeModule, session: DocumentSession, widget: AnnotationRef, ): number { const annotPtr = openAnnotRaw(runtime, session, widget); try { return runtime.fn.EPDFAnnot_GetMKIcon(annotPtr, MK_ICON_NORMAL); } finally { runtime.fn.FPDFPage_CloseAnnot(annotPtr); } }