//========================================================================
//
// Form.cc
//
// This file is licensed under the GPLv2 or later
//
// Copyright 2006-2008 Julien Rebetez <julienr@svn.gnome.org>
// Copyright 2007-2012, 2015-2026 Albert Astals Cid <aacid@kde.org>
// Copyright 2007-2008, 2011 Carlos Garcia Campos <carlosgc@gnome.org>
// Copyright 2007, 2013, 2016, 2019, 2022 Adrian Johnson <ajohnson@redneon.com>
// Copyright 2007 Iñigo Martínez <inigomartinez@gmail.com>
// Copyright 2008, 2011 Pino Toscano <pino@kde.org>
// Copyright 2008 Michael Vrable <mvrable@cs.ucsd.edu>
// Copyright 2009 Matthias Drochner <M.Drochner@fz-juelich.de>
// Copyright 2009 KDAB via Guillermo Amaral <gamaral@amaral.com.mx>
// Copyright 2010, 2012 Mark Riedesel <mark@klowner.com>
// Copyright 2012 Fabio D'Urso <fabiodurso@hotmail.it>
// Copyright 2015 André Guerreiro <aguerreiro1985@gmail.com>
// Copyright 2015 André Esser <bepandre@hotmail.com>
// Copyright 2017 Hans-Ulrich Jüttner <huj@froreich-bioscientia.de>
// Copyright 2017 Bernd Kuhls <berndkuhls@hotmail.com>
// Copyright 2018 Andre Heinecke <aheinecke@intevation.de>
// Copyright 2018 Klarälvdalens Datakonsult AB, a KDAB Group company, <info@kdab.com>. Work sponsored by the LiMux project of the city of Munich
// Copyright 2018 Chinmoy Ranjan Pradhan <chinmoyrp65@protonmail.com>
// Copyright 2018 Adam Reichold <adam.reichold@t-online.de>
// Copyright 2018-2022, 2026 Nelson Benítez León <nbenitezl@gmail.com>
// Copyright 2019, 2020 2024, Oliver Sander <oliver.sander@tu-dresden.de>
// Copyright 2019 Tomoyuki Kubota <himajin100000@gmail.com>
// Copyright 2019 João Netto <joaonetto901@gmail.com>
// Copyright 2020-2022 Marek Kasik <mkasik@redhat.com>
// Copyright 2020 Thorsten Behrens <Thorsten.Behrens@CIB.de>
// Copyright 2020, 2023, 2024 Klarälvdalens Datakonsult AB, a KDAB Group company, <info@kdab.com>. Work sponsored by Technische Universität Dresden
// Copyright 2021 Georgiy Sgibnev <georgiy@sgibnev.com>. Work sponsored by lab50.net.
// Copyright 2021 Theofilos Intzoglou <int.teo@gmail.com>
// Copyright 2021 Even Rouault <even.rouault@spatialys.com>
// Copyright 2022 Alexander Sulfrian <asulfrian@zedat.fu-berlin.de>
// Copyright 2022, 2024 Erich E. Hoover <erich.e.hoover@gmail.com>
// Copyright 2023-2026 g10 Code GmbH, Author: Sune Stolborg Vuorela <sune@vuorela.dk>
// Copyright 2024 Pratham Gandhi <ppg.1382@gmail.com>
// Copyright 2024 Vincent Lefevre <vincent@vinc17.net>
// Copyright 2025, 2026 Juraj Šarinay <juraj@sarinay.com>
// Copyright 2025 Blair Bonnett <blair.bonnett@gmail.com>
// Copyright 2025 Jonathan Hähne <jonathan.haehne@hotmail.com>
// Copyright 2026 Stefan Brüns <stefan.bruens@rwth-aachen.de>
//
//========================================================================

#include <config.h>

#include <array>
#include <set>
#include <limits>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include "goo/ft_utils.h"
#include "goo/gfile.h"
#include "goo/GooString.h"
#include "Error.h"
#include "ErrorCodes.h"
#include "CharCodeToUnicode.h"
#include "Object.h"
#include "Array.h"
#include "Dict.h"
#include "Gfx.h"
#include "GfxFont.h"
#include "GlobalParams.h"
#include "Form.h"
#include "PDFDoc.h"
#include "DateInfo.h"
#include "CryptoSignBackend.h"
#include "SignatureInfo.h"
#include "CertificateInfo.h"
#include "XRef.h"
#include "PDFDocEncoding.h"
#include "Annot.h"
#include "Link.h"
#include "Lexer.h"
#include "CIDFontsWidthsBuilder.h"
#include "UTF.h"

#include "fofi/FoFiTrueType.h"
#include "fofi/FoFiIdentifier.h"

#include <ft2build.h>
#include <variant>
#include FT_FREETYPE_H
#include <unordered_set>

// helper for using std::visit to get a dependent false for static_asserts
// to help get compile errors if one ever extends variants
template<class>
inline constexpr bool always_false_v = false;

// return a newly allocated char* containing an UTF16BE string of size length
std::string pdfDocEncodingToUTF16(const std::string &orig)
{
    // double size, a unicode char takes 2 char, add 2 for the unicode marker
    int length = 2 + 2 * orig.size();
    std::string result;
    result.reserve(length);
    // unicode marker
    result.push_back('\xfe');
    result.push_back('\xff');
    // convert to utf16
    for (int i = 2, j = 0; i < length; i += 2, j++) {
        Unicode u = pdfDocEncoding[static_cast<unsigned int>(static_cast<unsigned char>(orig[j]))] & 0xffff;
        result.push_back((u >> 8) & 0xff);
        result.push_back(u & 0xff);
    }
    return result;
}

static std::unique_ptr<GooString> convertToUtf16(GooString *pdfDocEncodingString)
{
    std::string tmpStr = pdfDocEncodingToUTF16(pdfDocEncodingString->toStr());
    return std::make_unique<GooString>(tmpStr.c_str() + 2, tmpStr.size() - 2); // Remove the unicode BOM
}

FormWidget::FormWidget(PDFDoc *docA, Object *aobj, unsigned num, Ref aref, FormField *fieldA)
{
    ref = aref;
    ID = 0;
    childNum = num;
    doc = docA;
    xref = doc->getXRef();
    obj = aobj->copy();
    type = formUndef;
    field = fieldA;
    widget = nullptr;
}

FormWidget::~FormWidget() = default;

void FormWidget::print(int indent) const
{
    printf("%*s+ (%d %d): [widget]\n", indent, "", ref.num, ref.gen);
}

void FormWidget::createWidgetAnnotation()
{
    if (widget) {
        return;
    }

    Object obj1(ref);
    widget = std::make_shared<AnnotWidget>(doc, &obj, &obj1, field);
}

bool FormWidget::inRect(double x, double y) const
{
    return widget ? widget->inRect(x, y) : false;
}

void FormWidget::getRect(double *x1, double *y1, double *x2, double *y2) const
{
    if (widget) {
        widget->getRect(x1, y1, x2, y2);
    }
}

bool FormWidget::isReadOnly() const
{
    return field->isReadOnly();
}

void FormWidget::setReadOnly(bool value)
{
    field->setReadOnly(value);
}

int FormWidget::encodeID(unsigned pageNum, unsigned fieldNum)
{
    return (pageNum << 4 * sizeof(unsigned)) + fieldNum;
}

void FormWidget::decodeID(unsigned id, unsigned *pageNum, unsigned *fieldNum)
{
    *pageNum = id >> 4 * sizeof(unsigned);
    *fieldNum = (id << 4 * sizeof(unsigned)) >> 4 * sizeof(unsigned);
}

const GooString *FormWidget::getPartialName() const
{
    return field->getPartialName();
}

void FormWidget::setPartialName(const GooString &name)
{
    field->setPartialName(name);
}

const GooString *FormWidget::getAlternateUiName() const
{
    return field->getAlternateUiName();
}

const GooString *FormWidget::getMappingName() const
{
    return field->getMappingName();
}

const GooString *FormWidget::getFullyQualifiedName()
{
    return field->getFullyQualifiedName();
}

const LinkAction *FormWidget::getActivationAction()
{
    return widget ? widget->getAction() : nullptr;
}

std::unique_ptr<LinkAction> FormWidget::getAdditionalAction(Annot::FormAdditionalActionsType t)
{
    return widget ? widget->getFormAdditionalAction(t) : nullptr;
}

bool FormWidget::setAdditionalAction(Annot::FormAdditionalActionsType t, const std::string &js)
{
    if (!widget) {
        return false;
    }

    return widget->setFormAdditionalAction(t, js);
}

FormWidgetButton::FormWidgetButton(PDFDoc *docA, Object *dictObj, unsigned num, Ref refA, FormField *p) : FormWidget(docA, dictObj, num, refA, p)
{
    type = formButton;

    // Find the name of the ON state in the AP dictionary
    // The reference say the Off state, if it exists, _must_ be stored in the AP dict under the name /Off
    // The "on" state may be stored under any other name
    Object obj1 = obj.dictLookup("AP");
    if (obj1.isDict()) {
        Object obj2 = obj1.dictLookup("N");
        if (obj2.isDict()) {
            Dict *dictN = obj2.getDict();
            for (int i = 0; i < dictN->getLength(); i++) {
                const std::string &key = dictN->getKey(i);
                if (key != "Off") {
                    onStr = std::make_unique<GooString>(key);
                    break;
                }
            }
        }
    }
}

const char *FormWidgetButton::getOnStr() const
{
    if (onStr) {
        return onStr->c_str();
    }

    // 12.7.4.2.3 Check Boxes
    //  Yes should be used as the name for the on state
    return parent()->getButtonType() == formButtonCheck ? "Yes" : nullptr;
}

FormWidgetButton::~FormWidgetButton() = default;

FormButtonType FormWidgetButton::getButtonType() const
{
    return parent()->getButtonType();
}

void FormWidgetButton::setAppearanceState(const char *state)
{
    if (!widget) {
        return;
    }
    widget->setAppearanceState(state);
}

void FormWidgetButton::updateWidgetAppearance()
{
    // The appearance stream must NOT be regenerated for this widget type
}

void FormWidgetButton::setState(bool astate)
{
    // pushButtons don't have state
    if (parent()->getButtonType() == formButtonPush) {
        return;
    }

    // Silently return if can't set ON state
    if (astate && !getOnStr()) {
        return;
    }

    parent()->setState(astate ? getOnStr() : "Off");
    // Parent will call setAppearanceState()

    // Now handle standAlone fields which are related to this one by having the same
    // fully qualified name. This is *partially* by spec, as seen in "Field names"
    // section inside "8.6.2 Field Dictionaries" in 1.7 PDF spec. Issue #1034

    if (!astate) { // We're only interested when this field is being set to ON,
        return; // to check if it has related fields and then set them OFF
    }

    unsigned this_page_num, this_field_num;
    decodeID(getID(), &this_page_num, &this_field_num);
    Page *this_page = doc->getCatalog()->getPage(this_page_num);
    const FormField *this_field = getField();
    if (!this_page->hasStandaloneFields() || this_field == nullptr) {
        return;
    }

    auto this_page_widgets = this_page->getFormWidgets();
    const FormButtonType this_button_type = getButtonType();

    const int tot = this_page_widgets->getNumWidgets();
    for (int i = 0; i < tot; i++) {
        bool found_related = false;
        FormWidget *wid = this_page_widgets->getWidget(i);
        const bool same_fqn = wid->getFullyQualifiedName()->compare(getFullyQualifiedName()->toStr()) == 0;
        const bool same_button_type = wid->getType() == formButton && static_cast<const FormWidgetButton *>(wid)->getButtonType() == this_button_type;

        if (same_fqn && same_button_type) {
            if (this_field->isStandAlone()) {
                //'this_field' is standAlone, so we need to search in both standAlone fields and normal fields
                if (this_field != wid->getField()) { // so take care to not choose our same field
                    found_related = true;
                }
            } else {
                //'this_field' is not standAlone, so we just need to search in standAlone fields
                if (wid->getField()->isStandAlone()) {
                    found_related = true;
                }
            }
        }

        if (found_related) {
            auto *ffb = static_cast<FormFieldButton *>(wid->getField());
            if (ffb == nullptr) {
                error(errInternal, -1, "FormWidgetButton::setState : FormFieldButton expected");
                continue;
            }
            ffb->setState("Off", true);
        }
    }
}

bool FormWidgetButton::getState() const
{
    return getOnStr() ? parent()->getState(getOnStr()) : false;
}

FormFieldButton *FormWidgetButton::parent() const
{
    return static_cast<FormFieldButton *>(field);
}

FormWidgetText::FormWidgetText(PDFDoc *docA, Object *dictObj, unsigned num, Ref refA, FormField *p) : FormWidget(docA, dictObj, num, refA, p)
{
    type = formText;
}

const GooString *FormWidgetText::getContent() const
{
    return parent()->getContent();
}

void FormWidgetText::updateWidgetAppearance()
{
    if (widget) {
        widget->updateAppearanceStream();
    }
}

bool FormWidgetText::isMultiline() const
{
    return parent()->isMultiline();
}

bool FormWidgetText::isPassword() const
{
    return parent()->isPassword();
}

bool FormWidgetText::isFileSelect() const
{
    return parent()->isFileSelect();
}

bool FormWidgetText::noSpellCheck() const
{
    return parent()->noSpellCheck();
}

bool FormWidgetText::noScroll() const
{
    return parent()->noScroll();
}

bool FormWidgetText::isComb() const
{
    return parent()->isComb();
}

bool FormWidgetText::isRichText() const
{
    return parent()->isRichText();
}

int FormWidgetText::getMaxLen() const
{
    return parent()->getMaxLen();
}

double FormWidgetText::getTextFontSize()
{
    return parent()->getTextFontSize();
}

void FormWidgetText::setTextFontSize(int fontSize)
{
    parent()->setTextFontSize(fontSize);
}

