TPDFlibFormSession

Forms, interaction, data types

Description

Maintains AcroForm hit testing, keyboard navigation, focus, editing value and text selection state without depending on a GUI framework

The attached TPDFlib instance remains caller-owned and has to outlive the session

Focus transitions expose Widget /Fo and /Bl actions as typed host callbacks through OnAction

Page rectangles use the visual CropBox after page rotation in the library's current measurement units, with the origin at the visual top left

Directed selections retain independent anchor and caret positions and can be set or queried in UTF-16 code units, Unicode code points or extended grapheme clusters

Bidirectional edits retain logical field-value order while resolving per-line visual caret slots from embedding levels, so physical Left and Right movement follows mixed left-to-right and right-to-left text

Selection replacements dispatch /K to the host, expose the selected and replacement text through OnTextEdit, enforce /MaxLen at complete grapheme boundaries and collapse the selection after one accepted edit

Each active edit keeps a bounded delta history that restores the transient value, display value and directed selection without redispatching form actions or host edit callbacks

DispatchInputEvent converts platform-neutral pointer, wheel, named-key and composed-text records into constrained Widget actions, focus transitions, grapheme-safe editing, button activation and choice navigation

The session retains entered and pressed Widget identity so /E, /X, /D and /U follow PDF trigger ordering even across pointer capture and cancellation

Commits dispatch /V and /F actions, execute their supported bounded JavaScript subset before changing the document and retain the active edit when validation, formatting or a host callback rejects the transaction

The validated raw value is stored in the field while DisplayValue and the generated Widget appearance retain any formatting result

Declaration

type
  TPDFlibFormFieldIndices = array of Integer;

  TPDFlibFormSelectionUnit = (fsuUTF16CodeUnit,
    fsuUnicodeCodePoint, fsuGraphemeCluster);

  TPDFlibFormTextDirection = (ftdAuto,
    ftdLeftToRight, ftdRightToLeft);
  TPDFlibFormCaretIndices = array of Integer;

  TPDFlibFormSelection = record
    IndexUnit: TPDFlibFormSelectionUnit;
    AnchorIndex: Integer;
    CaretIndex: Integer;
    StartIndex: Integer;
    SelectionLength: Integer;
    IsReversed: Boolean;
  end;

  TPDFlibFormSessionActionEvent = procedure(Sender: TObject;
    FieldIndex: Integer; const TriggerEvent: AnsiString;
    const ActionInfo: TPDFlibActionInfo; var Allow: Boolean) of object;
  TPDFlibFormSessionFocusEvent = procedure(Sender: TObject;
    OldFieldIndex, NewFieldIndex: Integer) of object;
  TPDFlibFormSessionValueEvent = procedure(Sender: TObject;
    FieldIndex: Integer; const OldValue, NewValue: WideString) of object;
  TPDFlibFormEditKind = (fekReplaceSelection,
    fekCutSelection, fekPasteText);
  TPDFlibFormSessionTextEditEvent = procedure(Sender: TObject;
    FieldIndex: Integer; EditKind: TPDFlibFormEditKind;
    SelectionStart, SelectionLength: Integer;
    const SelectedText: WideString; var ReplacementText: WideString;
    var Allow: Boolean) of object;

  TPDFlibFormInputEventKind = (fiekPointerMove,
    fiekPointerDown, fiekPointerUp, fiekPointerDoubleClick,
    fiekPointerLeave, fiekPointerCancel, fiekWheel,
    fiekKeyDown, fiekKeyUp, fiekTextInput);
  TPDFlibFormInputModifiers = set of TPDFlibFormInputModifier;

  TPDFlibFormInputEvent = record
    Kind: TPDFlibFormInputEventKind;
    Modifiers: TPDFlibFormInputModifiers;
    Button: TPDFlibFormInputButton;
    Key: TPDFlibFormInputKey;
    Page: Integer;
    X, Y: Double;
    WheelDeltaX, WheelDeltaY: Double;
    Text: WideString;
  end;

  TPDFlibFormSession = class
  public
    constructor Create(ALibrary: TPDFlib);
    procedure AttachLibrary(ALibrary: TPDFlib);
    procedure Reset;
    function FocusField(FieldIndex: Integer;
      CommitCurrent: Boolean = True): Integer;
    function GetFieldPageRect(FieldIndex: Integer; out Page: Integer;
      out Left, Top, Width, Height: Double): Integer;
    function HitTest(Page: Integer; X, Y: Double): Integer;
    function GetTabSequence(out FieldIndices: TPDFlibFormFieldIndices): Integer;
    function FocusAt(Page: Integer; X, Y: Double;
      CommitCurrent: Boolean = True): Integer;
    function FocusNext(Backwards: Boolean = False;
      WrapAround: Boolean = True; CommitCurrent: Boolean = True): Integer;
    function Blur(CommitCurrent: Boolean = True): Integer;
    function BeginEdit(FieldIndex: Integer): Integer;
    function SetEditValue(const NewValue: WideString): Integer;
    function SetSelection(StartIndex, SelectionLength: Integer): Integer;
    function SetSelectionRange(AnchorIndex, CaretIndex: Integer;
      IndexUnit: TPDFlibFormSelectionUnit): Integer;
    function GetSelectionRange(IndexUnit: TPDFlibFormSelectionUnit;
      out Selection: TPDFlibFormSelection): Integer;
    function SetTextDirection(
      Direction: TPDFlibFormTextDirection): Integer;
    function GetVisualCaretOrder(IndexUnit: TPDFlibFormSelectionUnit;
      out CaretIndices: TPDFlibFormCaretIndices): Integer;
    function MoveVisualCaret(ToRight: Boolean;
      ExtendSelection: Boolean = False): Integer;
    function GetSelectedText: WideString;
    function ReplaceSelection(const ReplacementText: WideString): Integer;
    function CutSelection(out CutText: WideString): Integer;
    function PasteText(const Text: WideString): Integer;
    function CanUndoEdit: Boolean;
    function CanRedoEdit: Boolean;
    function UndoEdit: Integer;
    function RedoEdit: Integer;
    procedure ClearEditHistory;
    function DispatchInputEvent(
      const InputEvent: TPDFlibFormInputEvent;
      out InputResult: TPDFlibFormInputResult): Integer;
    function CommitEdit: Integer;
    procedure CancelEdit;
    property TextDirection: TPDFlibFormTextDirection;
    property ResolvedTextDirection: TPDFlibFormTextDirection;
    property VisualCaretPosition: Integer;
    property MaxUndoSteps: Integer;
    property UndoEditCount: Integer;
    property RedoEditCount: Integer;
    property HoveredFieldIndex: Integer;
    property PressedFieldIndex: Integer;
  end;

