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
| Create | Creates a session attached to a caller-owned library instance |
|---|---|
| AttachLibrary | Resets all transient state and attaches another caller-owned library instance, or nil |
| Reset | Clears focus, edit and selection state without changing field values or dispatching actions |
| FocusField | Commits or cancels the current edit, dispatches /Bl for the previous Widget and then dispatches /Fo for the requested visible Widget |
| GetFieldPageRect | Returns a visible Widget rectangle in rotated visual CropBox coordinates without changing the selected page |
| HitTest | Returns the topmost visible Widget at a visual page point, using later entries in the page /Annots array as the frontmost hit |
| GetTabSequence | Returns 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 |
| FocusAt | Hit-tests a visual page point and focuses the returned Widget through the normal commit, blur and focus action path |
| FocusNext | Moves forward or backward through the computed tab sequence with optional wraparound and the normal focus transition rules |
| Blur | Commits or cancels the current edit and dispatches /Bl before clearing focus |
| BeginEdit | Focuses an editable text or choice field and snapshots its original value |
| SetEditValue | Updates the transient value and enforces a text field's configured maximum length without dividing an extended grapheme cluster |
| SetSelection | Clamps and stores a zero-based UTF-16 selection range within the transient value |
| SetSelectionRange | Clamps 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 |
| GetSelectionRange | Returns anchor, caret, normalized start and length in the requested index unit together with the original direction |
| SetTextDirection | Selects automatic, explicit left-to-right or explicit right-to-left paragraph direction and invalidates the cached visual caret order |
| GetVisualCaretOrder | Returns grapheme-safe logical caret indexes in physical left-to-right order, including distinct split slots at mixed-direction boundaries |
| MoveVisualCaret | Moves or extends the directed selection by one physical visual slot and collapses existing selections toward the requested physical edge |
| GetSelectedText | Returns the currently selected UTF-16 text or an empty string |
| ReplaceSelection | Replaces the normalized selection through one vetoable /K and OnTextEdit transaction, then collapses the caret after the accepted replacement |
| CutSelection | Returns and removes the selected text through the same atomic replacement path |
| PasteText | Replaces the current selection with caller-supplied clipboard text without introducing a platform clipboard dependency |
| CanUndoEdit | Reports whether the active edit has a history entry that can be reversed |
| CanRedoEdit | Reports whether the active edit has a reversed history entry that can be replayed |
| UndoEdit | Reverses the latest retained edit and restores its previous directed selection |
| RedoEdit | Replays the next retained edit and restores its resulting directed selection |
| ClearEditHistory | Discards the active edit's undo and redo history without changing its current value or selection |
| DispatchInputEvent | Dispatches one platform-neutral pointer, wheel, key or composed-text event and returns the resulting focus, hover, press, value and selection state |
| CommitEdit | Validates and formats a candidate before storing its raw value, refreshes the formatted appearance and then raises OnValueChanged |
| CancelEdit | Discards the transient value and selection without changing the field |
State properties
| LibraryInstance | Current non-owned TPDFlib instance |
|---|---|
| FocusedFieldIndex | Focused field or temporary Widget index, or zero when no Widget has focus |
| EditingFieldIndex | Base text or choice field being edited, or zero when no edit is active |
| OriginalValue | Field value captured by BeginEdit |
| EditValue | Current transient value |
| DisplayValue | Current edit value or the formatted display value produced by the latest successful commit |
| SelectionStart | Zero-based UTF-16 start index |
| SelectionLength | UTF-16 selection length |
| SelectionAnchor | Zero-based UTF-16 anchor position that remains fixed while the caret extends a directed selection |
| SelectionCaret | Zero-based UTF-16 moving edge of the directed selection |
| TextDirection | Configured direction, defaulting to ftdAuto and retained across edits in the session |
| ResolvedTextDirection | Explicit direction or the automatic direction selected from the active edit value's first strong character |
| VisualCaretPosition | Current slot in the cached physical caret order, or -1 when no visual move has selected a slot |
| MaxUndoSteps | Maximum retained edit-history entries from 0 through 10000; the default is 1000 and zero disables recording |
| UndoEditCount | Number of retained entries currently available to UndoEdit |
| RedoEditCount | Number of retained entries currently available to RedoEdit |
| Modified | True when EditValue differs from OriginalValue |
| HoveredFieldIndex | Widget with a currently active pointer-enter state, or zero |
| PressedFieldIndex | Widget retaining primary-pointer capture until matching up or pointer cancellation, or zero |
Events
| OnAction | Receives a typed TPDFlibActionInfo for available focus, blur, keystroke, validation and formatting actions; set Allow to False to veto the pending operation |
|---|---|
| OnFocusChanged | Reports each completed focus transition, including transitions to zero after a new focus action is vetoed |
| OnValueChanged | Reports a successfully committed value change after the field and its dirty appearances have been updated |
| OnTextEdit | Receives 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