void FormWidgetText::setContent(std::unique_ptr<GooString> new_content)
{
    parent()->setContent(std::move(new_content));
}

void FormWidgetText::setAppearanceContent(std::unique_ptr<GooString> new_content)
{
    parent()->setAppearanceContent(std::move(new_content));
}

FormFieldText *FormWidgetText::parent() const
{
    return static_cast<FormFieldText *>(field);
}

FormWidgetChoice::FormWidgetChoice(PDFDoc *docA, Object *dictObj, unsigned num, Ref refA, FormField *p) : FormWidget(docA, dictObj, num, refA, p)
{
    type = formChoice;
}

FormWidgetChoice::~FormWidgetChoice() = default;

bool FormWidgetChoice::_checkRange(int i) const
{
    if (i < 0 || static_cast<size_t>(i) >= getChoices().size()) {
        error(errInternal, -1, "FormWidgetChoice::_checkRange i out of range : {0:d}", i);
        return false;
    }
    return true;
}

void FormWidgetChoice::select(int i)
{
    if (!_checkRange(i)) {
        return;
    }
    parent()->select(i);
}

void FormWidgetChoice::toggle(int i)
{
    if (!_checkRange(i)) {
        return;
    }
    parent()->toggle(i);
}

void FormWidgetChoice::deselectAll()
{
    parent()->deselectAll();
}

const GooString *FormWidgetChoice::getEditChoice() const
{
    if (!hasEdit()) {
        error(errInternal, -1, "FormFieldChoice::getEditChoice called on a non-editable choice");
        return nullptr;
    }
    return parent()->getEditChoice();
}

void FormWidgetChoice::updateWidgetAppearance()
{
    if (widget) {
        widget->updateAppearanceStream();
    }
}

bool FormWidgetChoice::isSelected(int i) const
{
    if (!_checkRange(i)) {
        return false;
    }
    return parent()->isSelected(i);
}

void FormWidgetChoice::setEditChoice(std::unique_ptr<GooString> new_content)
{
    if (!hasEdit()) {
        error(errInternal, -1, "FormFieldChoice::setEditChoice : trying to edit an non-editable choice");
        return;
    }

    parent()->setEditChoice(std::move(new_content));
}

void FormWidgetChoice::setAppearanceChoiceContent(std::unique_ptr<GooString> new_content)
{
    parent()->setAppearanceChoiceContent(std::move(new_content));
}

const std::vector<FormFieldChoiceOption> &FormWidgetChoice::getChoices() const
{
    return parent()->getChoices();
}

const GooString *FormWidgetChoice::getChoice(int i) const
{
    return parent()->getChoice(i);
}

const GooString *FormWidgetChoice::getExportVal(int i) const
{
    return parent()->getExportVal(i);
}

bool FormWidgetChoice::isCombo() const
{
    return parent()->isCombo();
}

bool FormWidgetChoice::hasEdit() const
{
    return parent()->hasEdit();
}

bool FormWidgetChoice::isMultiSelect() const
{
    return parent()->isMultiSelect();
}

bool FormWidgetChoice::noSpellCheck() const
{
    return parent()->noSpellCheck();
}

bool FormWidgetChoice::commitOnSelChange() const
{
    return parent()->commitOnSelChange();
}

bool FormWidgetChoice::isListBox() const
{
    return parent()->isListBox();
}

FormFieldChoice *FormWidgetChoice::parent() const
{
    return static_cast<FormFieldChoice *>(field);
}

FormWidgetSignature::FormWidgetSignature(PDFDoc *docA, Object *dictObj, unsigned num, Ref refA, FormField *p) : FormWidget(docA, dictObj, num, refA, p)
{
    type = formSignature;
}

const std::vector<unsigned char> &FormWidgetSignature::getSignature() const
{
    return static_cast<FormFieldSignature *>(field)->getSignature();
}

SignatureInfo *FormWidgetSignature::validateSignatureAsync(bool doVerifyCert, bool forceRevalidation, time_t validationTime, bool ocspRevocationCheck, bool enableAIA, const std::function<void()> &doneCallback)
{
    return static_cast<FormFieldSignature *>(field)->validateSignatureAsync(doVerifyCert, forceRevalidation, validationTime, ocspRevocationCheck, enableAIA, doneCallback);
}

CertificateValidationStatus FormWidgetSignature::validateSignatureResult()
{
    return static_cast<FormFieldSignature *>(field)->validateSignatureResult();
}

// update hash with the specified range of data from the file
static bool hashFileRange(FILE *f, CryptoSign::SigningInterface *handler, Goffset start, Goffset end)
{
    if (!handler) {
        return false;
    }
    const int BUF_SIZE = 65536;

    auto *buf = new unsigned char[BUF_SIZE];

    while (start < end) {
        if (Gfseek(f, start, SEEK_SET) != 0) {
            delete[] buf;
            return false;
        }
        int len = BUF_SIZE;
        if (end - start < len) {
            len = static_cast<int>(end - start);
        }
        if (fread(buf, 1, len, f) != static_cast<size_t>(len)) {
            delete[] buf;
            return false;
        }
        handler->addData(buf, len);
        start += len;
    }
    delete[] buf;
    return true;
}

std::optional<CryptoSign::SigningErrorMessage> FormWidgetSignature::signDocument(const std::string &saveFilename, const std::string &certNickname, const std::string &password, const GooString *reason, const GooString *location,
                                                                                 const std::optional<GooString> &ownerPassword, const std::optional<GooString> &userPassword)
{
    auto backend = CryptoSign::Factory::createActive();
    if (!backend) {
        return CryptoSign::SigningErrorMessage { .type = CryptoSign::SigningError::InternalError, .message = ERROR_IN_CODE_LOCATION };
    }
    if (certNickname.empty()) {
        error(errInternal, -1, "signDocument: Empty nickname");
        return CryptoSign::SigningErrorMessage { .type = CryptoSign::SigningError::KeyMissing, .message = ERROR_IN_CODE_LOCATION };
    }

    auto sigHandler = backend->createSigningHandler(certNickname, HashAlgorithm::Sha256);

    const unsigned int maxExpectedSignatureSize = sigHandler->estimateSize();

    auto *signatureField = static_cast<FormFieldSignature *>(field);
    std::unique_ptr<X509CertificateInfo> certInfo = sigHandler->getCertificateInfo();
    if (!certInfo) {
        error(errInternal, -1, "signDocument: error getting signature info");
        return CryptoSign::SigningErrorMessage { .type = CryptoSign::SigningError::KeyMissing, .message = ERROR_IN_CODE_LOCATION };
    }
    const std::string signerName = certInfo->getSubjectInfo().commonName;
    signatureField->setCertificateInfo(certInfo);
    updateWidgetAppearance(); // add visible signing info to appearance

    Object vObj(std::make_unique<Dict>(xref));
    Ref vref = xref->addIndirectObject(vObj);
    if (!createSignature(vObj, vref, GooString(signerName), maxExpectedSignatureSize, reason, location, sigHandler->signatureType())) {
        return CryptoSign::SigningErrorMessage { .type = CryptoSign::SigningError::InternalError, .message = ERROR_IN_CODE_LOCATION };
    }

    // Incremental save to avoid breaking any existing signatures
    if (doc->saveAs(saveFilename, writeForceIncremental) != errNone) {
        error(errIO, -1, "signDocument: error saving to file \"{0:r}\"", &saveFilename);
        return CryptoSign::SigningErrorMessage { .type = CryptoSign::SigningError::WriteFailed, .message = ERROR_IN_CODE_LOCATION };
    }

    // Get start/end offset of signature object in the saved PDF
    Goffset objStart, objEnd;
    const GooString fname(saveFilename);
    if (!getObjectStartEnd(fname, vref.num, &objStart, &objEnd, ownerPassword, userPassword)) {
        error(errIO, -1, "signDocument: unable to get signature object offsets");
        return CryptoSign::SigningErrorMessage { .type = CryptoSign::SigningError::InternalError, .message = ERROR_IN_CODE_LOCATION };
    }

    // Update byte range of signature in the saved PDF
    Goffset sigStart, sigEnd, fileSize;
    FILE *file = openFile(saveFilename.c_str(), "r+b");
    if (!updateOffsets(file, objStart, objEnd, &sigStart, &sigEnd, &fileSize)) {
        error(errIO, -1, "signDocument: unable update byte range");
        fclose(file);
        return CryptoSign::SigningErrorMessage { .type = CryptoSign::SigningError::WriteFailed, .message = ERROR_IN_CODE_LOCATION };
    }

    // compute hash of byte ranges
    if (!hashFileRange(file, sigHandler.get(), 0LL, sigStart)) {
        fclose(file);
        return CryptoSign::SigningErrorMessage { .type = CryptoSign::SigningError::InternalError, .message = ERROR_IN_CODE_LOCATION };
    }
    if (!hashFileRange(file, sigHandler.get(), sigEnd, fileSize)) {
        fclose(file);
        return CryptoSign::SigningErrorMessage { .type = CryptoSign::SigningError::InternalError, .message = ERROR_IN_CODE_LOCATION };
    }

    // and sign it
    auto signature = sigHandler->signDetached(password);
    if (std::holds_alternative<CryptoSign::SigningErrorMessage>(signature)) {
        fclose(file);
        return std::get<CryptoSign::SigningErrorMessage>(signature);
    }

    if (std::get<std::vector<unsigned char>>(signature).size() > maxExpectedSignatureSize) {
        error(errInternal, -1, "signature too large");
        fclose(file);
        return CryptoSign::SigningErrorMessage { .type = CryptoSign::SigningError::InternalError, .message = ERROR_IN_CODE_LOCATION };
    }

    // pad with zeroes to placeholder length
    std::get<std::vector<unsigned char>>(signature).resize(maxExpectedSignatureSize, '\0');

    // write signature to saved file
    if (!updateSignature(file, sigStart, sigEnd, std::get<std::vector<unsigned char>>(signature))) {
        error(errIO, -1, "signDocument: unable update signature");
        fclose(file);
        return CryptoSign::SigningErrorMessage { .type = CryptoSign::SigningError::WriteFailed, .message = ERROR_IN_CODE_LOCATION };
    }
    signatureField->setSignature(std::get<std::vector<unsigned char>>(std::move(signature)));

    fclose(file);

    return {};
}

static std::tuple<double, double> calculateDxDy(int rot, const PDFRectangle &rect)
{
    switch (rot) {
    case 90:
        return { rect.y2 - rect.y1, rect.x2 - rect.x1 };

    case 180:
        return { rect.x2 - rect.y2, rect.y2 - rect.y1 };

    case 270:
        return { rect.y2 - rect.y1, rect.x2 - rect.x1 };

    default: // assume rot == 0
        return { rect.x2 - rect.x1, rect.y2 - rect.y1 };
    }
}

std::optional<CryptoSign::SigningErrorMessage> FormWidgetSignature::signDocumentWithAppearance(const std::string &saveFilename, const std::string &certNickname, const std::string &password, const GooString *reason,
                                                                                               const GooString *location, const std::optional<GooString> &ownerPassword, const std::optional<GooString> &userPassword,
                                                                                               const GooString &signatureText, const GooString &signatureTextLeft, double fontSize, double leftFontSize,
                                                                                               std::unique_ptr<AnnotColor> &&fontColor, double borderWidth, std::unique_ptr<AnnotColor> &&borderColor,
                                                                                               std::unique_ptr<AnnotColor> &&backgroundColor)
{
    // Set the appearance
    const std::string originalDefaultAppearance = getField()->getDefaultAppearance();

    Form *form = doc->getCatalog()->getCreateForm();

    double x1, y1, x2, y2;
    getRect(&x1, &y1, &x2, &y2);
    const PDFRectangle rect(x1, y1, x2, y2);
    std::unique_ptr<AnnotAppearanceCharacs> origAppearCharacs = getWidgetAnnotation()->getAppearCharacs() ? getWidgetAnnotation()->getAppearCharacs()->copy() : nullptr;
    const int rot = origAppearCharacs ? origAppearCharacs->getRotation() : 0;
    const auto dxdy = calculateDxDy(rot, rect);
    const double dx = std::get<0>(dxdy);
    const double dy = std::get<1>(dxdy);
    const double wMax = dx - 2 * borderWidth - 4;
    const double hMax = dy - 2 * borderWidth;

    std::unique_ptr<AnnotBorder> origBorderCopy = getWidgetAnnotation()->getBorder() ? getWidgetAnnotation()->getBorder()->copy() : nullptr;
    std::unique_ptr<AnnotBorder> border(new AnnotBorderArray());
    border->setWidth(borderWidth);
    getWidgetAnnotation()->setBorder(std::move(border));

    if (!signatureText.empty() || !signatureTextLeft.empty()) {
        const std::string pdfFontName = form->findPdfFontNameToUseForSigning();
        if (pdfFontName.empty()) {
            return CryptoSign::SigningErrorMessage { .type = CryptoSign::SigningError::InternalError, .message = ERROR_IN_CODE_LOCATION };
        }
        std::shared_ptr<GfxFont> font = form->getDefaultResources()->lookupFont(pdfFontName);

        if (fontSize == 0) {
            fontSize = Annot::calculateFontSize(form, *font, signatureText.toStr(), wMax / 2.0, hMax);
        }
        if (leftFontSize == 0) {
            leftFontSize = Annot::calculateFontSize(form, *font, signatureTextLeft.toStr(), wMax / 2.0, hMax);
        }
        const DefaultAppearance da { pdfFontName, fontSize, std::move(fontColor) };
        getField()->setDefaultAppearance(da.toAppearanceString());
        form->ensureFontsForAllCharacters(signatureText.toStr(), pdfFontName);
        form->ensureFontsForAllCharacters(signatureTextLeft.toStr(), pdfFontName);
    }
    auto appearCharacs = std::make_unique<AnnotAppearanceCharacs>(nullptr);
    appearCharacs->setBorderColor(std::move(borderColor));
    appearCharacs->setBackColor(std::move(backgroundColor));
    getWidgetAnnotation()->setAppearCharacs(std::move(appearCharacs));

    getWidgetAnnotation()->generateFieldAppearance();
    getWidgetAnnotation()->updateAppearanceStream();

    auto *ffs = static_cast<::FormFieldSignature *>(getField());
    ffs->setCustomAppearanceContent(signatureText);
    ffs->setCustomAppearanceLeftContent(signatureTextLeft);
    ffs->setCustomAppearanceLeftFontSize(leftFontSize);

    // say that there a now signatures and that we should append only
    doc->getCatalog()->getAcroForm()->dictSet("SigFlags", Object(3));

    auto signingResult = signDocument(saveFilename, certNickname, password, reason, location, ownerPassword, userPassword);

    // Now bring back the annotation appearance back to what it was
    ffs->setDefaultAppearance(originalDefaultAppearance);
    ffs->setCustomAppearanceContent({});
    ffs->setCustomAppearanceLeftContent({});
    getWidgetAnnotation()->setAppearCharacs(std::move(origAppearCharacs));
    getWidgetAnnotation()->setBorder(std::move(origBorderCopy));
    getWidgetAnnotation()->updateAppearanceStream();

    return signingResult;
}