Methods

CreateCreates a session attached to a caller-owned library instance
AttachLibraryResets all transient state and attaches another caller-owned library instance, or nil
ResetClears focus, edit and selection state without changing field values or dispatching actions
FocusFieldCommits or cancels the current edit, dispatches /Bl for the previous Widget and then dispatches /Fo for the requested visible Widget
GetFieldPageRectReturns a visible Widget rectangle in rotated visual CropBox coordinates without changing the selected page
HitTestReturns the topmost visible Widget at a visual page point, using later entries in the page /Annots array as the frontmost hit
GetTabSequenceReturns visible Widgets across pages in page order and applies /Tabs /R, /C, /S, PDF 2.0 /A and /W semantics, page rotation and ViewerPreferences /Direction; a missing or invalid /Tabs value uses annotation-array order
FocusAtHit-tests a visual page point and focuses the returned Widget through the normal commit, blur and focus action path
FocusNextMoves forward or backward through the computed tab sequence with optional wraparound and the normal focus transition rules
BlurCommits or cancels the current edit and dispatches /Bl before clearing focus
BeginEditFocuses an editable text or choice field and snapshots its original value
SetEditValueUpdates the transient value and enforces a text field's configured maximum length without dividing an extended grapheme cluster
SetSelectionClamps and stores a zero-based UTF-16 selection range within the transient value
SetSelectionRangeClamps directed anchor and caret positions in the requested index unit, converts them to the internal UTF-16 range and never divides a code point or grapheme cluster when either Unicode unit is used
GetSelectionRangeReturns anchor, caret, normalised start and length in the requested index unit together with the original direction
SetTextDirectionSelects automatic, explicit left-to-right or explicit right-to-left paragraph direction and invalidates the cached visual caret order
GetVisualCaretOrderReturns grapheme-safe logical caret indexes in physical left-to-right order, including distinct split slots at mixed-direction boundaries
MoveVisualCaretMoves or extends the directed selection by one physical visual slot and collapses existing selections towards the requested physical edge
GetSelectedTextReturns the currently selected UTF-16 text or an empty string
ReplaceSelectionReplaces the normalised selection through one vetoable /K and OnTextEdit transaction, then collapses the caret after the accepted replacement
CutSelectionReturns and removes the selected text through the same atomic replacement path
PasteTextReplaces the current selection with caller-supplied clipboard text without introducing a platform clipboard dependency
CanUndoEditReports whether the active edit has a history entry that can be reversed
CanRedoEditReports whether the active edit has a reversed history entry that can be replayed
UndoEditReverses the latest retained edit and restores its previous directed selection
RedoEditReplays the next retained edit and restores its resulting directed selection
ClearEditHistoryDiscards the active edit's undo and redo history without changing its current value or selection
DispatchInputEventDispatches one platform-neutral pointer, wheel, key or composed-text event and returns the resulting focus, hover, press, value and selection state
CommitEditValidates and formats a candidate before storing its raw value, refreshes the formatted appearance and then raises OnValueChanged
CancelEditDiscards the transient value and selection without changing the field