// Get start and end file position of objNum in the PDF named filename.
bool FormWidgetSignature::getObjectStartEnd(const GooString &filename, int objNum, Goffset *objStart, Goffset *objEnd, const std::optional<GooString> &ownerPassword, const std::optional<GooString> &userPassword)
{
    PDFDoc newDoc(filename.copy(), ownerPassword, userPassword);
    if (!newDoc.isOk()) {
        return false;
    }

    XRef *newXref = newDoc.getXRef();
    XRefEntry *entry = newXref->getEntry(objNum);
    if (entry->type != xrefEntryUncompressed) {
        return false;
    }

    *objStart = entry->offset;
    newXref->fetch(objNum, entry->gen, 0, objEnd);
    return true;
}

// find next offset containing the dummy offset '9999999999' and overwrite with offset
static char *setNextOffset(char *start, Goffset offset)
{
    char buf[50];
    sprintf(buf, "%lld", offset);
    strcat(buf, "                  "); // add some padding

    char *p = strstr(start, "9999999999");
    if (p) {
        memcpy(p, buf, 10); // overwrite exact size.
        p += 10;
    } else {
        return nullptr;
    }
    return p;
}

// Updates the ByteRange array of the signature object in the file.
// Returns start/end of signature string and file size.
bool FormWidgetSignature::updateOffsets(FILE *f, Goffset objStart, Goffset objEnd, Goffset *sigStart, Goffset *sigEnd, Goffset *fileSize)
{
    if (Gfseek(f, 0, SEEK_END) != 0) {
        return false;
    }
    *fileSize = Gftell(f);

    if (objEnd > *fileSize) {
        objEnd = *fileSize;
    }

    // sanity check object offsets
    if (objEnd <= objStart || (objEnd - objStart >= INT_MAX)) {
        return false;
    }

    const auto bufSize = static_cast<size_t>(objEnd - objStart);
    if (Gfseek(f, objStart, SEEK_SET) != 0) {
        return false;
    }
    std::vector<char> buf(bufSize + 1);
    if (fread(buf.data(), 1, bufSize, f) != bufSize) {
        return false;
    }
    buf[bufSize] = 0; // prevent string functions from searching past the end

    // search for the Contents field which contains the signature placeholder
    // which always must start with hex digits 000
    *sigStart = -1;
    *sigEnd = -1;
    for (size_t i = 0; i < bufSize - 14; i++) {
        if (buf[i] == '/' && strncmp(&buf[i], "/Contents <000", 14) == 0) {
            *sigStart = objStart + i + 10;
            char *p = strchr(&buf[i], '>');
            if (p) {
                *sigEnd = objStart + (p - buf.data()) + 1;
            }
            break;
        }
    }

    if (*sigStart == -1 || *sigEnd == -1) {
        return false;
    }

    // Search for ByteRange array and update offsets
    for (size_t i = 0; i < bufSize - 10; i++) {
        if (buf[i] == '/' && strncmp(&buf[i], "/ByteRange", 10) == 0) {
            // update range
            char *p = setNextOffset(&buf[i], *sigStart);
            if (!p) {
                return false;
            }
            p = setNextOffset(p, *sigEnd);
            if (!p) {
                return false;
            }
            p = setNextOffset(p, *fileSize - *sigEnd);
            if (!p) {
                return false;
            }
            break;
        }
    }

    // write buffer back to disk
    if (Gfseek(f, objStart, SEEK_SET) != 0) {
        return false;
    }
    fwrite(buf.data(), bufSize, 1, f);
    return true;
}

// Overwrite signature string in the file with new signature
bool FormWidgetSignature::updateSignature(FILE *f, Goffset sigStart, Goffset sigEnd, const std::vector<unsigned char> &signature)
{
    if (signature.size() * 2 + 2 != static_cast<size_t>(sigEnd - sigStart)) {
        return false;
    }

    if (Gfseek(f, sigStart, SEEK_SET) != 0) {
        return false;
    }
    fprintf(f, "<");
    for (unsigned char value : signature) {
        fprintf(f, "%2.2x", value);
    }
    fprintf(f, "> ");
    return true;
}

bool FormWidgetSignature::createSignature(Object &vObj, Ref vRef, const GooString &name, int placeholderLength, const GooString *reason, const GooString *location, CryptoSign::SignatureType signatureType)
{
    vObj.dictAdd("Type", Object::name("Sig"));
    vObj.dictAdd("Filter", Object::name("Adobe.PPKLite"));
    vObj.dictAdd("SubFilter", Object::name(toStdString(signatureType)));
    vObj.dictAdd("Name", Object(std::string { name.toStr() }));
    vObj.dictAdd("M", Object(std::string { timeToDateString(nullptr)->toStr() }));
    if (reason && !reason->empty()) {
        vObj.dictAdd("Reason", Object(std::string { reason->toStr() }));
    }
    if (location && !location->empty()) {
        vObj.dictAdd("Location", Object(std::string { location->toStr() }));
    }

    vObj.dictAdd("Contents", Object::hexString(std::string(placeholderLength, '\0')));
    auto byteRangeArray = std::make_unique<Array>(xref);
    // reserve space in byte range for maximum number of bytes
    byteRangeArray->add(Object(0LL));
    byteRangeArray->add(Object(9999999999LL));
    byteRangeArray->add(Object(9999999999LL));
    byteRangeArray->add(Object(9999999999LL));
    vObj.dictAdd("ByteRange", Object(std::move(byteRangeArray)));
    field->getObj()->dictSet("V", Object(vRef));
    xref->setModifiedObject(field->getObj(), field->getRef());
    return true;
}

std::vector<Goffset> FormWidgetSignature::getSignedRangeBounds() const
{
    return static_cast<FormFieldSignature *>(field)->getSignedRangeBounds();
}

std::pair<std::optional<std::vector<unsigned char>>, int64_t> FormWidgetSignature::getCheckedSignature()
{
    return static_cast<FormFieldSignature *>(field)->getCheckedSignature();
}

void FormWidgetSignature::updateWidgetAppearance()
{
    if (widget) {
        widget->updateAppearanceStream();
    }
}

//========================================================================
// FormField
//========================================================================

FormField::FormField(PDFDoc *docA, Object &&aobj, const Ref aref, FormField *parentA, std::set<int> *usedParents, FormFieldType ty)
{
    doc = docA;
    xref = doc->getXRef();
    obj = std::move(aobj);
    Dict *dict = obj.getDict();
    ref = aref;
    type = ty;
    parent = parentA;
    terminal = false;
    readOnly = false;
    fullyQualifiedName = nullptr;
    quadding = VariableTextQuadding::leftJustified;
    hasQuadding = false;
    standAlone = false;
    noExport = false;

    // childs
    Object obj1 = dict->lookup("Kids");
    if (obj1.isArray()) {
        // Load children
        for (int i = 0; i < obj1.arrayGetLength(); i++) {
            Ref childRef;
            Object childObj = obj1.getArray()->get(i, &childRef);
            if (childRef == Ref::INVALID()) {
                error(errSyntaxError, -1, "Invalid form field renference");
                continue;
            }
            if (!childObj.isDict()) {
                error(errSyntaxError, -1, "Form field child is not a dictionary");
                continue;
            }

            if (usedParents->size() > 500) {
                error(errSyntaxError, -1, "Form kids hierarchy too deep; stopping");
                break;
            }

            if (!usedParents->contains(childRef.num)) {
                // Field child: it could be a form field or a widget or composed dict
                const Object &objParent = childObj.dictLookupNF("Parent");
                Object obj3 = childObj.dictLookup("Parent");
                const bool hasParent = objParent.isRef() || obj3.isDict();
                const bool isWidget = childObj.dictLookup("Subtype").isName("Widget");
                // Handle hypothetical case of root Field with no children and no "T" key (as "T" is optional for PDF < 2.0)
                const bool isField = childObj.dictLookup("T").isString() || (!hasParent && childObj.dictLookup("FT").isName());
                const bool isComposedWidget = isWidget && isField;
                const bool isPureWidget = isWidget && !isComposedWidget;
                if (hasParent && !isPureWidget) {
                    // Child is a form field or composed dict
                    // We create the field, if it's composed
                    // it will create the widget as a child
                    std::set<int> usedParentsAux = *usedParents;
                    usedParentsAux.insert(childRef.num);

                    if (terminal) {
                        error(errSyntaxWarning, -1, "Field can't have both Widget AND Field as kids");
                        continue;
                    }

                    children.push_back(Form::createFieldFromDict(std::move(childObj), doc, childRef, this, &usedParentsAux));
                } else if (isPureWidget) {
                    if (hasParent) {
                        // PDF 1.7 wrt 1.4 introduced "Parent" for Widget Annotations, this is
                        // such a case so let's validate the Parent just for warning purposes
                        const bool parentOK = (objParent.isRef() && objParent.getRef() == ref) || (obj3.isDict() && &obj3 == &obj);
                        if (!parentOK) {
                            error(errSyntaxWarning, -1, "Widget Annotation's Parent entry not pointing to its parent FormField");
                        }
                    }
                    // Child is a widget annotation
                    if (!terminal && !children.empty()) {
                        error(errSyntaxWarning, -1, "Field can't have both Widget AND Field as kids");
                        continue;
                    }
                    _createWidget(&childObj, childRef);
                }
            }
        }
    } else {
        // No children, if it's a composed dict, create the child widget
        obj1 = dict->lookup("Subtype");
        if (obj1.isName("Widget")) {
            _createWidget(&obj, ref);
        }
    }

    // flags
    obj1 = Form::fieldLookup(dict, "Ff");
    if (obj1.isInt()) {
        int flags = obj1.getInt();
        if (flags & 0x1) { // 1 -> ReadOnly
            readOnly = true;
        }
        if (flags & 0x2) { // 2 -> Required
            // TODO
        }
        if (flags & 0x4) { // 3 -> NoExport
            noExport = true;
        }
    }

    // Variable Text
    obj1 = Form::fieldLookup(dict, "DA");
    if (obj1.isString()) {
        defaultAppearance = std::move(obj1.takeString()->toNonConstStr());
    }

    obj1 = Form::fieldLookup(dict, "Q");
    if (obj1.isInt()) {
        const auto aux = static_cast<VariableTextQuadding>(obj1.getInt());
        hasQuadding = aux == VariableTextQuadding::leftJustified || aux == VariableTextQuadding::centered || aux == VariableTextQuadding::rightJustified;
        if (likely(hasQuadding)) {
            quadding = static_cast<VariableTextQuadding>(aux);
        }
    }

    obj1 = dict->lookup("T");
    if (obj1.isString()) {
        partialName = obj1.takeString();
    }

    obj1 = dict->lookup("TU");
    if (obj1.isString()) {
        alternateUiName = obj1.takeString();
    }

    obj1 = dict->lookup("TM");
    if (obj1.isString()) {
        mappingName = obj1.takeString();
    }
    widgets.shrink_to_fit();
    children.shrink_to_fit();
}

void FormField::setDefaultAppearance(const std::string &appearance)
{
    defaultAppearance = appearance;
}

void FormField::setPartialName(const GooString &name)
{
    partialName = name.copy();

    obj.getDict()->set("T", Object(std::string { name.toStr() }));
    xref->setModifiedObject(&obj, ref);
}

FormField::~FormField() = default;

void FormField::print(int indent)
{
    printf("%*s- (%d %d): [container] terminal: %s children: %zu\n", indent, "", ref.num, ref.gen, terminal ? "Yes" : "No", terminal ? widgets.size() : children.size());
}

void FormField::printTree(int indent)
{
    print(indent);
    if (terminal) {
        for (const auto &widget : widgets) {
            widget->print(indent + 4);
        }
    } else {
        for (const auto &child : children) {
            child->printTree(indent + 4);
        }
    }
}

void FormField::fillChildrenSiblingsID()
{
    if (terminal) {
        return;
    }
    for (const auto &child : children) {
        child->fillChildrenSiblingsID();
    }
}

void FormField::createWidgetAnnotations()
{
    if (terminal) {
        for (auto &widget : widgets) {
            widget->createWidgetAnnotation();
        }
    } else {
        for (auto &child : children) {
            child->createWidgetAnnotations();
        }
    }
}

void FormField::_createWidget(Object *objA, Ref aref)
{
    terminal = true;
    // ID = index in "widgets" table
    switch (type) {
    case formButton:
        widgets.push_back(std::make_unique<FormWidgetButton>(doc, objA, widgets.size(), aref, this));
        break;
    case formText:
        widgets.push_back(std::make_unique<FormWidgetText>(doc, objA, widgets.size(), aref, this));
        break;
    case formChoice:
        widgets.push_back(std::make_unique<FormWidgetChoice>(doc, objA, widgets.size(), aref, this));
        break;
    case formSignature:
        widgets.push_back(std::make_unique<FormWidgetSignature>(doc, objA, widgets.size(), aref, this));
        break;
    default:
        error(errSyntaxWarning, -1, "SubType on non-terminal field, invalid document?");
    }
}

FormWidget *FormField::findWidgetByRef(Ref aref)
{
    if (terminal) {
        for (auto &widget : widgets) {
            if (widget->getRef() == aref) {
                return widget.get();
            }
        }
    } else {
        for (auto &child : children) {
            FormWidget *result = child->findWidgetByRef(aref);
            if (result) {
                return result;
            }
        }
    }
    return nullptr;
}

const GooString *FormField::getFullyQualifiedName() const
{
    Object parentObj;
    bool unicode_encoded = false;

    if (fullyQualifiedName) {
        return fullyQualifiedName.get();
    }

    fullyQualifiedName = std::make_unique<GooString>();

    std::set<int> parsedRefs;
    Ref parentRef;
    parentObj = obj.getDict()->lookup("Parent", &parentRef);
    if (parentRef != Ref::INVALID()) {
        parsedRefs.insert(parentRef.num);
    }
    while (parentObj.isDict()) {
        Object obj2 = parentObj.dictLookup("T");
        if (obj2.isString()) {
            const std::string &parent_name = obj2.getString();

            if (unicode_encoded) {
                fullyQualifiedName->insert(0, "\0.", 2); // 2-byte unicode period
                if (hasUnicodeByteOrderMark(parent_name)) {
                    fullyQualifiedName->insert(0, parent_name.c_str() + 2, parent_name.size() - 2); // Remove the unicode BOM
                } else {
                    std::string tmp_str = pdfDocEncodingToUTF16(parent_name);
                    fullyQualifiedName->insert(0, tmp_str.c_str() + 2, tmp_str.size() - 2); // Remove the unicode BOM
                }
            } else {
                fullyQualifiedName->insert(0, "."); // 1-byte ascii period
                if (hasUnicodeByteOrderMark(parent_name)) {
                    unicode_encoded = true;
                    fullyQualifiedName = convertToUtf16(fullyQualifiedName.get());
                    fullyQualifiedName->insert(0, parent_name.c_str() + 2, parent_name.size() - 2); // Remove the unicode BOM
                } else {
                    fullyQualifiedName->insert(0, parent_name);
                }
            }
        }
        parentObj = parentObj.getDict()->lookup("Parent", &parentRef);
        if (parentRef != Ref::INVALID() && !parsedRefs.insert(parentRef.num).second) {
            error(errSyntaxError, -1, "FormField: Loop while trying to look for Parents");
            return fullyQualifiedName.get();
        }
    }

    if (partialName) {
        if (unicode_encoded) {
            if (hasUnicodeByteOrderMark(partialName->toStr())) {
                fullyQualifiedName->append(partialName->c_str() + 2, partialName->size() - 2); // Remove the unicode BOM
            } else {
                std::string tmp_str = pdfDocEncodingToUTF16(partialName->toStr());
                fullyQualifiedName->append(tmp_str.c_str() + 2, tmp_str.size() - 2); // Remove the unicode BOM
            }
        } else {
            if (hasUnicodeByteOrderMark(partialName->toStr())) {
                unicode_encoded = true;
                fullyQualifiedName = convertToUtf16(fullyQualifiedName.get());
                fullyQualifiedName->append(partialName->c_str() + 2, partialName->size() - 2); // Remove the unicode BOM
            } else {
                fullyQualifiedName->append(partialName->toStr());
            }
        }
    } else {
        int len = fullyQualifiedName->size();
        // Remove the last period
        if (unicode_encoded) {
            if (len > 1) {
                fullyQualifiedName->erase(len - 2, 2);
            }
        } else {
            if (len > 0) {
                fullyQualifiedName->erase(len - 1, 1);
            }
        }
    }

    if (unicode_encoded) {
        prependUnicodeByteOrderMark(fullyQualifiedName->toNonConstStr());
    }

    return fullyQualifiedName.get();
}

void FormField::updateChildrenAppearance()
{
    // Recursively update each child's appearance
    if (terminal) {
        for (auto &widget : widgets) {
            widget->updateWidgetAppearance();
        }
    } else {
        for (auto &child : children) {
            child->updateChildrenAppearance();
        }
    }
}

void FormField::setReadOnly(bool value)
{
    if (value == readOnly) {
        return;
    }

    readOnly = value;

    Dict *dict = obj.getDict();

    const Object obj1 = Form::fieldLookup(dict, "Ff");
    int flags = 0;
    if (obj1.isInt()) {
        flags = obj1.getInt();
    }
    if (value) {
        flags |= 1;
    } else {
        flags &= ~1;
    }

    dict->set("Ff", Object(flags));
    xref->setModifiedObject(&obj, ref);
    updateChildrenAppearance();
}

void FormField::reset(const std::vector<std::string> &excludedFields)
{
    resetChildren(excludedFields);
}

void FormField::resetChildren(const std::vector<std::string> &excludedFields)
{
    if (!terminal) {
        for (auto &child : children) {
            child->reset(excludedFields);
        }
    }
}

bool FormField::isAmongExcludedFields(const std::vector<std::string> &excludedFields)
{
    Ref fieldRef;

    for (const std::string &field : excludedFields) {
        if (field.ends_with(" R")) {
            if (sscanf(field.c_str(), "%d %d R", &fieldRef.num, &fieldRef.gen) == 2 && fieldRef == getRef()) {
                return true;
            }
        } else {
            if (field == getFullyQualifiedName()->toStr()) {
                return true;
            }
        }
    }

    return false;
}

FormField *FormField::findFieldByRef(Ref aref)
{
    if (terminal) {
        if (this->getRef() == aref) {
            return this;
        }
    } else {
        for (auto &child : children) {
            FormField *result = child->findFieldByRef(aref);
            if (result) {
                return result;
            }
        }
    }
    return nullptr;
}

FormField *FormField::findFieldByFullyQualifiedName(const std::string &name)
{
    if (terminal) {
        if (getFullyQualifiedName()->compare(name) == 0) {
            return this;
        }
    } else {
        for (auto &child : children) {
            FormField *result = child->findFieldByFullyQualifiedName(name);
            if (result) {
                return result;
            }
        }
    }
    return nullptr;
}

//------------------------------------------------------------------------
// FormFieldButton
//------------------------------------------------------------------------
FormFieldButton::FormFieldButton(PDFDoc *docA, Object &&dictObj, const Ref refA, FormField *parentA, std::set<int> *usedParents) : FormField(docA, std::move(dictObj), refA, parentA, usedParents, formButton)
{
    Dict *dict = obj.getDict();
    active_child = -1;
    noAllOff = false;
    appearanceState.setToNull();
    defaultAppearanceState.setToNull();

    btype = formButtonCheck;
    Object obj1 = Form::fieldLookup(dict, "Ff");
    if (obj1.isInt()) {
        int flags = obj1.getInt();

        if (flags & 0x10000) { // 17 -> push button
            btype = formButtonPush;
        } else if (flags & 0x8000) { // 16 -> radio button
            btype = formButtonRadio;
            if (flags & 0x4000) { // 15 -> noToggleToOff
                noAllOff = true;
            }
        }
        if (flags & 0x1000000) { // 26 -> radiosInUnison
            error(errUnimplemented, -1, "FormFieldButton:: radiosInUnison flag unimplemented, please report a bug with a testcase");
        }
    }

    bool isChildRadiobutton = btype == formButtonRadio && terminal && parent && parent->getType() == formButton;
    // Ignore "V" for child radiobuttons, so FormFieldButton::getState() does not use it and instead uses the
    // "V" of the parent, which is the real value indicating the active field in the radio group. Issue #159
    if (btype != formButtonPush && !isChildRadiobutton) {
        // Even though V is inheritable we are interested in the value of this
        // field, if not present it's probably because it's a button in a set.
        appearanceState = dict->lookup("V");
        defaultAppearanceState = Form::fieldLookup(dict, "DV");
    }
}

static const char *_getButtonType(FormButtonType type)
{
    switch (type) {
    case formButtonPush:
        return "push";
    case formButtonCheck:
        return "check";
    case formButtonRadio:
        return "radio";
    default:
        break;
    }
    return "unknown";
}

void FormFieldButton::print(int indent)
{
    printf("%*s- (%d %d): [%s] terminal: %s children: %zu\n", indent, "", ref.num, ref.gen, _getButtonType(btype), terminal ? "Yes" : "No", terminal ? widgets.size() : children.size());
}

void FormFieldButton::setNumSiblings(int num)
{
    siblings.resize(num, nullptr);
}

void FormFieldButton::fillChildrenSiblingsID()
{
    if (!terminal) {
        int numChildren = static_cast<int>(children.size());
        for (int i = 0; i < numChildren; i++) {
            auto *child = dynamic_cast<FormFieldButton *>(children[i].get());
            if (child != nullptr) {
                // Fill the siblings of this node childs
                child->setNumSiblings(numChildren - 1);
                for (int j = 0, counter = 0; j < numChildren; j++) {
                    auto *otherChild = dynamic_cast<FormFieldButton *>(children[j].get());
                    if (i == j) {
                        continue;
                    }
                    if (child == otherChild) {
                        continue;
                    }
                    child->setSibling(counter, otherChild);
                    counter++;
                }

                // now call ourselves on the child
                // to fill its children data
                child->fillChildrenSiblingsID();
            }
        }
    }
}

bool FormFieldButton::setState(const char *state, bool ignoreToggleOff)
{
    // A check button could behave as a radio button
    // when it's in a set of more than 1 buttons
    if (btype != formButtonRadio && btype != formButtonCheck) {
        return false;
    }

    if (terminal && parent && parent->getType() == formButton && appearanceState.isNull()) {
        // It's button in a set, set state on parent
        return static_cast<FormFieldButton *>(parent)->setState(state);
    }

    bool isOn = strcmp(state, "Off") != 0;

    if (!isOn && noAllOff && !ignoreToggleOff) {
        return false; // Don't allow to set all radio to off
    }

    const char *current = getAppearanceState();
    bool currentFound = false, newFound = false;

    for (size_t i = 0; i < (terminal ? widgets.size() : children.size()); i++) {
        FormWidgetButton *widget;

        // If radio button is a terminal field we want the widget at i, but
        // if it's not terminal, the child widget is a composed dict, so
        // we want the ony child widget of the children at i
        if (terminal) {
            widget = static_cast<FormWidgetButton *>(widgets[i].get());
        } else {
            widget = static_cast<FormWidgetButton *>(children[i]->getWidget(0));
        }

        if (!widget->getOnStr()) {
            continue;
        }

        const char *onStr = widget->getOnStr();
        if (current && strcmp(current, onStr) == 0) {
            widget->setAppearanceState("Off");
            if (!isOn) {
                break;
            }
            currentFound = true;
        }

        if (isOn && strcmp(state, onStr) == 0) {
            widget->setAppearanceState(state);
            newFound = true;
        }

        if (currentFound && newFound) {
            break;
        }
    }

    updateState(state);

    return true;
}

bool FormFieldButton::getState(const char *state) const
{
    if (appearanceState.isName(state)) {
        return true;
    }

    return (parent && parent->getType() == formButton) ? static_cast<FormFieldButton *>(parent)->getState(state) : false;
}

void FormFieldButton::updateState(const char *state)
{
    appearanceState = Object::name(state);
    obj.getDict()->set("V", appearanceState.copy());
    xref->setModifiedObject(&obj, ref);
}

FormFieldButton::~FormFieldButton() = default;

void FormFieldButton::reset(const std::vector<std::string> &excludedFields)
{
    if (!isAmongExcludedFields(excludedFields)) {
        if (getDefaultAppearanceState()) {
            setState(getDefaultAppearanceState());
        } else {
            obj.getDict()->remove("V");

            // Clear check button if it doesn't have default value.
            // This behaviour is what Adobe Reader does, it is not written in specification.
            if (btype == formButtonCheck) {
                setState("Off");
            }
        }
    }

    resetChildren(excludedFields);
}

//------------------------------------------------------------------------
// FormFieldText
//------------------------------------------------------------------------
FormFieldText::FormFieldText(PDFDoc *docA, Object &&dictObj, const Ref refA, FormField *parentA, std::set<int> *usedParents) : FormField(docA, std::move(dictObj), refA, parentA, usedParents, formText)
{
    Dict *dict = obj.getDict();
    Object obj1;
    multiline = password = fileSelect = doNotSpellCheck = doNotScroll = comb = richText = false;
    maxLen = 0;

    obj1 = Form::fieldLookup(dict, "Ff");
    if (obj1.isInt()) {
        int flags = obj1.getInt();
        if (flags & 0x1000) { // 13 -> Multiline
            multiline = true;
        }
        if (flags & 0x2000) { // 14 -> Password
            password = true;
        }
        if (flags & 0x100000) { // 21 -> FileSelect
            fileSelect = true;
        }
        if (flags & 0x400000) { // 23 -> DoNotSpellCheck
            doNotSpellCheck = true;
        }
        if (flags & 0x800000) { // 24 -> DoNotScroll
            doNotScroll = true;
        }
        if (flags & 0x1000000) { // 25 -> Comb
            comb = true;
        }
        if (flags & 0x2000000) { // 26 -> RichText
            richText = true;
        }
    }

    obj1 = Form::fieldLookup(dict, "MaxLen");
    if (obj1.isInt()) {
        maxLen = obj1.getInt();
    }

    fillContent(fillDefaultValue);
    fillContent(fillValue);
}