State properties

LibraryInstanceCurrent non-owned TPDFlib instance
FocusedFieldIndexFocused field or temporary Widget index, or zero when no Widget has focus
EditingFieldIndexBase text or choice field being edited, or zero when no edit is active
OriginalValueField value captured by BeginEdit
EditValueCurrent transient value
DisplayValueCurrent edit value or the formatted display value produced by the latest successful commit
SelectionStartZero-based UTF-16 start index
SelectionLengthUTF-16 selection length
SelectionAnchorZero-based UTF-16 anchor position that remains fixed while the caret extends a directed selection
SelectionCaretZero-based UTF-16 moving edge of the directed selection
TextDirectionConfigured direction, defaulting to ftdAuto and retained across edits in the session
ResolvedTextDirectionExplicit direction or the automatic direction selected from the active edit value's first strong character
VisualCaretPositionCurrent slot in the cached physical caret order, or -1 when no visual move has selected a slot
MaxUndoStepsMaximum retained edit-history entries from 0 through 10000; the default is 1000 and zero disables recording
UndoEditCountNumber of retained entries currently available to UndoEdit
RedoEditCountNumber of retained entries currently available to RedoEdit
ModifiedTrue when EditValue differs from OriginalValue
HoveredFieldIndexWidget with a currently active pointer-enter state, or zero
PressedFieldIndexWidget retaining primary-pointer capture until matching up or pointer cancellation, or zero

Events

OnActionReceives a typed TPDFlibActionInfo for available focus, blur, keystroke, validation and formatting actions; set Allow to False to veto the pending operation
OnFocusChangedReports each completed focus transition, including transitions to zero after a new focus action is vetoed
OnValueChangedReports a successfully committed value change after the field and its dirty appearances have been updated
OnTextEditReceives the edit kind, UTF-16 selection, selected text and mutable replacement before the transient value changes; set Allow to False for an atomic rejection

Return values

State-changing functions return 1 on success and 0 when the request is invalid, reentrant, vetoed or cannot be committed; HitTest returns a field or temporary Widget index and GetTabSequence returns the number of entries

Selection units

fsuUTF16CodeUnit preserves the legacy zero-based WideString indexing contract, including positions inside a surrogate pair when explicitly requested

fsuUnicodeCodePoint counts a valid surrogate pair as one supplementary code point and treats an unpaired surrogate as one standalone code point

fsuGraphemeCluster counts complete extended grapheme clusters so combining sequences and joined emoji remain indivisible

Unicode boundary tables are cached for the current edit value and invalidated when that value changes

Bidirectional navigation

ftdAuto uses the first strong character and defaults to left-to-right when the edit has no strong directional character

Visual run order is resolved independently for each line and does not alter the logical UTF-16 field value, PDF string or text alignment

A logical index can occupy two distinct visual slots at a mixed-direction boundary, so VisualCaretPosition disambiguates repeated movement through that boundary

Example

var
  Session: TPDFlibFormSession;
  Selection: TPDFlibFormSelection;
begin
  Session := TPDFlibFormSession.Create(PDF);
  try
    if Session.FocusAt(PageNumber, MouseX, MouseY) = 1 then
      Session.FocusNext(False, True);
    if Session.BeginEdit(Session.FocusedFieldIndex) = 1 then
    begin
      Session.SetEditValue('A' + WideChar($D83D) + WideChar($DE00) + 'B');
      Session.SetSelectionRange(1, 2, fsuUnicodeCodePoint);
      Session.GetSelectionRange(fsuUTF16CodeUnit, Selection);
      Session.SetTextDirection(ftdAuto);
      Session.MoveVisualCaret(True, True);
      Session.PasteText('replacement');
      if Session.CanUndoEdit then
        Session.UndoEdit;
      if Session.CanRedoEdit then
        Session.RedoEdit;
      Session.CommitEdit;
    end;
  finally
    Session.Free;
  end;
end;

See also

SetTextDirection, GetVisualCaretOrder, MoveVisualCaret, TPDFlibFormTextDirection, DispatchInputEvent, TPDFlibFormInputEvent, TPDFlibFormInputResult, UndoEdit, RedoEdit, ClearEditHistory, ReplaceSelection, CutSelection, PasteText, TPDFlibFormEditKind, SetSelectionRange, GetSelectionRange, ExecuteFormFieldScript, TPDFlibActionInfo