void FormFieldText::fillContent(FillValueType fillType)
{
    Dict *dict = obj.getDict();
    Object obj1;

    obj1 = Form::fieldLookup(dict, fillType == fillDefaultValue ? "DV" : "V");
    if (obj1.isString()) {
        if (hasUnicodeByteOrderMark(obj1.getString())) {
            if (obj1.getString().size() > 2) {
                if (fillType == fillDefaultValue) {
                    defaultContent = obj1.takeString();
                } else {
                    content = obj1.takeString();
                }
            }
        } else if (!obj1.getString().empty()) {
            // non-unicode string -- assume pdfDocEncoding and try to convert to UTF16BE
            std::string tmp_str = pdfDocEncodingToUTF16(obj1.getString());

            if (fillType == fillDefaultValue) {
                defaultContent = std::make_unique<GooString>(std::move(tmp_str));
            } else {
                content = std::make_unique<GooString>(std::move(tmp_str));
            }
        }
    }
}

void FormFieldText::print(int indent)
{
    printf("%*s- (%d %d): [text] terminal: %s children: %zu\n", indent, "", ref.num, ref.gen, terminal ? "Yes" : "No", terminal ? widgets.size() : children.size());
}

void FormFieldText::setContent(std::unique_ptr<GooString> new_content)
{
    content.reset();

    if (new_content) {
        content = std::move(new_content);

        // append the unicode marker <FE FF> if needed
        if (!hasUnicodeByteOrderMark(content->toStr())) {
            prependUnicodeByteOrderMark(content->toNonConstStr());
        }
        Form *form = doc->getCatalog()->getForm();
        if (form) {
            DefaultAppearance da(defaultAppearance);
            const std::string &fontName = da.getFontName();
            if (!fontName.empty()) {
                // Use the field resource dictionary if it exists
                Object fieldResourcesDictObj = obj.dictLookup("DR");
                if (fieldResourcesDictObj.isDict()) {
                    GfxResources fieldResources(doc->getXRef(), fieldResourcesDictObj.getDict(), form->getDefaultResources());
                    const std::vector<Form::AddFontResult> newFonts = form->ensureFontsForAllCharacters(content->toStr(), fontName, &fieldResources);
                    // If we added new fonts to the Form object default resuources we also need to add them (we only add the ref so this is cheap)
                    // to the field DR dictionary
                    if (!newFonts.empty()) {
                        for (const Form::AddFontResult &afr : newFonts) {
                            fieldResourcesDictObj.dictLookup("Font").dictAdd(afr.fontName, Object(afr.ref));
                            // This is not fully correct, it changes the entire font to the last added font
                            // but it is much better than not doing anything, because we know that one of
                            // the fonts have characters we need, so there is a bit of hope involved here
                            // It is likely that we only have added one font, and it is likely that it is
                            // a non-subset version of a subset or a reduced type1 font or similar.
                            da.setFontName(afr.fontName);
                        }
                        setDefaultAppearance(da.toAppearanceString());
                    }
                } else {
                    form->ensureFontsForAllCharacters(content->toStr(), fontName);
                }
            } else {
                // This is wrong, there has to be a Tf in DA
            }
        }
    }

    obj.getDict()->set("V", Object(content ? std::string { content->toStr() } : std::string()));
    xref->setModifiedObject(&obj, ref);
    updateChildrenAppearance();
}

void FormFieldText::setAppearanceContent(std::unique_ptr<GooString> new_content)
{
    internalContent.reset();

    if (new_content) {
        internalContent = std::move(new_content);
    }
    updateChildrenAppearance();
}

FormFieldText::~FormFieldText() = default;

void FormFieldText::reset(const std::vector<std::string> &excludedFields)
{
    if (!isAmongExcludedFields(excludedFields)) {
        setContent(defaultContent ? defaultContent->copy() : nullptr);
        if (defaultContent == nullptr) {
            obj.getDict()->remove("V");
        }
    }

    resetChildren(excludedFields);
}

double FormFieldText::getTextFontSize()
{
    std::vector<std::string> daToks;
    const std::optional<size_t> idx = parseDA(&daToks);
    double fontSize = -1;
    if (idx) {
        char *p = nullptr;
        fontSize = strtod(daToks[*idx].c_str(), &p);
        if (!p || *p) {
            fontSize = -1;
        }
    }
    return fontSize;
}

void FormFieldText::setTextFontSize(int fontSize)
{
    if (fontSize > 0 && obj.isDict()) {
        std::vector<std::string> daToks;
        const std::optional<size_t> idx = parseDA(&daToks);
        if (!idx) {
            error(errSyntaxError, -1, "FormFieldText:: invalid DA object");
            return;
        }
        defaultAppearance.clear();
        for (std::size_t i = 0; i < daToks.size(); ++i) {
            if (i > 0) {
                defaultAppearance.push_back(' ');
            }
            if (i == idx) {
                GooString::appendf(defaultAppearance, "{0:d}", fontSize);
            } else {
                defaultAppearance.append(daToks[i]);
            }
        }
        obj.dictSet("DA", Object(std::string { defaultAppearance }));
        xref->setModifiedObject(&obj, ref);
        updateChildrenAppearance();
    }
}

std::optional<size_t> FormFieldText::tokenizeDA(const std::string &da, std::vector<std::string> *daToks, const char *searchTok)
{
    std::optional<size_t> idx;
    if (daToks) {
        size_t i = 0;
        size_t j = 0;
        while (i < da.size()) {
            while (i < da.size() && Lexer::isSpace(da[i])) {
                ++i;
            }
            if (i < da.size()) {
                for (j = i + 1; j < da.size() && !Lexer::isSpace(da[j]); ++j) { }
                std::string tok(da, i, j - i);
                if (searchTok && tok == searchTok) {
                    idx = daToks->size();
                }
                daToks->emplace_back(std::move(tok));
                i = j;
            }
        }
    }
    return idx;
}

std::optional<size_t> FormFieldText::parseDA(std::vector<std::string> *daToks) const
{
    if (obj.isDict()) {
        Object objDA(obj.dictLookup("DA"));
        if (objDA.isString()) {
            const std::string &da = objDA.getString();
            const std::optional<size_t> tfIndex = tokenizeDA(da, daToks, "Tf");
            if (tfIndex) {
                return tfIndex.value() - 1;
            }
        }
    }
    return {};
}

//------------------------------------------------------------------------
// FormFieldChoice
//------------------------------------------------------------------------
FormFieldChoice::FormFieldChoice(PDFDoc *docA, Object &&aobj, const Ref refA, FormField *parentA, std::set<int> *usedParents) : FormField(docA, std::move(aobj), refA, parentA, usedParents, formChoice)
{
    int numChoices = 0;
    editedChoice = nullptr;
    appearanceSelectedChoice = nullptr;
    topIdx = 0;

    Dict *dict = obj.getDict();
    Object obj1;

    combo = edit = multiselect = doNotSpellCheck = doCommitOnSelChange = false;

    obj1 = Form::fieldLookup(dict, "Ff");
    if (obj1.isInt()) {
        int flags = obj1.getInt();
        if (flags & 0x20000) { // 18 -> Combo
            combo = true;
        }
        if (flags & 0x40000) { // 19 -> Edit
            edit = true;
        }
        if (flags & 0x200000) { // 22 -> MultiSelect
            multiselect = true;
        }
        if (flags & 0x400000) { // 23 -> DoNotSpellCheck
            doNotSpellCheck = true;
        }
        if (flags & 0x4000000) { // 27 -> CommitOnSelChange
            doCommitOnSelChange = true;
        }
    }

    obj1 = dict->lookup("TI");
    if (obj1.isInt()) {
        topIdx = obj1.getInt();
        if (topIdx < 0) {
            error(errSyntaxError, -1, "FormFieldChoice:: invalid topIdx entry");
            topIdx = 0;
        }
    }

    obj1 = Form::fieldLookup(dict, "Opt");
    if (obj1.isArray()) {
        numChoices = obj1.arrayGetLength();
        choices.resize(numChoices);

        for (int i = 0; i < numChoices; i++) {
            Object obj2 = obj1.arrayGet(i);
            if (obj2.isString()) {
                choices[i].optionName = obj2.takeString();
            } else if (obj2.isArray()) { // [Export_value, Displayed_text]
                if (obj2.arrayGetLength() < 2) {
                    error(errSyntaxError, -1, "FormWidgetChoice:: invalid Opt entry -- array's length < 2");
                    continue;
                }
                Object obj3 = obj2.arrayGet(0);
                if (obj3.isString()) {
                    choices[i].exportVal = obj3.takeString();
                } else {
                    error(errSyntaxError, -1, "FormWidgetChoice:: invalid Opt entry -- exported value not a string");
                }

                obj3 = obj2.arrayGet(1);
                if (obj3.isString()) {
                    choices[i].optionName = obj3.takeString();
                } else {
                    error(errSyntaxError, -1, "FormWidgetChoice:: invalid Opt entry -- choice name not a string");
                }
            } else {
                error(errSyntaxError, -1, "FormWidgetChoice:: invalid {0:d} Opt entry", i);
            }
        }
    } else {
        // empty choice
    }

    // Find selected items
    // Note: PDF specs say that /V has precedence over /I, but acroread seems to
    // do the opposite. We do the same.
    obj1 = Form::fieldLookup(dict, "I");
    if (obj1.isArray()) {
        for (int i = 0; i < obj1.arrayGetLength(); i++) {
            Object obj2 = obj1.arrayGet(i);
            if (obj2.isInt() && obj2.getInt() >= 0 && obj2.getInt() < numChoices) {
                choices[obj2.getInt()].selected = true;
            }
        }
    } else {
        // Note: According to PDF specs, /V should *never* contain the exportVal.
        // However, if /Opt is an array of (exportVal,optionName) pairs, acroread
        // seems to expect the exportVal instead of the optionName and so we do too.
        fillChoices(fillValue);
    }

    fillChoices(fillDefaultValue);
}

void FormFieldChoice::fillChoices(FillValueType fillType)
{
    const char *key = fillType == fillDefaultValue ? "DV" : "V";
    Dict *dict = obj.getDict();
    Object obj1;

    obj1 = Form::fieldLookup(dict, key);
    if (obj1.isString() || obj1.isArray()) {
        if (fillType == fillDefaultValue) {
            defaultChoices.resize(choices.size());
        }

        if (obj1.isString()) {
            bool optionFound = false;

            const size_t numChoices = choices.size();
            for (size_t i = 0; i < numChoices; i++) {
                if (choices[i].exportVal) {
                    if (choices[i].exportVal->compare(obj1.getString()) == 0) {
                        optionFound = true;
                    }
                } else if (choices[i].optionName) {
                    if (choices[i].optionName->compare(obj1.getString()) == 0) {
                        optionFound = true;
                    }
                }

                if (optionFound) {
                    if (fillType == fillDefaultValue) {
                        defaultChoices[i] = true;
                    } else {
                        choices[i].selected = true;
                    }
                    break; // We've determined that this option is selected. No need to keep on scanning
                }
            }

            // Set custom value if /V doesn't refer to any predefined option and the field is user-editable
            if (fillType == fillValue && !optionFound && edit) {
                editedChoice = obj1.takeString();
            }
        } else if (obj1.isArray()) {
            const size_t numChoices = choices.size();
            for (size_t i = 0; i < numChoices; i++) {
                for (int j = 0; j < obj1.arrayGetLength(); j++) {
                    const Object obj2 = obj1.arrayGet(j);
                    if (!obj2.isString()) {
                        error(errSyntaxError, -1, "FormWidgetChoice:: {0:s} array contains a non string object", key);
                        continue;
                    }

                    bool matches = false;

                    if (choices[i].exportVal) {
                        if (choices[i].exportVal->compare(obj2.getString()) == 0) {
                            matches = true;
                        }
                    } else if (choices[i].optionName) {
                        if (choices[i].optionName->compare(obj2.getString()) == 0) {
                            matches = true;
                        }
                    }

                    if (matches) {
                        if (fillType == fillDefaultValue) {
                            defaultChoices[i] = true;
                        } else {
                            choices[i].selected = true;
                        }
                        break; // We've determined that this option is selected. No need to keep on scanning
                    }
                }
            }
        }
    }
}

FormFieldChoice::~FormFieldChoice() = default;

void FormFieldChoice::print(int indent)
{
    printf("%*s- (%d %d): [choice] terminal: %s children: %zu\n", indent, "", ref.num, ref.gen, terminal ? "Yes" : "No", terminal ? widgets.size() : children.size());
}

void FormFieldChoice::updateSelection()
{
    Object objV;
    std::unique_ptr<Array> iArray;

    if (edit && editedChoice) {
        // This is an editable combo-box with user-entered text
        objV = Object(std::string { editedChoice->toStr() });
    } else {
        const int numSelected = getNumSelected();

        // Create /I array only if multiple selection is allowed (as per PDF spec)
        if (multiselect) {
            iArray = std::make_unique<Array>(xref);
        }

        if (numSelected == 0) {
            // No options are selected
            objV = Object(std::string());
        } else if (numSelected == 1) {
            // Only one option is selected
            const int numChoices = choices.size();
            for (int i = 0; i < numChoices; i++) {
                if (choices[i].selected) {
                    if (multiselect) {
                        iArray->add(Object(i));
                    }

                    if (choices[i].exportVal) {
                        objV = Object(std::string { choices[i].exportVal->toStr() });
                    } else if (choices[i].optionName) {
                        objV = Object(std::string { choices[i].optionName->toStr() });
                    }

                    break; // We've just written the selected option. No need to keep on scanning
                }
            }
        } else {
            // More than one option is selected
            auto vArray = std::make_unique<Array>(xref);
            const int numChoices = choices.size();
            for (int i = 0; i < numChoices; i++) {
                if (choices[i].selected) {
                    if (multiselect) {
                        iArray->add(Object(i));
                    }

                    if (choices[i].exportVal) {
                        vArray->add(Object(std::string { choices[i].exportVal->toStr() }));
                    } else if (choices[i].optionName) {
                        vArray->add(Object(std::string { choices[i].optionName->toStr() }));
                    }
                }
            }
            objV = Object(std::move(vArray));
        }
    }

    obj.getDict()->set("V", std::move(objV));
    if (multiselect) {
        obj.getDict()->set("I", Object(std::move(iArray)));
    } else {
        obj.getDict()->set("I", Object::null());
    }
    xref->setModifiedObject(&obj, ref);
    updateChildrenAppearance();
}

void FormFieldChoice::unselectAll()
{
    for (FormFieldChoiceOption &choice : choices) {
        choice.selected = false;
    }
}

void FormFieldChoice::deselectAll()
{
    editedChoice.reset();

    unselectAll();
    updateSelection();
}

void FormFieldChoice::toggle(int i)
{
    editedChoice.reset();

    choices[i].selected = !choices[i].selected;
    updateSelection();
}

void FormFieldChoice::select(int i)
{
    editedChoice.reset();

    if (!multiselect) {
        unselectAll();
    }

    choices[i].selected = true;
    updateSelection();
}

void FormFieldChoice::setEditChoice(std::unique_ptr<GooString> new_content)
{
    editedChoice.reset();

    unselectAll();

    if (new_content) {
        editedChoice = std::move(new_content);

        // append the unicode marker <FE FF> if needed
        if (!hasUnicodeByteOrderMark(editedChoice->toStr())) {
            prependUnicodeByteOrderMark(editedChoice->toNonConstStr());
        }
    }
    updateSelection();
}

void FormFieldChoice::setAppearanceChoiceContent(std::unique_ptr<GooString> new_content)
{
    appearanceSelectedChoice.reset();

    if (new_content) {
        appearanceSelectedChoice = std::move(new_content);

        // append the unicode marker <FE FF> if needed
        if (!hasUnicodeByteOrderMark(appearanceSelectedChoice->toStr())) {
            prependUnicodeByteOrderMark(appearanceSelectedChoice->toNonConstStr());
        }
    }
    updateChildrenAppearance();
}

const GooString *FormFieldChoice::getEditChoice() const
{
    return editedChoice.get();
}

int FormFieldChoice::getNumSelected() const
{
    int cnt = 0;
    for (const FormFieldChoiceOption &choice : choices) {
        if (choice.selected) {
            cnt++;
        }
    }
    return cnt;
}

const GooString *FormFieldChoice::getSelectedChoice() const
{
    if (edit && editedChoice) {
        return editedChoice.get();
    }

    for (const FormFieldChoiceOption &choice : choices) {
        if (choice.optionName && choice.selected) {
            return choice.optionName.get();
        }
    }

    return nullptr;
}

void FormFieldChoice::reset(const std::vector<std::string> &excludedFields)
{
    if (!isAmongExcludedFields(excludedFields)) {
        editedChoice.reset();

        if (defaultChoices.size() == choices.size()) {
            for (size_t i = 0; i < choices.size(); i++) {
                choices[i].selected = defaultChoices[i];
            }
        } else {
            unselectAll();
        }
    }

    resetChildren(excludedFields);

    updateSelection();
}

//------------------------------------------------------------------------
// FormFieldSignature
//------------------------------------------------------------------------
FormFieldSignature::FormFieldSignature(PDFDoc *docA, Object &&dict, const Ref refA, FormField *parentA, std::set<int> *usedParents) : FormField(docA, std::move(dict), refA, parentA, usedParents, formSignature)
{
    signature_info = new SignatureInfo();
    parseInfo();
}

FormFieldSignature::~FormFieldSignature()
{
    delete signature_info;
}

void FormFieldSignature::setSignature(std::vector<unsigned char> &&sig)
{
    signature = std::move(sig);
}

const GooString &FormFieldSignature::getCustomAppearanceContent() const
{
    return customAppearanceContent;
}

void FormFieldSignature::setCustomAppearanceContent(const GooString &s)
{
    customAppearanceContent = GooString(s.toStr());
}

const GooString &FormFieldSignature::getCustomAppearanceLeftContent() const
{
    return customAppearanceLeftContent;
}

void FormFieldSignature::setCustomAppearanceLeftContent(const GooString &s)
{
    customAppearanceLeftContent = GooString(s.toStr());
}

double FormFieldSignature::getCustomAppearanceLeftFontSize() const
{
    return customAppearanceLeftFontSize;
}

void FormFieldSignature::setCustomAppearanceLeftFontSize(double size)
{
    customAppearanceLeftFontSize = size;
}

Ref FormFieldSignature::getImageResource() const
{
    return imageResource;
}

void FormFieldSignature::setImageResource(const Ref imageResourceA)
{
    imageResource = imageResourceA;
}

void FormFieldSignature::setCertificateInfo(std::unique_ptr<X509CertificateInfo> &certInfo)
{
    certificate_info.swap(certInfo);
}

FormWidget *FormFieldSignature::getCreateWidget()
{
    ::FormWidget *fw = getWidget(0);
    if (!fw) {
        error(errSyntaxError, 0, "FormFieldSignature: was asked for widget and didn't had one, creating it");
        _createWidget(&obj, ref);
        fw = getWidget(0);
        fw->createWidgetAnnotation();
    }
    return fw;
}

void FormFieldSignature::parseInfo()
{
    if (!obj.isDict()) {
        return;
    }

    // retrieve PKCS#7
    Object sig_dict = obj.dictLookup("V");
    if (!sig_dict.isDict()) {
        return;
    }

    byte_range = sig_dict.dictLookup("ByteRange");

    Object contents_obj = sig_dict.dictLookup("Contents");
    if (contents_obj.isString()) {
        auto signatureString = contents_obj.takeString();
        signature = std::vector<unsigned char>(signatureString->c_str(), signatureString->c_str() + signatureString->size());
    }

    Object location_obj = sig_dict.dictLookup("Location");
    if (location_obj.isString()) {
        signature_info->setLocation(location_obj.takeString());
    }

    Object reason_obj = sig_dict.dictLookup("Reason");
    if (reason_obj.isString()) {
        signature_info->setReason(reason_obj.takeString());
    }

    // retrieve SigningTime
    Object time_of_signing = sig_dict.dictLookup("M");
    if (time_of_signing.isString()) {
        const std::string &time_str = time_of_signing.getString();
        signature_info->setSigningTime(dateStringToTime(time_str)); // Put this information directly in SignatureInfo object
    }

    // check if subfilter is supported for signature validation, only detached signatures work for now
    Object subfilterName = sig_dict.dictLookup("SubFilter");
    if (subfilterName.getType() == objName) {
        signature_type = CryptoSign::signatureTypeFromString(subfilterName.getNameString());
        switch (signature_type) {
        case CryptoSign::SignatureType::adbe_pkcs7_sha1:
        case CryptoSign::SignatureType::adbe_pkcs7_detached:
        case CryptoSign::SignatureType::ETSI_CAdES_detached:
        case CryptoSign::SignatureType::g10c_pgp_signature_detached:
            signature_info->setSubFilterSupport(true);
            break;
        case CryptoSign::SignatureType::unknown_signature_type:
        case CryptoSign::SignatureType::unsigned_signature_field:
            break;
        }
    }
}

void FormFieldSignature::hashSignedDataBlock(CryptoSign::VerificationInterface *handler, Goffset block_len)
{
    if (!handler) {
        return;
    }
    const int BLOCK_SIZE = 4096;
    unsigned char signed_data_buffer[BLOCK_SIZE];

    Goffset i = 0;
    while (i < block_len) {
        Goffset bytes_left = block_len - i;
        if (bytes_left < BLOCK_SIZE) {
            doc->getBaseStream()->doGetChars(static_cast<int>(bytes_left), signed_data_buffer);
            handler->addData(signed_data_buffer, static_cast<int>(bytes_left));
            i = block_len;
        } else {
            doc->getBaseStream()->doGetChars(BLOCK_SIZE, signed_data_buffer);
            handler->addData(signed_data_buffer, BLOCK_SIZE);
            i += BLOCK_SIZE;
        }
    }
}

CryptoSign::SignatureType FormWidgetSignature::signatureType() const
{
    return static_cast<FormFieldSignature *>(field)->getSignatureType();
}

void FormWidgetSignature::setSignatureType(CryptoSign::SignatureType fst)
{
    static_cast<FormFieldSignature *>(field)->setSignatureType(fst);
}

SignatureInfo *FormFieldSignature::validateSignatureAsync(bool doVerifyCert, bool forceRevalidation, time_t validationTime, bool ocspRevocationCheck, bool enableAIA, const std::function<void()> &doneCallback)
{
    auto backend = CryptoSign::Factory::createActive();
    if (!backend) {
        if (doneCallback) {
            doneCallback();
        }
        return signature_info;
    }

    if (signature_info->getSignatureValStatus() != SIGNATURE_NOT_VERIFIED && !forceRevalidation) {
        if (doneCallback) {
            doneCallback();
        }
        return signature_info;
    }

    if (signature.empty()) {
        error(errSyntaxError, 0, "Invalid or missing Signature string");
        if (doneCallback) {
            doneCallback();
        }
        return signature_info;
    }

    if (!byte_range.isArray()) {
        error(errSyntaxError, 0, "Invalid or missing ByteRange array");
        if (doneCallback) {
            doneCallback();
        }
        return signature_info;
    }

    int arrayLen = byte_range.arrayGetLength();
    if (arrayLen < 2) {
        error(errSyntaxError, 0, "Too few elements in ByteRange array");
        if (doneCallback) {
            doneCallback();
        }
        return signature_info;
    }

    // Some signatures are supposed to be padded with zeroes, but are instead padded with crap
    // so preprocess them before sending them into the slightly stricter cryptobackend
    auto [unpadded, _] = getCheckedSignature();
    if (!unpadded) {
        error(errSyntaxError, 0, "Invalid or missing Signature string");
        return signature_info;
    }

    signature_handler = backend->createVerificationHandler(std::move(*unpadded), signature_type);

    if (!signature_handler) {
        if (doneCallback) {
            doneCallback();
        }
        return signature_info;
    }

    Goffset fileLength = doc->getBaseStream()->getLength();
    for (int i = 0; i < arrayLen / 2; i++) {
        Object offsetObj = byte_range.arrayGet(i * 2);
        Object lenObj = byte_range.arrayGet(i * 2 + 1);

        if (!offsetObj.isIntOrInt64() || !lenObj.isIntOrInt64()) {
            error(errSyntaxError, 0, "Illegal values in ByteRange array");
            if (doneCallback) {
                doneCallback();
            }
            return signature_info;
        }

        Goffset offset = offsetObj.getIntOrInt64();
        Goffset len = lenObj.getIntOrInt64();

        if (offset < 0 || offset >= fileLength || len < 0 || len > fileLength || offset + len > fileLength) {
            error(errSyntaxError, 0, "Illegal values in ByteRange array");
            if (doneCallback) {
                doneCallback();
            }
            return signature_info;
        }

        doc->getBaseStream()->setPos(offset);
        hashSignedDataBlock(signature_handler.get(), len);
    }

    if (!signature_info->isSubfilterSupported()) {
        error(errUnimplemented, 0, "Unable to validate this type of signature");
        if (doneCallback) {
            doneCallback();
        }
        return signature_info;
    }
    const SignatureValidationStatus sig_val_state = signature_handler->validateSignature();
    signature_info->setSignatureValStatus(sig_val_state);
    signature_info->setSignerName(signature_handler->getSignerName());
    signature_info->setSubjectDN(signature_handler->getSignerSubjectDN());
    signature_info->setHashAlgorithm(signature_handler->getHashAlgorithm());

    // verify if signature contains a 'signing time' attribute
    if (signature_handler->getSigningTime() != std::chrono::system_clock::time_point {}) {
        signature_info->setSigningTime(std::chrono::system_clock::to_time_t(signature_handler->getSigningTime()));
    }

    signature_info->setCertificateInfo(signature_handler->getCertificateInfo());

    if (sig_val_state != SIGNATURE_VALID || !doVerifyCert) {
        if (doneCallback) {
            doneCallback();
        }
        return signature_info;
    }

    signature_handler->validateCertificateAsync(std::chrono::system_clock::from_time_t(validationTime), ocspRevocationCheck, enableAIA, doneCallback);

    return signature_info;
}

CertificateValidationStatus FormFieldSignature::validateSignatureResult()
{
    if (!signature_handler) {
        return CERTIFICATE_GENERIC_ERROR;
    }
    return signature_handler->validateCertificateResult();
}

std::vector<Goffset> FormFieldSignature::getSignedRangeBounds() const
{
    std::vector<Goffset> range_vec;
    if (byte_range.isArray()) {
        if (byte_range.arrayGetLength() == 4) {
            for (int i = 0; i < 2; ++i) {
                const Object offsetObj(byte_range.arrayGet(2 * i));
                const Object lenObj(byte_range.arrayGet(2 * i + 1));
                if (offsetObj.isIntOrInt64() && lenObj.isIntOrInt64()) {
                    const Goffset offset = offsetObj.getIntOrInt64();
                    const Goffset len = lenObj.getIntOrInt64();
                    range_vec.push_back(offset);
                    range_vec.push_back(offset + len);
                }
            }
        }
    }
    return range_vec;
}

std::pair<std::optional<std::vector<unsigned char>>, int64_t> FormFieldSignature::getCheckedSignature()
{
    const std::vector<Goffset> ranges = getSignedRangeBounds();
    if (ranges.size() != 4) {
        return { {}, 0 };
    }
    if (signature.size() < 150) { // This can't be a valid signature, and it simplifies later validation code.
        return { {}, 0 };
    }
    BaseStream *stream = doc->getBaseStream();
    Goffset checkedFileSize = stream->getLength();
    if (signature_type == CryptoSign::SignatureType::g10c_pgp_signature_detached) {
        // Padding here is done as pgp packets, so keep no need to try to unmangle it
        return { signature, checkedFileSize };
    }
    // we have a asn1 object
    if (signature[0] == 0x30) {
        // 0x80 is indefinite lenth.
        // defined length is anything above 0x80 with the number of bytes used for length in the next bits
        if (signature[1] == 0x80) {
            // infdefinite length, let's just do all of it if it ends with two nulls
            if (signature[signature.size() - 1] == 0 && signature[signature.size() - 2] == 0) {
                return { signature, checkedFileSize };
            }
            return { {}, 0 };
        }
        if (signature[1] > 0x80) {
            size_t lengthLength = signature[1] - 0x80;
            size_t length = 0;
            for (size_t i = 0; i < lengthLength; i++) {
                length <<= 8;
                length += signature[2 + i];
            }
            length += 2 + lengthLength; // we also need the two initial bytes 0x30 and 0x8?  and the number of length bytes
            if (length > signature.size()) {
                return { {}, 0 };
            }
            return { std::vector(signature.data(), signature.data() + length), checkedFileSize };
        }
    }
    return { {}, 0 };
}

void FormFieldSignature::print(int indent)
{
    printf("%*s- (%d %d): [signature] terminal: %s children: %zu\n", indent, "", ref.num, ref.gen, terminal ? "Yes" : "No", terminal ? widgets.size() : children.size());
}

//------------------------------------------------------------------------
// Form
//------------------------------------------------------------------------

Form::Form(PDFDoc *docA) : doc(docA)
{
    Object obj1;

    XRef *xref = doc->getXRef();

    quadding = VariableTextQuadding::leftJustified;
    defaultResources = nullptr;

    Object *acroForm = doc->getCatalog()->getAcroForm();

    needAppearances = acroForm->dictLookup("NeedAppearances").getBoolWithDefaultValue(false);

    obj1 = acroForm->dictLookup("DA");
    if (obj1.isString()) {
        defaultAppearance = std::move(obj1.takeString()->toNonConstStr());
    }

    obj1 = acroForm->dictLookup("Q");
    if (obj1.isInt()) {
        const auto aux = static_cast<VariableTextQuadding>(obj1.getInt());
        if (aux == VariableTextQuadding::leftJustified || aux == VariableTextQuadding::centered || aux == VariableTextQuadding::rightJustified) {
            quadding = static_cast<VariableTextQuadding>(aux);
        }
    }

    resDict = acroForm->dictLookup("DR");
    if (resDict.isDict()) {
        // At a minimum, this dictionary shall contain a Font entry
        obj1 = resDict.dictLookup("Font");
        if (obj1.isDict()) {
            defaultResources = new GfxResources(xref, resDict.getDict(), nullptr);
        }
    }
    if (!defaultResources) {
        resDict.setToNull();
    }

    obj1 = acroForm->dictLookup("Fields");
    if (obj1.isArray()) {
        Array *array = obj1.getArray();
        RefRecursionChecker alreadyReadRefs;
        for (int i = 0; i < array->getLength(); i++) {
            Object obj2 = array->get(i);
            const Object &oref = array->getNF(i);
            if (!oref.isRef()) {
                error(errSyntaxWarning, -1, "Direct object in rootFields");
                continue;
            }

            if (!obj2.isDict()) {
                error(errSyntaxWarning, -1, "Reference in Fields array to an invalid or non existent object");
                continue;
            }

            if (!alreadyReadRefs.insert(oref.getRef())) {
                continue;
            }

            std::set<int> usedParents;
            rootFields.push_back(createFieldFromDict(std::move(obj2), doc, oref.getRef(), nullptr, &usedParents));
        }
    } else {
        error(errSyntaxError, -1, "Can't get Fields array");
    }

    obj1 = acroForm->dictLookup("CO");
    if (obj1.isArray()) {
        Array *array = obj1.getArray();
        calculateOrder.reserve(array->getLength());
        for (int i = 0; i < array->getLength(); i++) {
            const Object &oref = array->getNF(i);
            if (!oref.isRef()) {
                error(errSyntaxWarning, -1, "Direct object in CO");
                continue;
            }
            calculateOrder.push_back(oref.getRef());
        }
    }

    //   for (int i = 0; i < numFields; i++)
    //     rootFields[i]->printTree();
}

Form::~Form()
{
    delete defaultResources;
}

// Look up an inheritable field dictionary entry.
static Object fieldLookup(Dict *field, const char *key, RefRecursionChecker *usedParents)
{
    Dict *dict = field;
    Object obj = dict->lookup(key);
    if (!obj.isNull()) {
        return obj;
    }
    const Object &parent = dict->lookupNF("Parent");
    if (parent.isRef()) {
        const Ref ref = parent.getRef();
        if (usedParents->insert(ref)) {
            Object obj2 = parent.fetch(dict->getXRef());
            if (obj2.isDict()) {
                return fieldLookup(obj2.getDict(), key, usedParents);
            }
        }
    } else if (parent.isDict()) {
        return fieldLookup(parent.getDict(), key, usedParents);
    }
    return Object::null();
}

Object Form::fieldLookup(Dict *field, const char *key)
{
    RefRecursionChecker usedParents;
    return ::fieldLookup(field, key, &usedParents);
}

std::unique_ptr<FormField> Form::createFieldFromDict(Object &&obj, PDFDoc *docA, const Ref aref, FormField *parent, std::set<int> *usedParents)
{
    const Object obj2 = Form::fieldLookup(obj.getDict(), "FT");
    if (obj2.isName("Btn")) {
        return std::make_unique<FormFieldButton>(docA, std::move(obj), aref, parent, usedParents);
    }
    if (obj2.isName("Tx")) {
        return std::make_unique<FormFieldText>(docA, std::move(obj), aref, parent, usedParents);
    }
    if (obj2.isName("Ch")) {
        return std::make_unique<FormFieldChoice>(docA, std::move(obj), aref, parent, usedParents);
    }
    if (obj2.isName("Sig")) {
        return std::make_unique<FormFieldSignature>(docA, std::move(obj), aref, parent, usedParents);
    }
    // we don't have an FT entry => non-terminal field
    return std::make_unique<FormField>(docA, std::move(obj), aref, parent, usedParents);

    return {};
}

static const std::string kOurDictFontNamePrefix = "popplerfont";

std::string Form::findFontInDefaultResources(const std::string &fontFamily, const std::string &fontStyle) const
{
    if (!resDict.isDict()) {
        return {};
    }

    const std::string fontFamilyAndStyle = fontStyle.empty() ? fontFamily : fontFamily + " " + fontStyle;

    Object fontDictObj = resDict.dictLookup("Font");
    assert(fontDictObj.isDict());

    const Dict *fontDict = fontDictObj.getDict();
    for (int i = 0; i < fontDict->getLength(); ++i) {
        const std::string &key = fontDict->getKey(i);
        if (key.starts_with(kOurDictFontNamePrefix)) {
            const Object fontObj = fontDict->getVal(i);
            if (fontObj.isDict("Font")) {
                const Object fontBaseFontObj = fontObj.dictLookup("BaseFont");
                if (fontBaseFontObj.isName(fontFamilyAndStyle)) {
                    return key;
                }
            }
        }
    }

    return {};
}

Form::AddFontResult Form::addFontToDefaultResources(const std::string &fontFamily, const std::string &fontStyle, bool forceName)
{
    FamilyStyleFontSearchResult findFontRes = globalParams->findSystemFontFileForFamilyAndStyle(fontFamily, fontStyle);
    std::vector<std::string> filesToIgnore;
    while (!findFontRes.filepath.empty()) {
        Form::AddFontResult addFontRes = addFontToDefaultResources(findFontRes.filepath, findFontRes.faceIndex, fontFamily, fontStyle, findFontRes.substituted, forceName);
        if (!addFontRes.fontName.empty()) {
            return addFontRes;
        }
        filesToIgnore.emplace_back(findFontRes.filepath);
        findFontRes = globalParams->findSystemFontFileForFamilyAndStyle(fontFamily, fontStyle, filesToIgnore);
    }
    return {};
}

Form::AddFontResult Form::addFontToDefaultResources(const std::string &filepath, int faceIndex, const std::string &fontFamily, const std::string &fontStyle, bool fontSubstitutedIn, bool forceName)
{
    if (!filepath.ends_with(".ttf") && !filepath.ends_with(".ttc") && !filepath.ends_with(".otf")) {
        error(errIO, -1, "We only support embedding ttf/ttc/otf fonts for now. The font file for {0:r} {1:r} was {2:r}", &fontFamily, &fontStyle, &filepath);
        return {};
    }

    const FoFiIdentifierType fontFoFiType = FoFiIdentifier::identifyFile(filepath.c_str());
    if (fontFoFiType != fofiIdTrueType && fontFoFiType != fofiIdTrueTypeCollection && fontFoFiType != fofiIdOpenTypeCFF8Bit && fontFoFiType != fofiIdOpenTypeCFFCID) {
        error(errIO, -1, "We only support embedding ttf/ttc/otf fonts for now. The font file for {0:r} {1:r} was {2:r} of type {3:d}", &fontFamily, &fontStyle, &filepath, fontFoFiType);
        return {};
    }

    const std::string fontFamilyAndStyle = fontStyle.empty() ? fontFamily : fontFamily + " " + fontStyle;

    if (forceName && defaultResources && defaultResources->lookupFont(fontFamilyAndStyle)) {
        error(errInternal, -1, "Form::addFontToDefaultResources: Asked to forceName but font name exists {0:r}", &fontFamilyAndStyle);
        return {};
    }

    // If caller asked for one of the base14 fonts and got something named differently
    // we are only having something close anyways, so don't embed the font program (and
    // when we don't embed the font program, also don't embed widths and the CIDToGIDMap)
    bool embedActualFont = !(fontSubstitutedIn && GfxFont::isBase14Font(fontFamily, fontStyle));

    XRef *xref = doc->getXRef();
    Object fontDict(std::make_unique<Dict>(xref));
    fontDict.dictSet("Type", Object::name("Font"));
    fontDict.dictSet("Subtype", Object::name((embedActualFont ? "Type0" : "Type1")));
    fontDict.dictSet("BaseFont", Object::name(fontFamilyAndStyle));

    if (embedActualFont) {
        fontDict.dictSet("Encoding", Object::name("Identity-H"));
        std::unique_ptr<Array> descendantFonts = std::make_unique<Array>(xref);

        const bool isTrueType = (fontFoFiType == fofiIdTrueType || fontFoFiType == fofiIdTrueTypeCollection);
        std::unique_ptr<Dict> descendantFont = std::make_unique<Dict>(xref);
        descendantFont->set("Type", Object::name("Font"));
        descendantFont->set("Subtype", Object::name(isTrueType ? "CIDFontType2" : "CIDFontType0"));
        descendantFont->set("BaseFont", Object::name(fontFamilyAndStyle));

        {
            // We only support fonts with identity cmaps for now
            auto cidSystemInfo = std::make_unique<Dict>(xref);
            cidSystemInfo->set("Registry", Object(std::string { "Adobe" }));
            cidSystemInfo->set("Ordering", Object(std::string { "Identity" }));
            cidSystemInfo->set("Supplement", Object(0));
            descendantFont->set("CIDSystemInfo", Object(std::move(cidSystemInfo)));
        }

        FT_Library freetypeLib;
        if (FT_Init_FreeType(&freetypeLib)) {
            error(errIO, -1, "FT_Init_FreeType failed");
            return {};
        }
        const std::unique_ptr<FT_Library, void (*)(FT_Library *)> freetypeLibDeleter(&freetypeLib, [](FT_Library *l) { FT_Done_FreeType(*l); });

        FT_Face face;
        if (ft_new_face_from_file(freetypeLib, filepath.c_str(), faceIndex, &face)) {
            error(errIO, -1, "ft_new_face_from_file failed for {0:r}", &filepath);
            return {};
        }
        const std::unique_ptr<FT_Face, void (*)(FT_Face *)> faceDeleter(&face, [](FT_Face *f) { FT_Done_Face(*f); });

        if (FT_Set_Char_Size(face, 1000, 1000, 0, 0)) {
            error(errIO, -1, "FT_Set_Char_Size failed for {0:r}", &filepath);
            return {};
        }

        {
            std::unique_ptr<Dict> fontDescriptor = std::make_unique<Dict>(xref);
            fontDescriptor->set("Type", Object::name("FontDescriptor"));
            fontDescriptor->set("FontName", Object::name(fontFamilyAndStyle));

            // a bit arbirary but the Flags field is mandatory...
            const std::string lowerCaseFontFamily = GooString::toLowerCase(fontFamily);
            if (lowerCaseFontFamily.contains("serif") && !lowerCaseFontFamily.contains("sans")) {
                fontDescriptor->set("Flags", Object(2)); // Serif
            } else {
                fontDescriptor->set("Flags", Object(0)); // Sans Serif
            }

            auto fontBBox = std::make_unique<Array>(xref);
            fontBBox->add(Object(static_cast<int>(face->bbox.xMin)));
            fontBBox->add(Object(static_cast<int>(face->bbox.yMin)));
            fontBBox->add(Object(static_cast<int>(face->bbox.xMax)));
            fontBBox->add(Object(static_cast<int>(face->bbox.yMax)));
            fontDescriptor->set("FontBBox", Object(std::move(fontBBox)));

            fontDescriptor->set("Ascent", Object(static_cast<int>(face->ascender)));

            fontDescriptor->set("Descent", Object(static_cast<int>(face->descender)));

            {
                const std::unique_ptr<GooFile> file(GooFile::open(filepath));
                if (!file) {
                    error(errIO, -1, "Failed to open {0:r}", &filepath);
                    return {};
                }
                const Goffset fileSize = file->size();
                if (fileSize < 0) {
                    error(errIO, -1, "Failed to get file size for {0:r}", &filepath);
                    return {};
                }
                // GooFile::read only takes an integer so for now we don't support huge fonts
                if (fileSize > std::numeric_limits<int>::max()) {
                    error(errIO, -1, "Font size is too big {0:r}", &filepath);
                    return {};
                }
                std::vector<char> data;
                data.resize(fileSize);
                const Goffset bytesRead = file->read(data.data(), static_cast<int>(fileSize), 0);
                if (bytesRead != fileSize) {
                    error(errIO, -1, "Failed to read contents of {0:r}", &filepath);
                    return {};
                }

                if (isTrueType) {
                    const Ref fontFile2Ref = xref->addStreamObject(std::make_unique<Dict>(xref), std::move(data), StreamCompression::Compress);
                    fontDescriptor->set("FontFile2", Object(fontFile2Ref));
                } else {
                    auto fontFileStreamDict = std::make_unique<Dict>(xref);
                    fontFileStreamDict->set("Subtype", Object::name("OpenType"));
                    const Ref fontFile3Ref = xref->addStreamObject(std::move(fontFileStreamDict), std::move(data), StreamCompression::Compress);
                    fontDescriptor->set("FontFile3", Object(fontFile3Ref));
                }
            }

            const Ref fontDescriptorRef = xref->addIndirectObject(Object(std::move(fontDescriptor)));
            descendantFont->set("FontDescriptor", Object(fontDescriptorRef));
        }

        static const int basicMultilingualMaxCode = 65535;

        const std::unique_ptr<FoFiTrueType> fft = FoFiTrueType::load(filepath.c_str(), faceIndex);
        if (fft) {

            // Look for the Unicode BMP cmaps, which are 0/3 or 3/1
            int unicodeBMPCMap = fft->findCmap(0, 3);
            if (unicodeBMPCMap < 0) {
                unicodeBMPCMap = fft->findCmap(3, 1);
            }
            if (unicodeBMPCMap < 0) {
                error(errIO, -1, "Font does not have an unicode BMP cmap {0:r}", &filepath);
                return {};
            }

            CIDFontsWidthsBuilder fontsWidths;

            for (int code = 0; code <= basicMultilingualMaxCode; ++code) {
                const int glyph = fft->mapCodeToGID(unicodeBMPCMap, code);
                if (FT_Load_Glyph(face, glyph, FT_LOAD_DEFAULT | FT_LOAD_NO_HINTING)) {
                    fontsWidths.addWidth(code, 0);
                } else {
                    fontsWidths.addWidth(code, static_cast<int>(face->glyph->metrics.horiAdvance));
                }
            }
            auto widths = std::make_unique<Array>(xref);
            for (const auto &segment : fontsWidths.takeSegments()) {
                std::visit(
                        [&widths, &xref](auto &&s) {
                            using T = std::decay_t<decltype(s)>;
                            if constexpr (std::is_same_v<T, CIDFontsWidthsBuilder::ListSegment>) {
                                widths->add(Object(s.first));
                                auto widthsInner = std::make_unique<Array>(xref);
                                for (const auto &w : s.widths) {
                                    widthsInner->add(Object(w));
                                }
                                widths->add(Object(std::move(widthsInner)));
                            } else if constexpr (std::is_same_v<T, CIDFontsWidthsBuilder::RangeSegment>) {
                                widths->add(Object(s.first));
                                widths->add(Object(s.last));
                                widths->add(Object(s.width));
                            } else {
                                static_assert(always_false_v<T>, "non-exhaustive visitor");
                            }
                        },
                        segment);
            }
            descendantFont->set("W", Object(std::move(widths)));

            std::vector<char> data;
            data.reserve(2 * basicMultilingualMaxCode);

            for (int code = 0; code <= basicMultilingualMaxCode; ++code) {
                const int glyph = fft->mapCodeToGID(unicodeBMPCMap, code);
                data.push_back(static_cast<char>(glyph >> 8));
                data.push_back(static_cast<char>(glyph & 0xff));
            }
            const Ref cidToGidMapStream = xref->addStreamObject(std::make_unique<Dict>(xref), std::move(data), StreamCompression::Compress);
            descendantFont->set("CIDToGIDMap", Object(cidToGidMapStream));
        }

        descendantFonts->add(Object(std::move(descendantFont)));

        fontDict.dictSet("DescendantFonts", Object(std::move(descendantFonts)));
    }

    const Ref fontDictRef = xref->addIndirectObject(fontDict);

    std::string dictFontName = forceName ? fontFamilyAndStyle : kOurDictFontNamePrefix;
    Object *acroForm = doc->getCatalog()->getAcroForm();
    if (resDict.isDict()) {
        Ref fontDictObjRef;
        Object fontDictObj = resDict.getDict()->lookup("Font", &fontDictObjRef);
        assert(fontDictObj.isDict());
        dictFontName = fontDictObj.getDict()->findAvailableKey(dictFontName);
        fontDictObj.dictSet(dictFontName, Object(fontDictRef));

        if (fontDictObjRef != Ref::INVALID()) {
            xref->setModifiedObject(&fontDictObj, fontDictObjRef);
        } else {
            Ref resDictRef;
            acroForm->getDict()->lookup("DR", &resDictRef);
            if (resDictRef != Ref::INVALID()) {
                xref->setModifiedObject(&resDict, resDictRef);
            } else {
                doc->getCatalog()->setAcroFormModified();
            }
        }

        // maybe we can do something to reuse the existing data instead of recreating from scratch?
        delete defaultResources;
        defaultResources = new GfxResources(xref, resDict.getDict(), nullptr);
    } else {
        auto fontsDict = std::make_unique<Dict>(xref);
        fontsDict->set(dictFontName, Object(fontDictRef));

        auto defaultResourcesDict = std::make_unique<Dict>(xref);
        defaultResourcesDict->set("Font", Object(std::move(fontsDict)));

        assert(!defaultResources);
        defaultResources = new GfxResources(xref, defaultResourcesDict.get(), nullptr);
        resDict = Object(std::move(defaultResourcesDict));

        acroForm->dictSet("DR", resDict.copy());
        doc->getCatalog()->setAcroFormModified();
    }

    return { .fontName = dictFontName, .ref = fontDictRef };
}

std::string Form::getFallbackFontForChar(Unicode uChar, const GfxFont &fontToEmulate) const
{
    const UCharFontSearchResult res = globalParams->findSystemFontFileForUChar(uChar, fontToEmulate);

    return findFontInDefaultResources(res.family, res.style);
}

std::vector<Form::AddFontResult> Form::ensureFontsForAllCharacters(const std::string &unicodeText, const std::string &pdfFontNameToEmulate, GfxResources *fieldResources)
{
    GfxResources *resources = fieldResources ? fieldResources : defaultResources;
    std::shared_ptr<GfxFont> f;
    if (!resources) {
        // There's no resources, so create one with the needed font name
        addFontToDefaultResources(pdfFontNameToEmulate, "", /*forceName*/ true);
        resources = defaultResources;
    }
    f = resources->lookupFont(pdfFontNameToEmulate);
    const CharCodeToUnicode *ccToUnicode = f ? f->getToUnicode() : nullptr;
    if (!ccToUnicode) {
        error(errInternal, -1, "Form::ensureFontsForAllCharacters: No ccToUnicode, this should not happen");
        return {}; // will never happen with current code
    }

    std::vector<AddFontResult> newFonts;

    // If the text has some characters that are not available in the font, try adding a font for those
    std::unordered_set<Unicode> seen;
    for (size_t i = 2; i < unicodeText.size(); i += 2) {
        Unicode uChar = static_cast<unsigned char>(unicodeText[i]) << 8;
        uChar += static_cast<unsigned char>(unicodeText[i + 1]);

        if (uChar < 128 && !std::isprint(static_cast<unsigned char>(uChar))) {
            continue;
        }
        const auto [_, inserted] = seen.insert(uChar);
        if (!inserted) {
            continue;
        }

        CharCode c;
        bool addFont = false;
        if (ccToUnicode->mapToCharCode(&uChar, &c, 1)) {
            if (f->isCIDFont()) {
                const auto *cidFont = static_cast<const GfxCIDFont *>(f.get());
                if (c < cidFont->getCIDToGIDLen() && c != 0 && c != '\r' && c != '\n') {
                    const int glyph = cidFont->getCIDToGID()[c];
                    if (glyph == 0) {
                        addFont = true;
                    }
                }
            }
        } else {
            addFont = true;
        }

        if (addFont) {
            Form::AddFontResult res = doGetAddFontToDefaultResources(uChar, *f);
            if (res.ref != Ref::INVALID()) {
                newFonts.emplace_back(res);
            }
        }
    }

    return newFonts;
}

Form::AddFontResult Form::doGetAddFontToDefaultResources(Unicode uChar, const GfxFont &fontToEmulate)
{
    const UCharFontSearchResult res = globalParams->findSystemFontFileForUChar(uChar, fontToEmulate);

    std::string pdfFontName = findFontInDefaultResources(res.family, res.style);
    if (pdfFontName.empty()) {
        return addFontToDefaultResources(res.filepath, res.faceIndex, res.family, res.style,
                                         true /*This is called when a string contains a uChar that is not present in the font for that string so we find a another font to display it, thus it's always a 'substitute' font*/,
                                         false /*forceName*/);
    }
    return { .fontName = pdfFontName, .ref = Ref::INVALID() };
}

void Form::postWidgetsLoad()
{
    // We create the widget annotations associated to
    // every form widget here, because the AnnotWidget constructor
    // needs the form object that gets from the catalog. When constructing
    // a FormWidget the Catalog is still creating the form object
    for (auto &rootField : rootFields) {
        rootField->fillChildrenSiblingsID();
        rootField->createWidgetAnnotations();
    }
}

FormWidget *Form::findWidgetByRef(Ref aref)
{
    for (auto &rootField : rootFields) {
        FormWidget *result = rootField->findWidgetByRef(aref);
        if (result) {
            return result;
        }
    }
    return nullptr;
}

FormField *Form::findFieldByRef(Ref aref) const
{
    for (const auto &rootField : rootFields) {
        FormField *result = rootField->findFieldByRef(aref);
        if (result) {
            return result;
        }
    }
    return nullptr;
}

FormField *Form::findFieldByFullyQualifiedName(const std::string &name) const
{
    for (const auto &rootField : rootFields) {
        FormField *result = rootField->findFieldByFullyQualifiedName(name);
        if (result) {
            return result;
        }
    }
    return nullptr;
}

FormField *Form::findFieldByFullyQualifiedNameOrRef(const std::string &field) const
{
    Ref fieldRef;

    if (field.ends_with(" R") && sscanf(field.c_str(), "%d %d R", &fieldRef.num, &fieldRef.gen) == 2) {
        return findFieldByRef(fieldRef);
    }
    return findFieldByFullyQualifiedName(field);
}

void Form::reset(const std::vector<std::string> &fields, bool excludeFields)
{
    const bool resetAllFields = fields.empty();

    if (resetAllFields) {
        for (auto &rootField : rootFields) {
            rootField->reset(std::vector<std::string>());
        }
    } else {
        if (!excludeFields) {
            FormField *foundField;
            for (const std::string &field : fields) {
                Ref fieldRef;

                if (field.ends_with(" R") && sscanf(field.c_str(), "%d %d R", &fieldRef.num, &fieldRef.gen) == 2) {
                    foundField = findFieldByRef(fieldRef);
                } else {
                    foundField = findFieldByFullyQualifiedName(field);
                }

                if (foundField) {
                    foundField->reset(std::vector<std::string>());
                }
            }
        } else {
            for (auto &rootField : rootFields) {
                rootField->reset(fields);
            }
        }
    }
}

std::string Form::findPdfFontNameToUseForSigning()
{
    static constexpr std::array<const char *, 2> fontsToUseToSign = { "Helvetica", "Arial" };
    for (const char *fontToUseToSign : fontsToUseToSign) {
        std::string pdfFontName = findFontInDefaultResources(fontToUseToSign, "");
        if (!pdfFontName.empty()) {
            return pdfFontName;
        }

        pdfFontName = addFontToDefaultResources(fontToUseToSign, "").fontName;
        if (!pdfFontName.empty()) {
            return pdfFontName;
        }
    }

    error(errInternal, -1, "Form::findPdfFontNameToUseForSigning: No suitable font found'");

    return {};
}

//------------------------------------------------------------------------
// FormPageWidgets
//------------------------------------------------------------------------

FormPageWidgets::FormPageWidgets(Annots *annots, unsigned int page, Form *form)
{
    if (annots && !annots->getAnnots().empty() && form) {

        /* For each entry in the page 'Annots' dict, try to find
           a matching form field */
        for (const std::shared_ptr<Annot> &annot : annots->getAnnots()) {

            if (annot->getType() != Annot::typeWidget) {
                continue;
            }

            if (!annot->getHasRef()) {
                /* Since all entry in a form field's kid dict needs to be
                   indirect references, if this annot isn't indirect, it isn't
                   related to a form field */
                continue;
            }

            Ref r = annot->getRef();

            /* Try to find a form field which either has this Annot in its Kids entry
                or  is merged with this Annot */
            FormWidget *tmp = form->findWidgetByRef(r);
            if (tmp) {
                // We've found a corresponding form field, link it
                tmp->setID(FormWidget::encodeID(page, widgets.size()));
                widgets.push_back(tmp);
            }
        }
    }
}

void FormPageWidgets::addWidgets(const std::vector<std::unique_ptr<FormField>> &addedWidgets, unsigned int page)
{
    if (addedWidgets.empty()) {
        return;
    }

    for (const auto &frmField : addedWidgets) {
        FormWidget *frmWidget = frmField->getWidget(0);
        frmWidget->setID(FormWidget::encodeID(page, widgets.size()));
        widgets.push_back(frmWidget);
    }
}

FormPageWidgets::~FormPageWidgets() = default;
