From 7a9675c54ae0af1d923d77ada47baa033bde49d4 Mon Sep 17 00:00:00 2001 From: Bob Singor Date: Thu, 26 Nov 2026 14:07:15 +0200 Subject: [PATCH] Draw form widgets' borders, button layouts and automatic sizes as Acrobat does Acrobat 26 redrew our fields itself, and its saved drawings are the reference: - Check boxes, radio buttons and push buttons draw every border style: they share the text field's box (WriteFieldBox), and a radio button that shows a circle draws it in the middle of its box, as wide as the box is high, with beveled and inset edges as half circles and underline as the whole circle. BuildCheckboxBoxStream is gone. - A beveled widget border's shaded edges are the background less a quarter, on every field kind (GenerateBorderAP takes the shade). - A push button's picture is fitted twice the border's width in, and its caption sits where Acrobat puts it, with room that grows with the border (ButtonPlate, SplitButton). With no room left the picture is left out. - A field's automatic size is the largest its text fits at, not a step of CPVT's ladder; a list box's fits its widest option, at most 12; a check box's check is as large as Acrobat's. --- core/fpdfdoc/cpdf_appearancegenerator.h | 13 +- .../cpdf_appearancegenerator_common.cpp | 37 +- .../cpdf_appearancegenerator_forms.cpp | 566 +++++++++------ .../cpdf_appearancegenerator_freetext.cpp | 6 +- .../cpdf_appearancegenerator_internal.h | 10 +- .../cpdf_appearancegenerator_unittest.cpp | 354 +++++++-- core/fpdfdoc/cpdf_richtextlayout.cpp | 47 +- core/fpdfdoc/cpdf_richtextlayout.h | 13 +- docs/embedpdf/fork-ledger.md | 38 +- fpdfsdk/BUILD.gn | 3 + .../epdf_appearance_state_embeddertest.cpp | 9 +- fpdfsdk/epdf_richtextlayout_embeddertest.cpp | 88 ++- fpdfsdk/epdf_widget_drawing_embeddertest.cpp | 675 ++++++++++-------- .../epdf_widget_text_size_embeddertest.cpp | 358 ++++++++++ testing/embedpdf_layer_mode_writers.txt | 4 +- 15 files changed, 1568 insertions(+), 653 deletions(-) create mode 100644 fpdfsdk/epdf_widget_text_size_embeddertest.cpp diff --git a/core/fpdfdoc/cpdf_appearancegenerator.h b/core/fpdfdoc/cpdf_appearancegenerator.h index bb11c8a1ea..c72b32d7a1 100644 --- a/core/fpdfdoc/cpdf_appearancegenerator.h +++ b/core/fpdfdoc/cpdf_appearancegenerator.h @@ -38,9 +38,9 @@ class CPDF_AppearanceGenerator { public: // kPushButton: the button's background and border, and its caption (/MK // /CA) centred in the /DA font and colour. One that shows its icon alone - // (/MK /TP 1) draws the normal icon (/MK /I) inside the border, fitted as - // /MK /IF says, and no caption. One that shows both (/MK /TP 2 to 6) - // draws both, each in its part of the button. + // (/MK /TP 1) draws the normal icon (/MK /I) twice the border's width in, + // fitted as /MK /IF says, and no caption. One that shows both (/MK /TP 2 + // to 6) draws both, sharing the button as Acrobat does. enum FormType { kTextField, kComboBox, kListBox, kPushButton }; static void GenerateFormAP(CPDF_Document* doc, @@ -66,9 +66,10 @@ class CPDF_AppearanceGenerator { static void GenerateCheckboxFormAP(CPDF_Document* doc, CPDF_Dictionary* annot_dict); - // A radio button's Off and on appearances: a circle with a dot by default; - // any other symbol /MK /CA names sits in a box, as PDFium's form filler - // draws it. The symbol takes the /DA colour (black by default). + // A radio button's Off and on appearances: by default a circle in the + // middle of the box, as wide as the box is high, with a dot, as Acrobat + // draws it; any other symbol /MK /CA names sits in a box, as PDFium's form + // filler draws it. The symbol takes the /DA colour (black by default). static void GenerateRadioButtonFormAP(CPDF_Document* doc, CPDF_Dictionary* annot_dict); diff --git a/core/fpdfdoc/cpdf_appearancegenerator_common.cpp b/core/fpdfdoc/cpdf_appearancegenerator_common.cpp index 735fcc8cea..8b958589d5 100644 --- a/core/fpdfdoc/cpdf_appearancegenerator_common.cpp +++ b/core/fpdfdoc/cpdf_appearancegenerator_common.cpp @@ -80,20 +80,6 @@ std::vector BorderDash(const fpdfdoc::AnnotBorder& border) { return DashValues(border.dash_array.Get()); } -// The dash operator for |values|; empty when there are none. -ByteString DashOperator(const std::vector& values) { - if (values.empty()) { - return ByteString(); - } - fxcrt::ostringstream dash_stream; - dash_stream << "["; - for (float value : values) { - WriteFloat(dash_stream, value) << " "; - } - dash_stream << "] 0 d\n"; - return ByteString(dash_stream); -} - // /RD as its four numbers, in rectangle order (left, bottom, right, top), as // Acrobat writes it and PDFium reads it. CFX_FloatRect GetRectDifferences(const CPDF_Dictionary* annot_dict) { @@ -411,9 +397,23 @@ ByteString GenerateColorAP(const CFX_Color& color, PaintOperation operation) { NOTREACHED(); } +ByteString DashOperator(const std::vector& values) { + if (values.empty()) { + return ByteString(); + } + fxcrt::ostringstream dash_stream; + dash_stream << "["; + for (float value : values) { + WriteFloat(dash_stream, value) << " "; + } + dash_stream << "] 0 d\n"; + return ByteString(dash_stream); +} + ByteString GenerateBorderAP(const CFX_FloatRect& rect, const BorderStyleInfo& border_style_info, - const CFX_Color& border_color) { + const CFX_Color& border_color, + const CFX_Color& beveled_shade) { const float width = border_style_info.width; if (width <= 0) { return ByteString(); @@ -472,10 +472,11 @@ ByteString GenerateBorderAP(const CFX_FloatRect& rect, WritePoint(app_stream, {left + width, top - width}) << " l\n"; WritePoint(app_stream, {left + width, bottom + width}) << " l f\n"; - const float right_bottom_gray_value = - border_style_info.style == BorderStyle::kBeveled ? 0.5f : 0.75f; app_stream << GenerateColorAP( - CFX_Color::MakeGray(right_bottom_gray_value), PaintOperation::kFill); + border_style_info.style == BorderStyle::kBeveled + ? beveled_shade + : CFX_Color::MakeGray(0.75f), + PaintOperation::kFill); WritePoint(app_stream, {right - half_width, top - half_width}) << " m\n"; WritePoint(app_stream, {right - half_width, bottom + half_width}) << " l\n"; diff --git a/core/fpdfdoc/cpdf_appearancegenerator_forms.cpp b/core/fpdfdoc/cpdf_appearancegenerator_forms.cpp index b47aae5219..8e2a3cc4b6 100644 --- a/core/fpdfdoc/cpdf_appearancegenerator_forms.cpp +++ b/core/fpdfdoc/cpdf_appearancegenerator_forms.cpp @@ -52,6 +52,7 @@ using appearance_generator::APGenerationTarget; using appearance_generator::AppearanceCharacteristics; using appearance_generator::BorderStyleInfo; using appearance_generator::DaFontResolution; +using appearance_generator::DashOperator; using appearance_generator::DefaultAppearanceInfo; using appearance_generator::EmitFieldTextBody; using appearance_generator::GenerateAPDict; @@ -192,8 +193,57 @@ ByteString GenerateComboBoxAP(const CPDF_Dictionary* annot_dict, return ByteString(body_stream); } +// A list box option's text: the string, or the second of a pair. +WideString ListBoxOptionText(const CPDF_Object* opt) { + if (opt->IsString()) { + return opt->GetUnicodeText(); + } + if (const CPDF_Array* opt_array = opt->AsArray()) { + if (RetainPtr item = opt_array->GetDirectObjectAt(1)) { + return item->GetUnicodeText(); + } + } + return WideString(); +} + +// The largest automatic size of a list box's options, as Acrobat 26 caps it. +constexpr float kListBoxAutoSizeCap = 12; + +// A width no option reaches: room to measure a line in without breaking it. +constexpr float kUnboundedWidth = 1e6f; + +// A list box's automatic size, as Acrobat 26 fits it: the widest option fits +// `width` on one line, at most 12. A line is as wide as its size says, so the +// widest option is measured once, at the cap. +float ListBoxAutoSize(const CPDF_Array* opts, + float width, + CPDF_AnnotFontMap& map, + const CPDF_RichTextLayout::Options& options) { + float widest = 0; + for (size_t i = 0, count = opts->size(); i < count; ++i) { + RetainPtr opt = opts->GetDirectObjectAt(i); + if (!opt) { + continue; + } + CPDF_RichTextLayout::Field field; + field.text = ListBoxOptionText(opt.Get()); + field.size = kListBoxAutoSizeCap; + const CPDF_RichTextLayout::Result laid = + ArrangeFieldText(map, options, std::move(field), + CFX_FloatRect(0, 0, kUnboundedWidth, 0)); + for (const CPDF_RichTextLayout::Line& line : laid.lines) { + widest = std::max(widest, line.width); + } + } + if (!(width > 0) || widest <= width) { + return kListBoxAutoSizeCap; + } + return std::floor(kListBoxAutoSizeCap * width / widest * 1000) / 1000; +} + ByteString GenerateListBoxAP(const CPDF_Dictionary* annot_dict, const CFX_FloatRect& body_rect, + float border_width, const CFX_Color& text_color, float font_size, CPDF_AnnotFontMap& map, @@ -203,6 +253,14 @@ ByteString GenerateListBoxAP(const CPDF_Dictionary* annot_dict, if (!opts) { return ByteString(); } + // A row's text starts twice the border in from the edge, as Acrobat's + // does; its highlight reaches the border. + CFX_FloatRect text_rect = body_rect; + text_rect.Deflate(border_width, 0); + const float size = + FXSYS_IsFloatZero(font_size) + ? ListBoxAutoSize(opts.Get(), text_rect.Width(), map, options) + : font_size; RetainPtr selections = ToArray(CPDF_FormField::GetFieldAttrForDict(annot_dict, "I")); @@ -219,14 +277,7 @@ ByteString GenerateListBoxAP(const CPDF_Dictionary* annot_dict, if (RetainPtr opt = opts->GetDirectObjectAt(i)) { CPDF_RichTextLayout::Field field; - if (opt->IsString()) { - field.text = opt->GetUnicodeText(); - } else if (const CPDF_Array* opt_array = opt->AsArray()) { - RetainPtr opt_item = opt_array->GetDirectObjectAt(1); - if (opt_item) { - field.text = opt_item->GetUnicodeText(); - } - } + field.text = ListBoxOptionText(opt.Get()); bool is_selected = false; if (selections) { for (size_t s = 0, ssz = selections->size(); s < ssz; s++) { @@ -238,11 +289,11 @@ ByteString GenerateListBoxAP(const CPDF_Dictionary* annot_dict, } } // A row is one line, from the top of what is left. - field.size = FXSYS_IsFloatZero(font_size) ? 12.0f : font_size; + field.size = size; float item_height = 0; const ByteString row = FieldText( map, options, std::move(field), - CFX_FloatRect(body_rect.left, fy, body_rect.right, fy), &item_height); + CFX_FloatRect(text_rect.left, fy, text_rect.right, fy), &item_height); if (is_selected) { CFX_FloatRect item_rect = CFX_FloatRect( body_rect.left, fy - item_height, body_rect.right, fy); @@ -266,10 +317,21 @@ ByteString GenerateListBoxAP(const CPDF_Dictionary* annot_dict, return ByteString(body_stream); } +// The colour a widget's beveled border paints its shaded edges in, the lower +// and the right: the background less a quarter, and light grey (white less a +// quarter) without one. Acrobat paints every field kind's so. +CFX_Color BeveledShade(const CFX_Color& background) { + return background.nColorType == CFX_Color::Type::kTransparent + ? CFX_Color::MakeGray(0.75f) + : background - 0.25f; +} + // A field's background and border, in isolated graphics state: what a text -// field draws under its text, and all a signature field's box is. A solid -// border is a stroked rectangle; the other styles draw as a combo box's and -// a list box's do. +// field draws under its text, all a signature field's box is, and the box of +// a check box, a push button and a radio button that shows no circle. A +// solid border is a stroked rectangle; the other styles draw as a combo +// box's and a list box's do: dashed, beveled, inset, or a line along the +// bottom. Acrobat draws each style so on every one of these kinds. void WriteFieldBox(fxcrt::ostringstream& app_stream, const AppearanceCharacteristics& mk, const BorderStyleInfo& bs, @@ -298,7 +360,8 @@ void WriteFieldBox(fxcrt::ostringstream& app_stream, WriteRect(app_stream, stroke_rect) << " re s\n"; } } else { - app_stream << GenerateBorderAP(bbox, bs, mk.border_color); + app_stream << GenerateBorderAP(bbox, bs, mk.border_color, + BeveledShade(mk.background_color)); } app_stream << "Q\n"; } @@ -362,7 +425,8 @@ void GenerateComboBoxFormAP(fxcrt::ostringstream& app_stream, } const ByteString border_stream = - GenerateBorderAP(bbox, border_info, dims.border_color); + GenerateBorderAP(bbox, border_info, dims.border_color, + BeveledShade(dims.background_color)); if (border_stream.GetLength() > 0) { app_stream << "q\n" << border_stream << "Q\n"; } @@ -393,7 +457,8 @@ void GenerateListBoxFormAP(fxcrt::ostringstream& app_stream, } const ByteString border_stream = - GenerateBorderAP(bbox, border_info, dims.border_color); + GenerateBorderAP(bbox, border_info, dims.border_color, + BeveledShade(dims.background_color)); if (border_stream.GetLength() > 0) { app_stream << "q\n" << border_stream << "Q\n"; } @@ -402,18 +467,29 @@ void GenerateListBoxFormAP(fxcrt::ostringstream& app_stream, body_rect.Deflate(border_info.width, border_info.width); const ByteString body = - GenerateListBoxAP(annot_dict, body_rect, da_info.text_color, - da_info.font_size, map, options); + GenerateListBoxAP(annot_dict, body_rect, border_info.width, + da_info.text_color, da_info.font_size, map, options); if (body.GetLength() > 0) { app_stream << "/Tx BMC\nq\n"; WriteRect(app_stream, body_rect) << " re\nW\nn\n" << body << "Q\nEMC\n"; } } +// The check mark's shape (PDFium's form filler's), in a unit square: the +// points its path writes (the curves' handles blended as the path blends +// them) reach from kCheckLeft to kCheckRight across and from kCheckBottom +// to kCheckTop up, the box GenerateCheckmarkPath() fills. +constexpr float kCheckLeft = 0.27448f; +constexpr float kCheckRight = 0.77105f; +constexpr float kCheckBottom = 0.28f; +constexpr float kCheckTop = 0.77761f; + +// The check mark's path, its points (CheckSymbolRect()'s box for a check) +// filling `bbox`. void GenerateCheckmarkPath(fxcrt::ostringstream& stream, const CFX_FloatRect& bbox) { - const float w = bbox.Width(); - const float h = bbox.Height(); + const float w = bbox.Width() / (kCheckRight - kCheckLeft); + const float h = bbox.Height() / (kCheckTop - kCheckBottom); using PointRow = std::array; std::array pts = {{ @@ -437,8 +513,8 @@ void GenerateCheckmarkPath(fxcrt::ostringstream& stream, for (auto& row : pts) { for (auto& pt : row) { - pt.x = pt.x * w + bbox.left; - pt.y = pt.y * h + bbox.bottom; + pt.x = (pt.x - kCheckLeft) * w + bbox.left; + pt.y = (pt.y - kCheckBottom) * h + bbox.bottom; } } @@ -460,32 +536,112 @@ void GenerateCheckmarkPath(fxcrt::ostringstream& stream, } } -void BuildCheckboxBoxStream(fxcrt::ostringstream& stream, - const AppearanceCharacteristics& mk, - const BorderStyleInfo& bs, - const CFX_FloatRect& bbox) { +// A path along a circle about `center`: `quarters` quarter turns +// anticlockwise from `from`, a unit vector naming where it starts (the +// rightmost point is (1, 0)). Each quarter is one Bezier curve. The path is +// not closed. +void WriteCircleArc(fxcrt::ostringstream& stream, + const CFX_PointF& center, + float radius, + CFX_PointF from, + int quarters) { + auto on_circle = [¢er, radius](const CFX_PointF& direction) { + return CFX_PointF(center.x + radius * direction.x, + center.y + radius * direction.y); + }; + const float handle = radius * FXSYS_BEZIER; + WritePoint(stream, on_circle(from)) << " m\n"; + for (int i = 0; i < quarters; ++i) { + // A quarter turn on: (x, y) turned anticlockwise is (-y, x). + const CFX_PointF to(-from.y, from.x); + const CFX_PointF start = on_circle(from); + const CFX_PointF end = on_circle(to); + WritePoint(stream, {start.x + handle * to.x, start.y + handle * to.y}) + << " "; + WritePoint(stream, {end.x + handle * from.x, end.y + handle * from.y}) + << " "; + WritePoint(stream, end) << " c\n"; + from = to; + } +} + +// A whole circle, from its rightmost point anticlockwise, closed. +void WriteCircle(fxcrt::ostringstream& stream, + const CFX_PointF& center, + float radius) { + WriteCircleArc(stream, center, radius, CFX_PointF(1, 0), 4); + stream << "h\n"; +} + +// The circle a radio button that shows a circle is drawn in: as wide as the +// box is high (or as high as it is wide), in the middle of the box. +struct RadioCircle { + CFX_PointF center; + float radius; +}; + +RadioCircle RadioCircleOf(const CFX_FloatRect& bbox) { + const CFX_FloatRect square = bbox.GetCenterSquare(); + return {CFX_PointF((square.left + square.right) / 2.0f, + (square.bottom + square.top) / 2.0f), + square.Width() / 2.0f}; +} + +// A radio button's background and border in its circle (RadioCircleOf()), +// in isolated graphics state, as Acrobat draws them: the background fills +// the circle, and the border is a circle line inside its edge, as wide as +// the border, dashed when the border is. A beveled or inset border is that +// line at half its width (BorderStyleInfo counts both halves) and, inside +// it, two half circles as wide, lit at the upper left and shaded at the +// lower right. A circle has no underline: Acrobat draws the whole circle for +// one, as for a solid border. +void WriteRadioCircleBox(fxcrt::ostringstream& stream, + const AppearanceCharacteristics& mk, + const BorderStyleInfo& bs, + const RadioCircle& circle) { const bool has_bg = mk.background_color.nColorType != CFX_Color::Type::kTransparent; const bool has_bc = mk.border_color.nColorType != CFX_Color::Type::kTransparent; - const float bw = bs.width; - const float half_bw = bw / 2.0f; - - CFX_FloatRect stroke_rect = bbox; - if (bw > 0) { - stroke_rect.Deflate(half_bw, half_bw); - } + const bool shaded = + bs.style == BorderStyle::kBeveled || bs.style == BorderStyle::kInset; + const float line_width = shaded ? bs.width / 2.0f : bs.width; + stream << "q\n"; if (has_bg) { stream << GenerateColorAP(mk.background_color, PaintOperation::kFill); - WriteRect(stream, stroke_rect) << " re f*\n"; - } - - if (has_bc && bw > 0) { - stream << GenerateColorAP(mk.border_color, PaintOperation::kStroke); - WriteFloat(stream, bw) << " w\n"; - WriteRect(stream, stroke_rect) << " re S\n"; + WriteCircle(stream, circle.center, circle.radius); + stream << "f\n"; + } + const float line_radius = circle.radius - line_width / 2.0f; + if (line_width > 0 && line_radius > 0 && (has_bc || shaded)) { + WriteFloat(stream, line_width) << " w\n"; + if (has_bc) { + stream << GenerateColorAP(mk.border_color, PaintOperation::kStroke); + if (bs.style == BorderStyle::kDash) { + stream << DashOperator(bs.dash_pattern); + } + WriteCircle(stream, circle.center, line_radius); + stream << "S\n"; + } + const float edge_radius = line_radius - line_width; + if (shaded && edge_radius > 0) { + const bool beveled = bs.style == BorderStyle::kBeveled; + constexpr float kDiagonal = 0.70710678f; // the cosine of 45 degrees + const CFX_PointF upper_right(kDiagonal, kDiagonal); + const CFX_PointF lower_left(-kDiagonal, -kDiagonal); + stream << GenerateColorAP(CFX_Color::MakeGray(beveled ? 1.0f : 0.5f), + PaintOperation::kStroke); + WriteCircleArc(stream, circle.center, edge_radius, upper_right, 2); + stream << "S\n" + << GenerateColorAP(beveled ? BeveledShade(mk.background_color) + : CFX_Color::MakeGray(0.75f), + PaintOperation::kStroke); + WriteCircleArc(stream, circle.center, edge_radius, lower_left, 2); + stream << "S\n"; + } } + stream << "Q\n"; } // How a push button lays out its caption and its icon: /MK /TP (ISO 32000-2 @@ -625,14 +781,16 @@ std::optional IconPlacement(const CFX_FloatRect& icon, } // The part of a push button its icon is fitted into, alone or with the -// caption beside it: the button less the border's width at each edge, or the -// whole button when /MK /IF /FB says the icon reaches the edges. +// caption beside it: the button less twice the border's width at each edge, +// as Acrobat leaves it, or the whole button when /MK /IF /FB says the icon +// reaches the edges. `border_width` is BorderStyleInfo's, which counts a +// beveled or inset border twice. CFX_FloatRect ButtonPlate(const CFX_FloatRect& bbox, float border_width, const CPDF_IconFit& fit) { CFX_FloatRect plate = bbox; if (!fit.GetFittingBounds()) { - plate.Deflate(border_width, border_width); + plate.Deflate(2.0f * border_width, 2.0f * border_width); } return plate; } @@ -667,55 +825,86 @@ void NameButtonIcon(CPDF_Dictionary* resources, // Where a push button that shows both draws its caption and its icon. struct ButtonParts { - CFX_FloatRect caption; - CFX_FloatRect icon; // without area when the caption takes the whole plate + CFX_FloatRect caption; // the box the caption is laid out in the middle of + CFX_FloatRect icon; // without area when the caption leaves it no room }; -// Shares `plate` between a caption and an icon by the rule of PDFium's form -// filler (GetPushButtonAppStream() in fpdfsdk/cpdfsdk_appstream.cpp), so a -// button looks the same whichever drew it. Below or above the icon, the -// caption takes a strip as high as its line; right or left of it, a strip -// as wide as its text; the icon takes the rest. A caption that needs more -// than the plate has takes all of it, and no icon is drawn. A caption whose -// size is fitted (a font size of 0) takes a third of the plate, and is -// fitted to that. Over the icon, both take the whole plate. `caption` is the -// room the caption takes at its font size, and is not read when `fitted`. +// Shares a push button between a caption and an icon as Acrobat 26 does, +// which these numbers were measured from. Call b the border's width +// (BorderStyleInfo's, which counts a beveled or inset border twice), and +// call the caption's extent its height below or above the icon and its width +// beside it: `extent`. +// +// The icon's part is the plate (ButtonPlate()) less the caption's strip, +// which reaches 3b + `extent` in from the button's edge on the caption's +// side. The caption is in the middle of the room between the icon's part +// and that edge, a room Acrobat measures from a different point on each +// side: from b above the bottom edge, from 2b below the top edge, from the +// right edge itself, and from 2b in from the left edge. With a border of 1, +// a caption is 2 from the bottom edge and 1 from the icon's part below it, +// 2.5 and 0.5 above it, 1.5 and 1.5 right of it, 2.5 and 0.5 left of it. +// Without a border, both touch the edge and each other. Across, the caption +// is in the middle of the plate. Over the icon, both take the plate. +// +// When the strip leaves the icon no room, the icon is left out, and the +// caption is in the middle of the room from the same point to the plate's +// far edge. ButtonParts SplitButton(ButtonLayout layout, + const CFX_FloatRect& bbox, const CFX_FloatRect& plate, - const CFX_SizeF& caption, - bool fitted) { + float border_width, + float extent) { ButtonParts parts = {plate, plate}; if (layout == ButtonLayout::kCaptionOverIcon) { return parts; } - const bool stacked = layout == ButtonLayout::kCaptionBelowIcon || - layout == ButtonLayout::kCaptionAboveIcon; - const float room = stacked ? plate.Height() : plate.Width(); - const float strip = - fitted ? room / 3.0f : (stacked ? caption.height : caption.width); - if (strip > room) { - parts.icon = CFX_FloatRect(); - return parts; - } + const float b = border_width; + const float strip = 3.0f * b + extent; + CFX_FloatRect& room = parts.caption; + CFX_FloatRect& icon = parts.icon; + bool icon_has_room = true; switch (layout) { case ButtonLayout::kCaptionBelowIcon: - parts.caption.top = plate.bottom + strip; - parts.icon.bottom = parts.caption.top; + icon.bottom = bbox.bottom + strip; + icon_has_room = icon.bottom < plate.top; + room.bottom = bbox.bottom + b; + room.top = icon_has_room ? icon.bottom : plate.top; break; case ButtonLayout::kCaptionAboveIcon: - parts.caption.bottom = plate.top - strip; - parts.icon.top = parts.caption.bottom; + icon.top = bbox.top - strip; + icon_has_room = icon.top > plate.bottom; + room.top = bbox.top - 2.0f * b; + room.bottom = icon_has_room ? icon.top : plate.bottom; break; case ButtonLayout::kCaptionRightOfIcon: - parts.caption.left = plate.right - strip; - parts.icon.right = parts.caption.left; + icon.right = bbox.right - strip; + icon_has_room = icon.right > plate.left; + room.right = bbox.right; + room.left = icon_has_room ? icon.right : plate.left; break; case ButtonLayout::kCaptionLeftOfIcon: - parts.caption.right = plate.left + strip; - parts.icon.left = parts.caption.right; + icon.left = bbox.left + strip; + icon_has_room = icon.left < plate.right; + room.left = bbox.left + 2.0f * b; + room.right = icon_has_room ? icon.left : plate.right; break; default: - break; + return parts; + } + if (!icon_has_room) { + icon = CFX_FloatRect(); + } + // The caption's box: as deep as its extent, in the middle of its room. + const bool stacked = layout == ButtonLayout::kCaptionBelowIcon || + layout == ButtonLayout::kCaptionAboveIcon; + if (stacked) { + const float middle = (room.bottom + room.top) / 2.0f; + room.bottom = middle - extent / 2.0f; + room.top = middle + extent / 2.0f; + } else { + const float middle = (room.left + room.right) / 2.0f; + room.left = middle - extent / 2.0f; + room.right = middle + extent / 2.0f; } return parts; } @@ -732,14 +921,15 @@ CPDF_RichTextLayout::Field ButtonCaptionField(const WideString& caption, return field; } -// The room a caption takes at `font_size`: its line's width and height. +// The room a caption takes at `font_size`: its line's width and height, +// measured in `box`. CFX_SizeF ButtonCaptionSize(CPDF_AnnotFontMap& map, const CPDF_RichTextLayout::Options& options, const WideString& caption, float font_size, - const CFX_FloatRect& plate) { + const CFX_FloatRect& box) { const CPDF_RichTextLayout::Result laid = ArrangeFieldText( - map, options, ButtonCaptionField(caption, font_size), plate); + map, options, ButtonCaptionField(caption, font_size), box); float width = 0; for (const CPDF_RichTextLayout::Line& line : laid.lines) { width = std::max(width, line.width); @@ -771,15 +961,19 @@ void WriteButtonCaption(fxcrt::ostringstream& app_stream, // A push button that draws a caption (GenerateIconButtonAP() draws the ones // that draw none): background and border as a text field draws them, and the // caption (/MK /CA) on one line, centred both ways, in the /DA font and -// colour. +// colour, clipped to the button inside its border. // // The caption alone (/MK /TP 0, or any layout without an icon) takes the // whole button inside its border. In the layouts that show a caption and an -// icon (/MK /TP 2 to 6), a button that has an icon (/MK /I) draws both, each -// in the part SplitButton() gives it: the icon first, fitted into its part -// as /MK /IF says and clipped to it, then the caption in the middle of its -// part, so over the icon the caption is on top. When the caption leaves the -// icon no room, the caption is drawn alone. +// icon (/MK /TP 2 to 6), a button that has an icon (/MK /I) draws both, as +// SplitButton() shares the button: the icon first, fitted into its part as +// /MK /IF says and clipped to it, then the caption in the middle of its box, +// so over the icon the caption is on top. A caption whose size is fitted (a +// font size of 0) takes a third of the plate (ButtonPlate()), of its height +// below or above the icon and of its width beside it, and is fitted to that. +// When the caption leaves the icon no room, the icon is left out and the +// caption is drawn where SplitButton() puts it alone. An icon that has no +// area of its own draws the caption alone. // // Returns the object number of the icon it drew, which the appearance's // resources must name /FRM (NameButtonIcon()), or 0. @@ -795,13 +989,13 @@ uint32_t GeneratePushButtonFormAP(fxcrt::ostringstream& app_stream, const BorderStyleInfo bs = GetAnnotBorderStyleInfo(annot_dict); const float bw = bs.width; - app_stream << "q\n"; - BuildCheckboxBoxStream(app_stream, mk, bs, bbox); - app_stream << "Q\n"; + WriteFieldBox(app_stream, mk, bs, bbox); if (mk.caption.IsEmpty()) { return 0; } + CFX_FloatRect inside_border = bbox; + inside_border.Deflate(bw, bw); const ButtonLayout layout = ButtonLayoutOf(annot_dict); RetainPtr icon = layout == ButtonLayout::kCaptionAlone ? nullptr @@ -809,15 +1003,24 @@ uint32_t GeneratePushButtonFormAP(fxcrt::ostringstream& app_stream, if (icon) { const CPDF_IconFit fit(mk_dict->GetDictFor("IF")); const CFX_FloatRect plate = ButtonPlate(bbox, bw, fit); - const bool fitted = FXSYS_IsFloatZero(da_info.font_size); - const ButtonParts parts = - SplitButton(layout, plate, - fitted ? CFX_SizeF() - : ButtonCaptionSize(map, options, mk.caption, - da_info.font_size, plate), - fitted); + const bool stacked = layout == ButtonLayout::kCaptionBelowIcon || + layout == ButtonLayout::kCaptionAboveIcon; + float extent = 0; + if (FXSYS_IsFloatZero(da_info.font_size)) { + extent = (stacked ? plate.Height() : plate.Width()) / 3.0f; + } else { + const CFX_SizeF size = + ButtonCaptionSize(map, options, mk.caption, da_info.font_size, bbox); + extent = stacked ? size.height : size.width; + } + const ButtonParts parts = SplitButton(layout, bbox, plate, bw, extent); + if (parts.icon.IsEmpty()) { + WriteButtonCaption(app_stream, mk.caption, parts.caption, inside_border, + da_info, map, options); + return 0; + } if (WriteButtonIcon(app_stream, icon.Get(), parts.icon, fit)) { - WriteButtonCaption(app_stream, mk.caption, parts.caption, parts.caption, + WriteButtonCaption(app_stream, mk.caption, parts.caption, inside_border, da_info, map, options); return icon->GetObjNum(); } @@ -825,10 +1028,8 @@ uint32_t GeneratePushButtonFormAP(fxcrt::ostringstream& app_stream, CFX_FloatRect body_rect = bbox; body_rect.Deflate(2.0f * bw, bw); - CFX_FloatRect clip_rect = bbox; - clip_rect.Deflate(bw, bw); - WriteButtonCaption(app_stream, mk.caption, body_rect, clip_rect, da_info, map, - options); + WriteButtonCaption(app_stream, mk.caption, body_rect, inside_border, da_info, + map, options); return 0; } @@ -876,13 +1077,30 @@ CFX_Color CheckSymbolColor(CPDF_Document* doc, // Where the symbol is drawn: the middle square of `body` (the widget inside // its border), shrunk for the filled shapes as PDFium's form filler shrinks -// them (CPDFSDK_AppStream), so a symbol looks the same whichever drew it. +// them (CPDFSDK_AppStream). A check is as large as Acrobat 26 draws one: +// ZapfDingbats' check mark at the size whose font box (963 thousandths +// high) fills the square less the border's width (`border_width`, counted +// twice for beveled and inset) at each side. The mark is 719 thousandths of +// that size high; the box returned is where the check's points reach, that +// high, as wide as its shape is, in the middle. CFX_FloatRect CheckSymbolRect(const CFX_FloatRect& body, + float border_width, CheckStyle style, bool radio) { CFX_FloatRect rect = body.GetCenterSquare(); switch (style) { - case CheckStyle::kCheck: + case CheckStyle::kCheck: { + constexpr float kFontBoxHeight = 0.963f; + constexpr float kMarkHeight = 0.719f; + const float room = std::max(rect.Width() - 2.0f * border_width, 0.0f); + const float height = room / kFontBoxHeight * kMarkHeight; + const float width = + height * (kCheckRight - kCheckLeft) / (kCheckTop - kCheckBottom); + const float middle_x = (rect.left + rect.right) / 2.0f; + const float middle_y = (rect.bottom + rect.top) / 2.0f; + return CFX_FloatRect(middle_x - width / 2.0f, middle_y - height / 2.0f, + middle_x + width / 2.0f, middle_y + height / 2.0f); + } case CheckStyle::kCross: break; case CheckStyle::kCircle: @@ -1034,9 +1252,7 @@ void GenerateIconButtonAP(APGenerationTarget* target, GetAnnotationDimensionsAndColor(annot_dict); fxcrt::ostringstream content; - content << "q\n"; - BuildCheckboxBoxStream(content, mk, bs, dims.bbox); - content << "Q\n"; + WriteFieldBox(content, mk, bs, dims.bbox); RetainPtr resources; if (RetainPtr icon = ButtonIconOf(mk_dict.Get())) { @@ -1245,70 +1461,6 @@ bool GenerateFormAPToTarget(APGenerationTarget* target, return true; } -void BuildRadioCircleStream(fxcrt::ostringstream& stream, - const AppearanceCharacteristics& mk, - const BorderStyleInfo& bs, - const CFX_FloatRect& bbox) { - const bool has_bg = - mk.background_color.nColorType != CFX_Color::Type::kTransparent; - const bool has_bc = - mk.border_color.nColorType != CFX_Color::Type::kTransparent; - const float bw = bs.width; - const float half_bw = bw / 2.0f; - - const float cx = (bbox.left + bbox.right) / 2.0f; - const float cy = (bbox.bottom + bbox.top) / 2.0f; - const float rx = (bbox.right - bbox.left) / 2.0f; - const float ry = (bbox.top - bbox.bottom) / 2.0f; - - constexpr float kKappa = 0.5523f; - - auto WriteEllipse = [&](fxcrt::ostringstream& s, float erx, float ery) { - const float dx = kKappa * erx; - const float dy = kKappa * ery; - WriteFloat(s, cx) << " "; - WriteFloat(s, cy + ery) << " m\n"; - WriteFloat(s, cx + dx) << " "; - WriteFloat(s, cy + ery) << " "; - WriteFloat(s, cx + erx) << " "; - WriteFloat(s, cy + dy) << " "; - WriteFloat(s, cx + erx) << " "; - WriteFloat(s, cy) << " c\n"; - WriteFloat(s, cx + erx) << " "; - WriteFloat(s, cy - dy) << " "; - WriteFloat(s, cx + dx) << " "; - WriteFloat(s, cy - ery) << " "; - WriteFloat(s, cx) << " "; - WriteFloat(s, cy - ery) << " c\n"; - WriteFloat(s, cx - dx) << " "; - WriteFloat(s, cy - ery) << " "; - WriteFloat(s, cx - erx) << " "; - WriteFloat(s, cy - dy) << " "; - WriteFloat(s, cx - erx) << " "; - WriteFloat(s, cy) << " c\n"; - WriteFloat(s, cx - erx) << " "; - WriteFloat(s, cy + dy) << " "; - WriteFloat(s, cx - dx) << " "; - WriteFloat(s, cy + ery) << " "; - WriteFloat(s, cx) << " "; - WriteFloat(s, cy + ery) << " c\n"; - s << "h\n"; - }; - - if (has_bg) { - stream << GenerateColorAP(mk.background_color, PaintOperation::kFill); - WriteEllipse(stream, rx - half_bw, ry - half_bw); - stream << "f*\n"; - } - - if (has_bc && bw > 0) { - stream << GenerateColorAP(mk.border_color, PaintOperation::kStroke); - WriteFloat(stream, bw) << " w\n"; - WriteEllipse(stream, rx - half_bw, ry - half_bw); - stream << "S\n"; - } -} - } // namespace namespace appearance_generator { @@ -1433,15 +1585,15 @@ void CPDF_AppearanceGenerator::GenerateCheckboxFormAP( const CheckStyle style = CheckStyleFromCaption(mk.caption).value_or(CheckStyle::kCheck); - // Off state: box only (background fill + border stroke). + // Off state: the box alone, its background and border (WriteFieldBox()). fxcrt::ostringstream off_content; - BuildCheckboxBoxStream(off_content, mk, bs, dims.bbox); + WriteFieldBox(off_content, mk, bs, dims.bbox); // On state: the same box and the symbol /MK /CA names, in the /DA colour. fxcrt::ostringstream yes_content; - BuildCheckboxBoxStream(yes_content, mk, bs, dims.bbox); + WriteFieldBox(yes_content, mk, bs, dims.bbox); WriteCheckSymbol(yes_content, style, - CheckSymbolRect(body_rect, style, /*radio=*/false), + CheckSymbolRect(body_rect, bs.width, style, /*radio=*/false), CheckSymbolColor(doc, annot_dict)); const uint32_t off_obj_num = @@ -1485,47 +1637,6 @@ void CPDF_AppearanceGenerator::GenerateRadioButtonFormAP( const AnnotationDimensionsAndColor dims = GetAnnotationDimensionsAndColor(annot_dict); - const float cx = (dims.bbox.left + dims.bbox.right) / 2.0f; - const float cy = (dims.bbox.bottom + dims.bbox.top) / 2.0f; - const float rx = (dims.bbox.right - dims.bbox.left) / 2.0f; - const float ry = (dims.bbox.top - dims.bbox.bottom) / 2.0f; - const float inner_rx = (rx - bs.width) * 0.5f; - const float inner_ry = (ry - bs.width) * 0.5f; - - constexpr float kKappa = 0.5523f; - - auto WriteEllipse = [&](fxcrt::ostringstream& s, float erx, float ery) { - const float dx = kKappa * erx; - const float dy = kKappa * ery; - WriteFloat(s, cx) << " "; - WriteFloat(s, cy + ery) << " m\n"; - WriteFloat(s, cx + dx) << " "; - WriteFloat(s, cy + ery) << " "; - WriteFloat(s, cx + erx) << " "; - WriteFloat(s, cy + dy) << " "; - WriteFloat(s, cx + erx) << " "; - WriteFloat(s, cy) << " c\n"; - WriteFloat(s, cx + erx) << " "; - WriteFloat(s, cy - dy) << " "; - WriteFloat(s, cx + dx) << " "; - WriteFloat(s, cy - ery) << " "; - WriteFloat(s, cx) << " "; - WriteFloat(s, cy - ery) << " c\n"; - WriteFloat(s, cx - dx) << " "; - WriteFloat(s, cy - ery) << " "; - WriteFloat(s, cx - erx) << " "; - WriteFloat(s, cy - dy) << " "; - WriteFloat(s, cx - erx) << " "; - WriteFloat(s, cy) << " c\n"; - WriteFloat(s, cx - erx) << " "; - WriteFloat(s, cy + dy) << " "; - WriteFloat(s, cx - dx) << " "; - WriteFloat(s, cy + ery) << " "; - WriteFloat(s, cx) << " "; - WriteFloat(s, cy + ery) << " c\n"; - s << "h\n"; - }; - const CheckStyle style = CheckStyleFromCaption(mk.caption).value_or(CheckStyle::kCircle); const CFX_Color symbol_color = CheckSymbolColor(doc, annot_dict); @@ -1533,23 +1644,30 @@ void CPDF_AppearanceGenerator::GenerateRadioButtonFormAP( fxcrt::ostringstream off_content; fxcrt::ostringstream yes_content; if (style == CheckStyle::kCircle) { - // Off state: circle only (background fill + border stroke). - BuildRadioCircleStream(off_content, mk, bs, dims.bbox); - - // On state: the same circle and a filled dot, in the /DA colour. - BuildRadioCircleStream(yes_content, mk, bs, dims.bbox); - yes_content << "q\n" - << GenerateColorAP(symbol_color, PaintOperation::kFill); - WriteEllipse(yes_content, inner_rx, inner_ry); - yes_content << "f*\nQ\n"; + // Off state: the circle alone, its background and border + // (WriteRadioCircleBox()). + const RadioCircle circle = RadioCircleOf(dims.bbox); + WriteRadioCircleBox(off_content, mk, bs, circle); + + // On state: the same circle and a dot in its middle, in the /DA colour, + // half as wide as the circle inside its border, as Acrobat draws it. + WriteRadioCircleBox(yes_content, mk, bs, circle); + const float dot_radius = (circle.radius - bs.width) / 2.0f; + if (dot_radius > 0) { + yes_content << "q\n" + << GenerateColorAP(symbol_color, PaintOperation::kFill); + WriteCircle(yes_content, circle.center, dot_radius); + yes_content << "f\nQ\n"; + } } else { // Any other symbol sits in a box, as PDFium's form filler draws it. CFX_FloatRect body_rect = dims.bbox; body_rect.Deflate(bs.width, bs.width); - BuildCheckboxBoxStream(off_content, mk, bs, dims.bbox); - BuildCheckboxBoxStream(yes_content, mk, bs, dims.bbox); + WriteFieldBox(off_content, mk, bs, dims.bbox); + WriteFieldBox(yes_content, mk, bs, dims.bbox); WriteCheckSymbol(yes_content, style, - CheckSymbolRect(body_rect, style, /*radio=*/true), + CheckSymbolRect(body_rect, bs.width, style, + /*radio=*/true), symbol_color); } diff --git a/core/fpdfdoc/cpdf_appearancegenerator_freetext.cpp b/core/fpdfdoc/cpdf_appearancegenerator_freetext.cpp index 0d14f13ab6..68bb6f145c 100644 --- a/core/fpdfdoc/cpdf_appearancegenerator_freetext.cpp +++ b/core/fpdfdoc/cpdf_appearancegenerator_freetext.cpp @@ -434,8 +434,10 @@ PrepareRichFreeTextAPInternal(CPDF_Document* doc, stream << "q\n" << GenerateColorAP(color, PaintOperation::kFill); WriteRect(stream, background_rect) << " re f\nQ\n"; } - const ByteString border_stream = - GenerateBorderAP(rect, border_style_info, in.da_color); + // A beveled border's shaded edges are mid grey here, whatever the box's + // colour. + const ByteString border_stream = GenerateBorderAP( + rect, border_style_info, in.da_color, CFX_Color::MakeGray(0.5f)); if (border_stream.GetLength() > 0) { stream << "q\n" << border_stream << "Q\n"; } diff --git a/core/fpdfdoc/cpdf_appearancegenerator_internal.h b/core/fpdfdoc/cpdf_appearancegenerator_internal.h index f4d127b725..457e502ba6 100644 --- a/core/fpdfdoc/cpdf_appearancegenerator_internal.h +++ b/core/fpdfdoc/cpdf_appearancegenerator_internal.h @@ -155,9 +155,17 @@ AnnotationDimensionsAndColor GetAnnotationDimensionsAndColor( const CPDF_Dictionary* annot_dict); ShapeRotationInfo GetShapeRotationInfo(const CPDF_Dictionary* annot_dict); ByteString GenerateColorAP(const CFX_Color& color, PaintOperation operation); +// The dash operator for a pattern (BorderStyleInfo::dash_pattern); empty for +// none. +ByteString DashOperator(const std::vector& values); +// A box's border inside `rect`, as `border_style_info` says: a solid or +// dashed line, a beveled or inset line with its lit and shaded edges inside +// it, or a line along the bottom. `beveled_shade` paints a beveled border's +// shaded edges, the lower and the right. ByteString GenerateBorderAP(const CFX_FloatRect& rect, const BorderStyleInfo& border_style_info, - const CFX_Color& border_color); + const CFX_Color& border_color, + const CFX_Color& beveled_shade); ByteString GetColorStringWithDefault(const CPDF_Array* color_array, const CFX_Color& default_color, PaintOperation operation); diff --git a/core/fpdfdoc/cpdf_appearancegenerator_unittest.cpp b/core/fpdfdoc/cpdf_appearancegenerator_unittest.cpp index 92ada5cc3d..c9ade41fc9 100644 --- a/core/fpdfdoc/cpdf_appearancegenerator_unittest.cpp +++ b/core/fpdfdoc/cpdf_appearancegenerator_unittest.cpp @@ -3,7 +3,9 @@ #include "core/fpdfdoc/cpdf_appearancegenerator.h" +#include #include +#include #include #include @@ -20,6 +22,8 @@ #include "core/fpdfapi/parser/cpdf_stream.h" #include "core/fpdfapi/parser/cpdf_string.h" #include "core/fpdfapi/parser/cpdf_test_document.h" +#include "core/fxcrt/fx_coordinates.h" +#include "core/fxcrt/fx_string.h" #include "core/fxge/cfx_color.h" #include "testing/gtest/include/gtest/gtest.h" @@ -394,30 +398,27 @@ enum class BorderedKind { struct BorderedKindCase { const char* name; BorderedKind kind; - // False for a check box, a radio button and a push button (with a caption - // or an icon), which draw one solid box for every border style. - bool draws_dashes; }; constexpr BorderedKindCase kBorderedKinds[] = { - {"square", BorderedKind::kSquare, true}, - {"circle", BorderedKind::kCircle, true}, - {"line", BorderedKind::kLine, true}, - {"polygon", BorderedKind::kPolygon, true}, - {"polyline", BorderedKind::kPolyLine, true}, - {"ink", BorderedKind::kInk, true}, - {"free text", BorderedKind::kFreeText, true}, - {"free text callout", BorderedKind::kCallout, true}, - {"link", BorderedKind::kLink, true}, - {"redaction", BorderedKind::kRedact, true}, - {"text field", BorderedKind::kTextField, true}, - {"combo box", BorderedKind::kComboBox, true}, - {"list box", BorderedKind::kListBox, true}, - {"check box", BorderedKind::kCheckBox, false}, - {"radio button", BorderedKind::kRadioButton, false}, - {"push button", BorderedKind::kPushButton, false}, - {"push button with an icon", BorderedKind::kIconButton, false}, - {"signature", BorderedKind::kSignature, true}, + {"square", BorderedKind::kSquare}, + {"circle", BorderedKind::kCircle}, + {"line", BorderedKind::kLine}, + {"polygon", BorderedKind::kPolygon}, + {"polyline", BorderedKind::kPolyLine}, + {"ink", BorderedKind::kInk}, + {"free text", BorderedKind::kFreeText}, + {"free text callout", BorderedKind::kCallout}, + {"link", BorderedKind::kLink}, + {"redaction", BorderedKind::kRedact}, + {"text field", BorderedKind::kTextField}, + {"combo box", BorderedKind::kComboBox}, + {"list box", BorderedKind::kListBox}, + {"check box", BorderedKind::kCheckBox}, + {"radio button", BorderedKind::kRadioButton}, + {"push button", BorderedKind::kPushButton}, + {"push button with an icon", BorderedKind::kIconButton}, + {"signature", BorderedKind::kSignature}, }; // An annotation of |kind|, 120 by 60, with what the kind needs to be drawn @@ -573,19 +574,14 @@ ByteString NormalAppearanceContent(const CPDF_Dictionary* annot_dict) { return content; } -// The appearance the generator writes for a new annotation of |kind| whose -// border |write_border| has written, each in a document of its own. -ByteString DrawBorderedKind( - BorderedKind kind, - const std::function& write_border) { - CPDF_TestDocument doc; - AddAcroFormWithHelvetica(&doc); - RetainPtr annot_dict = MakeBorderedDict(&doc, kind); - write_border(annot_dict.Get()); - +// Has the generator write the appearance of |annot_dict|, an annotation of +// |kind| in |doc|. +void GenerateBorderedKind(CPDF_Document* doc, + BorderedKind kind, + CPDF_Dictionary* annot_dict) { auto draw_annot = [&](CPDF_Annot::Subtype subtype) { - EXPECT_TRUE(CPDF_AppearanceGenerator::GenerateAnnotAP( - &doc, annot_dict.Get(), subtype)); + EXPECT_TRUE( + CPDF_AppearanceGenerator::GenerateAnnotAP(doc, annot_dict, subtype)); }; switch (kind) { case BorderedKind::kSquare: @@ -618,35 +614,140 @@ ByteString DrawBorderedKind( break; case BorderedKind::kTextField: CPDF_AppearanceGenerator::GenerateFormAP( - &doc, annot_dict.Get(), CPDF_AppearanceGenerator::kTextField); + doc, annot_dict, CPDF_AppearanceGenerator::kTextField); break; case BorderedKind::kComboBox: CPDF_AppearanceGenerator::GenerateFormAP( - &doc, annot_dict.Get(), CPDF_AppearanceGenerator::kComboBox); + doc, annot_dict, CPDF_AppearanceGenerator::kComboBox); break; case BorderedKind::kListBox: CPDF_AppearanceGenerator::GenerateFormAP( - &doc, annot_dict.Get(), CPDF_AppearanceGenerator::kListBox); + doc, annot_dict, CPDF_AppearanceGenerator::kListBox); break; case BorderedKind::kCheckBox: - CPDF_AppearanceGenerator::GenerateCheckboxFormAP(&doc, annot_dict.Get()); + CPDF_AppearanceGenerator::GenerateCheckboxFormAP(doc, annot_dict); break; case BorderedKind::kRadioButton: - CPDF_AppearanceGenerator::GenerateRadioButtonFormAP(&doc, - annot_dict.Get()); + CPDF_AppearanceGenerator::GenerateRadioButtonFormAP(doc, annot_dict); break; case BorderedKind::kPushButton: case BorderedKind::kIconButton: CPDF_AppearanceGenerator::GenerateFormAP( - &doc, annot_dict.Get(), CPDF_AppearanceGenerator::kPushButton); + doc, annot_dict, CPDF_AppearanceGenerator::kPushButton); break; case BorderedKind::kSignature: - CPDF_AppearanceGenerator::GenerateBoxFormAP(&doc, annot_dict.Get()); + CPDF_AppearanceGenerator::GenerateBoxFormAP(doc, annot_dict); break; } +} + +// The appearance the generator writes for a new annotation of |kind| whose +// border |write_border| has written, each in a document of its own. +ByteString DrawBorderedKind( + BorderedKind kind, + const std::function& write_border) { + CPDF_TestDocument doc; + AddAcroFormWithHelvetica(&doc); + RetainPtr annot_dict = MakeBorderedDict(&doc, kind); + write_border(annot_dict.Get()); + GenerateBorderedKind(&doc, kind, annot_dict.Get()); return NormalAppearanceContent(annot_dict.Get()); } +// What a widget of |kind| (MakeBorderedDict(): 120 by 60, a green border on +// a light yellow background) draws with a border 1 wide in |style|, the +// name /BS /S takes, in each of its appearance states: a single stream is +// the state "". |adjust| changes the widget first. +std::map DrawWidgetInStyle( + BorderedKind kind, + const char* style, + const std::function& adjust = nullptr) { + CPDF_TestDocument doc; + AddAcroFormWithHelvetica(&doc); + RetainPtr annot_dict = MakeBorderedDict(&doc, kind); + auto border_style = annot_dict->SetNewFor("BS"); + border_style->SetNewFor("W", 1); + border_style->SetNewFor("S", style); + if (adjust) { + adjust(annot_dict.Get()); + } + GenerateBorderedKind(&doc, kind, annot_dict.Get()); + + std::map states; + RetainPtr ap_dict = + annot_dict->GetDictFor(pdfium::annotation::kAP); + if (!ap_dict) { + return states; + } + if (RetainPtr stream = ap_dict->GetStreamFor("N")) { + states[""] = WrittenContent(std::move(stream)); + return states; + } + RetainPtr normal = ap_dict->GetDictFor("N"); + for (const ByteString& state : + normal ? normal->GetKeys() : std::vector()) { + states[state] = WrittenContent(normal->GetStreamFor(state.AsStringView())); + } + return states; +} + +// The first block of |content| saved and restored as one: from its first +// "q" line to the "Q" line that closes it. +ByteString FirstBlock(const ByteString& content) { + const std::optional start = content.Find("q\n"); + if (!start.has_value()) { + return ByteString(); + } + int depth = 0; + size_t at = start.value(); + while (at < content.GetLength()) { + const std::optional end = content.Find("\n", at); + const size_t line_end = end.value_or(content.GetLength()); + const ByteString line = content.Substr(at, line_end - at); + if (line == "q") { + ++depth; + } else if (line == "Q" && --depth == 0) { + return content.Substr(start.value(), line_end + 1 - start.value()); + } + at = line_end + 1; + } + return ByteString(); +} + +// Every point the paths of |content| pass through: the last two numbers +// before each m, l and c (a curve's handles may lie outside its path). +std::vector PathPoints(const ByteString& content) { + std::vector points; + std::vector numbers; + size_t at = 0; + while (at < content.GetLength()) { + while (at < content.GetLength() && + (content[at] == ' ' || content[at] == '\n')) { + ++at; + } + size_t end = at; + while (end < content.GetLength() && content[end] != ' ' && + content[end] != '\n') { + ++end; + } + const ByteString token = content.Substr(at, end - at); + at = end; + if (token.IsEmpty()) { + continue; + } + if ((token == "m" || token == "l" || token == "c") && numbers.size() >= 2) { + points.emplace_back(numbers[numbers.size() - 2], numbers.back()); + } + if (std::isdigit(static_cast(token[0])) || token[0] == '.' || + token[0] == '-') { + numbers.push_back(StringToFloat(token.AsStringView())); + } else { + numbers.clear(); + } + } + return points; +} + } // namespace // The one border rule (ISO 32000-1 12.5.2), for every kind the generator @@ -679,10 +780,10 @@ TEST_F(CPDFGenerateAPTest, BorderArrayDrawsAsBorderStyleForEveryKind) { EXPECT_NE(with_border_style(1), wide); EXPECT_EQ(with_border_array(5), wide); - // A dash. + // A dash, which every kind draws. const ByteString dashed = with_border_style(5, pattern); - EXPECT_EQ(kind_case.draws_dashes, dashed.Contains("[4 2 ] 0 d\n")); - EXPECT_EQ(kind_case.draws_dashes, dashed != wide); + EXPECT_TRUE(dashed.Contains("[4 2 ] 0 d\n")); + EXPECT_NE(dashed, wide); EXPECT_EQ(with_border_array(5, pattern), dashed); // No border. @@ -711,6 +812,171 @@ TEST_F(CPDFGenerateAPTest, BorderArrayDrawsAsBorderStyleForEveryKind) { } } +// Every widget kind drawn in a box draws every border style, as Acrobat 26 +// does on each of them: a text field, a signature field, a check box, a +// push button (with a caption, and with an icon alone), and a radio button +// that shows a symbol other than a circle draw the same box, background and +// border, which Acrobat draws as on a text field. The numbers are Acrobat's +// for this box (its drawings of a 90 by 40 field with a border of 1, saved +// from Acrobat, follow the same rule): the background fills the whole box; +// a solid or dashed line is drawn half its width in; a beveled or inset +// border is the line and, inside it, a lit edge at the upper left and a +// shaded one at the lower right; an underline is a line along the bottom. A +// beveled border's shade is the background less a quarter. +TEST_F(CPDFGenerateAPTest, WidgetBoxesDrawEveryBorderStyle) { + const struct { + const char* style; + const char* border; + } kStyles[] = { + {"S", "0 1 0 RG\n1 w\n.5 .5 119 59 re s\n"}, + {"D", + "0 1 0 RG\n1 w\n[3 ] 0 d\n.5 .5 m\n.5 59.5 l\n119.5 59.5 l\n" + "119.5 .5 l\n.5 .5 l S\n"}, + {"B", + "1 g\n1 1 m\n1 59 l\n119 59 l\n118 58 l\n2 58 l\n2 2 l f\n" + ".75 .75 .55 rg\n119 59 m\n119 1 l\n1 1 l\n2 2 l\n118 2 l\n" + "118 58 l f\n0 1 0 rg\n0 0 120 60 re\n1 1 118 58 re f*\n"}, + {"I", + ".5 g\n1 1 m\n1 59 l\n119 59 l\n118 58 l\n2 58 l\n2 2 l f\n" + ".75 g\n119 59 m\n119 1 l\n1 1 l\n2 2 l\n118 2 l\n118 58 l f\n" + "0 1 0 rg\n0 0 120 60 re\n1 1 118 58 re f*\n"}, + {"U", "0 1 0 RG\n1 w\n0 .5 m\n120 .5 l S\n"}, + }; + const struct { + const char* name; + BorderedKind kind; + const char* state; // the state whose box is read + const char* symbol = nullptr; // a radio button's /MK /CA + } kKinds[] = { + {"text field", BorderedKind::kTextField, ""}, + {"signature", BorderedKind::kSignature, ""}, + {"check box", BorderedKind::kCheckBox, "Off"}, + {"check box, checked", BorderedKind::kCheckBox, "Yes"}, + {"push button", BorderedKind::kPushButton, ""}, + {"push button with an icon", BorderedKind::kIconButton, ""}, + {"radio button with a check", BorderedKind::kRadioButton, "Off", "4"}, + }; + for (const auto& style : kStyles) { + SCOPED_TRACE(style.style); + const ByteString box = + ByteString("q\n1 1 .8 rg\n0 0 120 60 re f*\n") + style.border + "Q\n"; + for (const auto& kind : kKinds) { + SCOPED_TRACE(kind.name); + std::map states = DrawWidgetInStyle( + kind.kind, style.style, [&kind](CPDF_Dictionary* annot_dict) { + if (kind.symbol) { + annot_dict->GetMutableDictFor("MK")->SetNewFor( + "CA", kind.symbol); + } + }); + ASSERT_EQ(1u, states.count(kind.state)); + EXPECT_EQ(box, FirstBlock(states[kind.state])); + } + } +} + +// A combo box and a list box draw a beveled border's shaded edges in the +// background less a quarter too, and light grey without a background, as +// Acrobat draws every field kind's. +TEST_F(CPDFGenerateAPTest, ChoiceFieldsShadeABeveledBorderByTheirBackground) { + for (BorderedKind kind : {BorderedKind::kComboBox, BorderedKind::kListBox}) { + SCOPED_TRACE(kind == BorderedKind::kComboBox ? "combo box" : "list box"); + const ByteString drawn = DrawWidgetInStyle(kind, "B")[""]; + EXPECT_TRUE(drawn.Contains("1 g\n1 1 m\n")); + EXPECT_TRUE(drawn.Contains(".75 .75 .55 rg\n119 59 m\n")); + const ByteString bare = + DrawWidgetInStyle(kind, "B", [](CPDF_Dictionary* annot_dict) { + annot_dict->GetMutableDictFor("MK")->RemoveFor("BG"); + })[""]; + EXPECT_TRUE(bare.Contains(".75 g\n119 59 m\n")); + } + // And a text field without a background. + const ByteString bare = DrawWidgetInStyle( + BorderedKind::kTextField, "B", [](CPDF_Dictionary* annot_dict) { + annot_dict->GetMutableDictFor("MK")->RemoveFor("BG"); + })[""]; + EXPECT_TRUE(bare.Contains(".75 g\n119 59 m\n")); +} + +// A radio button that shows a circle draws it as Acrobat 26 does: as wide as +// the box is high, in the middle of the box (120 by 60: a circle of radius +// 30 about (60, 30)). The background fills it; the border is a circle line +// half its width in, dashed when the border is; a beveled or inset border is +// that line at half the doubled width and two half circles inside it, lit at +// the upper left and shaded at the lower right; an underline draws the whole +// circle, as a solid border does. The dot is half as wide as the circle +// inside its border, in the middle, in every state that shows one. +TEST_F(CPDFGenerateAPTest, RadioButtonsDrawACircleInTheMiddleOfTheBox) { + const struct { + const char* style; + const char* line; // the circle line, then what follows it + const char* edges; // the lit and shaded half circles' colours, or none + const char* dot; // where the dot starts: its rightmost point + } kStyles[] = { + {"S", "1 w\n0 1 0 RG\n89.5 30 m\n", nullptr, "74.5 30 m\n"}, + {"D", "1 w\n0 1 0 RG\n[3 ] 0 d\n89.5 30 m\n", nullptr, "74.5 30 m\n"}, + {"B", "1 w\n0 1 0 RG\n89.5 30 m\n", "1 G\n|.75 .75 .55 RG\n", + "74 30 m\n"}, + {"I", "1 w\n0 1 0 RG\n89.5 30 m\n", ".5 G\n|.75 G\n", "74 30 m\n"}, + {"U", "1 w\n0 1 0 RG\n89.5 30 m\n", nullptr, "74.5 30 m\n"}, + }; + const ByteString solid_off = + DrawWidgetInStyle(BorderedKind::kRadioButton, "S")["Off"]; + for (const auto& style : kStyles) { + SCOPED_TRACE(style.style); + std::map states = + DrawWidgetInStyle(BorderedKind::kRadioButton, style.style); + ASSERT_EQ(2u, states.size()); + const ByteString& off = states["Off"]; + const ByteString& on = states["Yes"]; + // The circle: the background from its rightmost point, then the line. + EXPECT_EQ(0u, off.Find("q\n1 1 .8 rg\n90 30 m\n").value_or(1)); + const std::optional line = off.Find(style.line); + ASSERT_TRUE(line.has_value()); + // One stroke for the line, and one for each half circle. + size_t strokes = 0; + for (std::optional at = off.Find("h\nS\n"); at.has_value(); + at = off.Find("h\nS\n", at.value() + 1)) { + ++strokes; + } + size_t arcs = 0; + for (std::optional at = off.Find(" c\nS\n"); at.has_value(); + at = off.Find(" c\nS\n", at.value() + 1)) { + ++arcs; + } + EXPECT_EQ(1u, strokes); + EXPECT_EQ(style.edges ? 2u : 0u, arcs); + if (style.edges) { + const ByteString edges(style.edges); + const size_t split = edges.Find("|").value(); + const std::optional lit = + off.Find(edges.First(split).AsStringView()); + const std::optional shade = + off.Find(edges.Substr(split + 1).AsStringView()); + ASSERT_TRUE(lit.has_value()); + ASSERT_TRUE(shade.has_value()); + EXPECT_LT(line.value(), lit.value()); + EXPECT_LT(lit.value(), shade.value()); + } + if (ByteString(style.style) == "U") { + EXPECT_EQ(solid_off, off); + } + // The circle and its edges pass through no point outside the middle + // square. + for (const CFX_PointF& point : PathPoints(off)) { + EXPECT_GE(point.x, 30 - 1e-3f); + EXPECT_LE(point.x, 90 + 1e-3f); + EXPECT_GE(point.y, -1e-3f); + EXPECT_LE(point.y, 60 + 1e-3f); + } + // On: the same circle and the dot after it. + EXPECT_EQ(off, on.First(off.GetLength())); + EXPECT_FALSE(off.Contains(style.dot)); + EXPECT_TRUE( + on.Contains((ByteString("q\n0 g\n") + style.dot).AsStringView())); + } +} + TEST_F(CPDFGenerateAPTest, GeneratePersistentFreeTextAPAfterDefaultAppearanceColorUpdate) { CPDF_TestDocument doc; diff --git a/core/fpdfdoc/cpdf_richtextlayout.cpp b/core/fpdfdoc/cpdf_richtextlayout.cpp index 1854e4b291..19ebe19838 100644 --- a/core/fpdfdoc/cpdf_richtextlayout.cpp +++ b/core/fpdfdoc/cpdf_richtextlayout.cpp @@ -42,12 +42,17 @@ constexpr float kSubRise = -0.15f; constexpr float kFallbackSize = 12.0f; constexpr float kEpsilon = 0.01f; -// CPVT's auto font size ladder: plain FreeText and form fields with a DA -// size of 0. A field of several lines tries its first quarter. +// CPVT's auto font size ladder: plain FreeText with a DA size of 0 steps +// down it. A form field's automatic size is fitted exactly between its ends +// instead (ArrangeField()). constexpr std::array kAutoSizeSteps = { 4, 6, 8, 9, 10, 12, 14, 18, 20, 25, 30, 35, 40, 45, 50, 55, 60, 70, 80, 90, 100, 110, 120, 130, 144}; +// The largest automatic size of a field of several lines, as Acrobat 26 +// caps it (and CPVT's ladder did, at its first quarter). +constexpr float kLinesAutoSizeCap = 12; + bool IsSpace(wchar_t ch) { return ch == L' ' || ch == 0x00A0 || ch == 0x3000; } @@ -1479,14 +1484,15 @@ CPDF_RichTextLayout::Result CPDF_RichTextLayout::ArrangeField( }; const float typeset_width = std::max(plate_width, 0.0f); - // The size: the biggest step of the ladder the text fits in, searched as - // CPVT's std::lower_bound searches it. + // The size: as large as the text fits, as Acrobat 26 fits a field's text, + // where CPVT stepped down its ladder to the step below. It is found to a + // thousandth of a point by halving the gap between the ladder's ends: 4, + // and 144, or 12 for a field of several lines. Text that doesn't fit at 4 + // is drawn at 4. float size = field.size; if (FXSYS_IsFloatZero(size)) { size = 0; if (plate_width > 0) { - const size_t steps = - field.multiline ? kAutoSizeSteps.size() / 4 : kAutoSizeSteps.size(); auto too_big = [&](float candidate) { Impl impl(fonts_, options_); impl.field = true; @@ -1505,19 +1511,26 @@ CPDF_RichTextLayout::Result CPDF_RichTextLayout::ArrangeField( } return false; }; - size_t first = 0; - size_t count = steps; - while (count > 0) { - const size_t step = count / 2; - if (!too_big(kAutoSizeSteps[first + step])) { - first += step + 1; - count -= step + 1; - } else { - count = step; + const float smallest = kAutoSizeSteps.front(); + const float largest = + field.multiline ? kLinesAutoSizeCap : kAutoSizeSteps.back(); + if (!too_big(largest)) { + size = largest; + } else if (too_big(smallest)) { + size = smallest; + } else { + float fits = smallest; + float over = largest; + while (over - fits > 0.001f) { + const float middle = (fits + over) / 2; + if (too_big(middle)) { + over = middle; + } else { + fits = middle; + } } + size = std::max(smallest, std::floor(fits * 1000) / 1000); } - size = first == steps ? kAutoSizeSteps[steps - 1] - : kAutoSizeSteps[first == 0 ? 0 : first - 1]; } } diff --git a/core/fpdfdoc/cpdf_richtextlayout.h b/core/fpdfdoc/cpdf_richtextlayout.h index e54a38c96b..2dbfd27608 100644 --- a/core/fpdfdoc/cpdf_richtextlayout.h +++ b/core/fpdfdoc/cpdf_richtextlayout.h @@ -99,12 +99,13 @@ class CPDF_RichTextLayout { // A form field's text, or a redaction label, laid out with the geometry // PDFium's form filler gives it (CPVT): words break where CPVT breaks them, // a line is as high as its fonts' ascent and descent with no leading and - // is aligned on its own, a size of 0 is the biggest of CPVT's sizes the - // text fits in (12 pt at most for several lines), and a comb puts one - // character in the middle of each cell. Fonts, shaping and order are this - // layout's: each cluster in the first font that has it, then the last - // resort; the Unicode bidi algorithm with the direction of the first strong - // character. + // is aligned on its own, a size of 0 is the largest size the text fits + // at, to a thousandth of a point (12 pt at most for several lines), as + // Acrobat fits a field's text where CPVT stepped down a ladder of sizes, + // and a comb puts one character in the middle of each cell. Fonts, shaping + // and order are this layout's: each cluster in the first font that has it, + // then the last resort; the Unicode bidi algorithm with the direction of + // the first strong character. struct Field { WideString text; int face_entry = -1; // the /DA font diff --git a/docs/embedpdf/fork-ledger.md b/docs/embedpdf/fork-ledger.md index 2635fb7b5e..cf0d98b0f4 100644 --- a/docs/embedpdf/fork-ledger.md +++ b/docs/embedpdf/fork-ledger.md @@ -351,11 +351,12 @@ upstream's `FPDFAnnot_AppendObject` and `FPDFAnnot_SetFontColor` in `fpdf_annot. `epdf_annot.cpp`, `epdf_form.cpp`, `epdf_redact.cpp` and the rich text writer. A push button's icon (`/MK /I`) is drawn in every layout that shows one. Alone (`/MK /TP 1`, an image field, and any layout 2 to 6 without a caption) `GenerateIconButtonAP` draws it. With the caption (`/MK /TP` -2 to 6) `GeneratePushButtonFormAP` draws both, and shares the button between them by the rule of -upstream's form filler (`SplitButton`, after `GetPushButtonAppStream` in -`fpdfsdk/cpdfsdk_appstream.cpp`, which stays unchanged), so a button looks the same whichever drew -it. The engine writes layouts 0 and 1 only, a caption or an image field, so layouts 2 to 6 are -met only in buttons other apps made. Either way the icon fit (`/MK /IF`) is read through +2 to 6) `GeneratePushButtonFormAP` draws both, and shares the button between them as Acrobat 26 +does (`ButtonPlate`, `SplitButton`), a rule measured from buttons Acrobat drew itself: the icon is +fitted twice the border's width in from every edge, and the caption's strip and its gaps grow with +the border. Upstream's form filler (`GetPushButtonAppStream` in `fpdfsdk/cpdfsdk_appstream.cpp`, +unchanged) shares a button by its own rule. The engine writes layouts 0 and 1 only, a caption or +an image field, so layouts 2 to 6 are met only in buttons other apps made. Either way the icon fit (`/MK /IF`) is read through upstream's `CPDF_IconFit` and the icon is placed by our own `IconPlacement`, by ISO 32000-2 Table 250: upstream's own placement (`CPDF_IconFit::GetScale` and `GetImageOffset`, used by its form filler) puts an icon whose fit names no `/A` at the bottom left, where the table's default is the @@ -365,7 +366,15 @@ a picture the button showed, so it is never written into, and the icon its resou with it. Before a form drawer replaces an appearance, a widget whose `/AP` is an indirect object gets a copy of its own (`OwnAppearanceDict`), and `epdf_annot.cpp` does the same for `/MK` and `/BS` before a setter writes one (`OwnMKForWriting` and `BorderStyleDictForWrite`, both through -`OwnDictEntry`): another annotation may name the same dictionary. A colour is +`OwnDictEntry`): another annotation may name the same dictionary. Every widget kind draws every +border style, as Acrobat does: a text field, a signature field, a check box, a push button and a +radio button that shows no circle draw one box (`WriteFieldBox`); a radio button that shows a +circle draws it in the middle of its box, as wide as the box is high (`WriteRadioCircleBox`), and +draws an underline as a whole circle. A beveled widget border's shaded edges are the background +less a quarter (`BeveledShade`), on every field kind; `GenerateBorderAP` takes that shade from its +caller. A field's automatic text size is fitted exactly (the rich text layout's `ArrangeField`), a +list box's to its widest option (`ListBoxAutoSize`), and a check box's check is as large as +Acrobat's (`CheckSymbolRect`). A colour is set as a new array, never written into the one the entry named, which may be an object another `/MK` names too. An `/MK` setter that changes nothing writes nothing, and it changes nothing only when the entry is well formed and reads as the value (three numbers from 0 to 1, a string, an @@ -376,16 +385,18 @@ view of it in `cpdf_appearancegenerator_common.cpp` (`GetAnnotBorderStyleInfo`, **Guarded by.** `check-fork-tags.py` fails when upstream's files differ from upstream (`fork-pristine.txt`); `upstream-preview.py` lists new upstream callers of `CPDF_GenerateAP::`, and upstream's commits to its generator. `epdf_widget_drawing_embeddertest.cpp` for a button's icon; -its `AButtonIsSharedAsTheFormFillerSharesIt` runs upstream's form filler on the same buttons and -compares the two. `CPDFGenerateAPTest.BorderArrayDrawsAsBorderStyleForEveryKind` draws every kind +its `AButtonIsSharedAsAcrobatSharesIt` holds Acrobat's measured rule for ten borders and three +sizes. `CPDFGenerateAPTest.WidgetBoxesDrawEveryBorderStyle` and +`RadioButtonsDrawACircleInTheMiddleOfTheBox` hold every widget kind's border styles, and +`epdf_widget_text_size_embeddertest.cpp` the automatic sizes and the check. `CPDFGenerateAPTest.BorderArrayDrawsAsBorderStyleForEveryKind` draws every kind that has a border from both keys; the border setters' tests are in `epdf_annot_embeddertest.cpp` (`ABorderCallThatChangesNothingWritesNothing`, `ASharedBorderStyleIsNotWrittenInto`). **When upstream touches this.** A commit to `cpdf_generateap.*`: port it to ours or skip it, with the reason in the sync report. A new upstream caller of `CPDF_GenerateAP::`: route it to ours, or accept it in the report. A change to what `CPDF_IconFit`'s readers return (`GetScaleMethod`, `IsProportionalScale`, `GetIconBottomLeftPosition`, `GetFittingBounds`): `IconPlacement` reads the -file through them. A change to how `GetPushButtonAppStream` shares a button: `SplitButton` -follows it, and the comparing test fails until it does. A drawer ported from upstream reads `/BS` +file through them. A change to how `GetPushButtonAppStream` shares a button needs nothing: +`SplitButton` follows Acrobat. A drawer ported from upstream reads `/BS` alone, as upstream's form fields do: give it our reading, and a row in that test. ## Text @@ -455,8 +466,11 @@ selective flattening. **When upstream touches this.** Attachment APIs and Flate decoding. ### rich-text -**Rule.** Rich-text FreeText layout: parsing, line breaking, shaping, and font resolution. -**Why.** FreeText annotations with mixed styles and scripts. +**Rule.** Rich-text FreeText layout: parsing, line breaking, shaping, and font resolution. A form +field's automatic size (a `/DA` size of 0) is the largest its text fits at, to a thousandth of a +point, at most 12 for several lines, as Acrobat fits it; FreeText steps down CPVT's ladder. +**Why.** FreeText annotations with mixed styles and scripts. A field's text the size Acrobat gives +it, not the ladder's step below. **Where.** `cpdf_richtext*` (ours), line breaking in `fx_linebreak.cpp` and `fgas_linebreak.h`, `fx_unicode`. **Guarded by.** `cpdf_richtextlayout_unittest.cpp`, `cpdf_richtextparser_unittest.cpp`. diff --git a/fpdfsdk/BUILD.gn b/fpdfsdk/BUILD.gn index 976c7ca96e..fba407a9db 100644 --- a/fpdfsdk/BUILD.gn +++ b/fpdfsdk/BUILD.gn @@ -264,6 +264,9 @@ pdfium_embeddertest_source_set("embeddertests") { # button's icons and the appearance drawn from the normal one, a mark a # wrapper places, and one drawing shared with stamps. "epdf_widget_drawing_embeddertest.cpp", + # EmbedPDF: covers a field's automatic text size and a check box's mark, + # as the appearance generator draws them. + "epdf_widget_text_size_embeddertest.cpp", # EmbedPDF: helpers for tests that compare a document before and after # writes. "epdf_edit_test_util.cpp", diff --git a/fpdfsdk/epdf_appearance_state_embeddertest.cpp b/fpdfsdk/epdf_appearance_state_embeddertest.cpp index ce34ce9666..905063bb8d 100644 --- a/fpdfsdk/epdf_appearance_state_embeddertest.cpp +++ b/fpdfsdk/epdf_appearance_state_embeddertest.cpp @@ -341,8 +341,7 @@ TEST_F(EPDFAppearanceStateEmbedderTest, CheckBoxDrawsTheSymbolItsCaptionNames) { EXPECT_NE(cross_content.Find(" l\nS\nQ\n"), std::nullopt) << cross_content; EXPECT_EQ(cross_content.Find(" c\n"), std::nullopt) << cross_content; - // No caption and no colour: the black check this generator always drew, - // byte for byte. + // No caption and no colour: the black check. ScopedFPDFAnnotation plain(FPDFPage_GetAnnot(page.get(), kPlain)); ASSERT_TRUE(plain); ASSERT_TRUE(EPDFAnnot_GenerateFormFieldAP(plain.get())); @@ -370,7 +369,7 @@ TEST_F(EPDFAppearanceStateEmbedderTest, ASSERT_TRUE(square); ASSERT_TRUE(EPDFAnnot_GenerateFormFieldAP(square.get())); const ByteString square_content = OnStateContent(square.get()); - EXPECT_NE(square_content.Find(" re S\n"), std::nullopt) << square_content; + EXPECT_NE(square_content.Find(" re s\n"), std::nullopt) << square_content; EXPECT_NE(square_content.Find("q\n1 0 0 rg\n"), std::nullopt) << square_content; EXPECT_NE(square_content.Find(" l\nh\nf\nQ\n"), std::nullopt) @@ -379,13 +378,13 @@ TEST_F(EPDFAppearanceStateEmbedderTest, EXPECT_EQ(kRed, DrawAnnot(page.get(), square.get(), FPDF_ANNOT_APPEARANCEMODE_NORMAL, "Yes", 100, 100)); - // No caption: the dot this generator always drew, now in the /DA colour. + // No caption: the dot, in the /DA colour. ScopedFPDFAnnotation dot(FPDFPage_GetAnnot(page.get(), kDot)); ASSERT_TRUE(dot); ASSERT_TRUE(EPDFAnnot_GenerateFormFieldAP(dot.get())); const ByteString dot_content = OnStateContent(dot.get()); EXPECT_NE(dot_content.Find("q\n0 0 1 rg\n"), std::nullopt) << dot_content; - EXPECT_NE(dot_content.Find(" c\nh\nf*\nQ\n"), std::nullopt) << dot_content; + EXPECT_NE(dot_content.Find(" c\nh\nf\nQ\n"), std::nullopt) << dot_content; EXPECT_EQ(kBlue, DrawAnnot(page.get(), dot.get(), FPDF_ANNOT_APPEARANCEMODE_NORMAL, "Yes", 220, 100)); diff --git a/fpdfsdk/epdf_richtextlayout_embeddertest.cpp b/fpdfsdk/epdf_richtextlayout_embeddertest.cpp index 3e9f9d08ab..a89a41e9c0 100644 --- a/fpdfsdk/epdf_richtextlayout_embeddertest.cpp +++ b/fpdfsdk/epdf_richtextlayout_embeddertest.cpp @@ -450,7 +450,10 @@ struct PlacedCharacter { // The field layout keeps the geometry of PDFium's form filler (CPVT) where // CPVT drew correctly: the same characters at the same places, for the // standard fonts, the sizes, fitted sizes, alignments, several lines, long -// words, passwords, limits and combs the forms parity gate draws. +// words, passwords, limits and combs the forms parity gate draws. A fitted +// size (0) is the largest the text fits at, as Acrobat fits it, where CPVT +// steps down its ladder: it is never smaller than CPVT's step, and the +// characters are where CPVT puts them at that size. TEST_F(EPDFRichTextLayoutEmbedderTest, FieldMatchesCpvt) { struct Case { const char* font; @@ -521,7 +524,40 @@ TEST_F(EPDFRichTextLayoutEmbedderTest, FieldMatchesCpvt) { ASSERT_TRUE(font); const bool centered = !c.multiline; - // CPVT, as the form generator drove it. + // The field layout. + std::vector actual; + float fitted_size = 0; + { + CPDF_AnnotFontMap map(doc, font, "F", + /*allow_registered_fallbacks=*/false); + ASSERT_TRUE(map.HasDefaultFont()); + CPDF_RichTextLayout::Field field; + field.text = c.text; + field.face_entry = 0; + field.size = c.size; + field.alignment = c.alignment; + field.multiline = c.multiline; + field.password = c.password; + field.limit = c.limit; + field.cells = c.cells; + field.centered = centered; + CPDF_RichTextLayout layout(&map, {}); + const CPDF_RichTextLayout::Result laid = + layout.ArrangeField(field, c.plate); + fitted_size = laid.body_size; + for (const Line& laid_line : laid.lines) { + const float y = c.plate.top - laid_line.baseline_y; + for (const GlyphRun& run : laid_line.runs) { + float x = c.plate.left + run.x; + for (const CPDF_RichTextLayout::ShapedGlyph& glyph : run.glyphs) { + actual.push_back({run.text[glyph.cluster], x, y}); + x += glyph.x_advance; + } + } + } + } + + // CPVT, as the form generator drove it, at the size the layout fitted. std::vector expected; { CPVT_FontMap cpvt_fonts(doc, /*resources=*/nullptr, font, "F"); @@ -530,7 +566,22 @@ TEST_F(EPDFRichTextLayoutEmbedderTest, FieldMatchesCpvt) { vt.SetPlateRect(c.plate); vt.SetAlignment(CPVT_VariableText::ToAlignment(c.alignment)); if (c.size == 0) { - vt.SetAutoFontSize(true); + // CPVT's own step first, which the fitted size is never under. + CPVT_VariableText stepped(&provider); + stepped.SetPlateRect(c.plate); + stepped.SetAutoFontSize(true); + stepped.SetMultiLine(c.multiline); + stepped.SetAutoReturn(c.multiline); + if (c.cells > 0) { + stepped.SetCharArray(static_cast(c.cells)); + } else { + stepped.SetLimitChar(static_cast(c.limit)); + } + stepped.Initialize(); + stepped.SetText(c.text); + stepped.RearrangeAll(); + EXPECT_GE(fitted_size, stepped.GetFontSize() - 0.001f); + vt.SetFontSize(fitted_size); } else { vt.SetFontSize(c.size); } @@ -565,37 +616,6 @@ TEST_F(EPDFRichTextLayoutEmbedderTest, FieldMatchesCpvt) { } } - // The field layout. - std::vector actual; - { - CPDF_AnnotFontMap map(doc, font, "F", - /*allow_registered_fallbacks=*/false); - ASSERT_TRUE(map.HasDefaultFont()); - CPDF_RichTextLayout::Field field; - field.text = c.text; - field.face_entry = 0; - field.size = c.size; - field.alignment = c.alignment; - field.multiline = c.multiline; - field.password = c.password; - field.limit = c.limit; - field.cells = c.cells; - field.centered = centered; - CPDF_RichTextLayout layout(&map, {}); - const CPDF_RichTextLayout::Result laid = - layout.ArrangeField(field, c.plate); - for (const Line& laid_line : laid.lines) { - const float y = c.plate.top - laid_line.baseline_y; - for (const GlyphRun& run : laid_line.runs) { - float x = c.plate.left + run.x; - for (const CPDF_RichTextLayout::ShapedGlyph& glyph : run.glyphs) { - actual.push_back({run.text[glyph.cluster], x, y}); - x += glyph.x_advance; - } - } - } - } - ASSERT_EQ(expected.size(), actual.size()); for (size_t i = 0; i < expected.size(); ++i) { SCOPED_TRACE(i); diff --git a/fpdfsdk/epdf_widget_drawing_embeddertest.cpp b/fpdfsdk/epdf_widget_drawing_embeddertest.cpp index 70c02e46ac..2ee03bbee1 100644 --- a/fpdfsdk/epdf_widget_drawing_embeddertest.cpp +++ b/fpdfsdk/epdf_widget_drawing_embeddertest.cpp @@ -42,10 +42,7 @@ #include "core/fxcrt/fx_coordinates.h" #include "core/fxcrt/fx_stream.h" #include "core/fxcrt/retain_ptr.h" -#include "fpdfsdk/cpdfsdk_formfillenvironment.h" #include "fpdfsdk/cpdfsdk_helpers.h" -#include "fpdfsdk/cpdfsdk_pageview.h" -#include "fpdfsdk/cpdfsdk_widget.h" #include "fpdfsdk/epdf_edit_test_util.h" #include "public/cpp/fpdf_scopers.h" #include "public/epdf_annot.h" @@ -54,7 +51,6 @@ #include "public/epdf_view.h" #include "public/fpdf_annot.h" #include "public/fpdf_edit.h" -#include "public/fpdf_formfill.h" #include "public/fpdf_save.h" #include "public/fpdfview.h" #include "testing/embedder_test.h" @@ -275,26 +271,6 @@ std::optional DrawnIconOf(FPDF_ANNOTATION annot) { return icon; } -// The part an appearance clips its caption to, in the appearance's own -// space, or nothing when it draws no caption. -std::optional DrawnCaptionOf(FPDF_ANNOTATION annot) { - RetainPtr appearance = AppearanceOf(annot); - if (!appearance) { - return std::nullopt; - } - const std::string content = StreamBytes(appearance.Get()); - const size_t text = content.find("BT\n"); - const size_t start = - text == std::string::npos ? text : content.rfind("q\n", text); - float part[4]; - if (start == std::string::npos || - sscanf(content.c_str() + start, "q\n%f %f %f %f re W n\nBT\n", &part[0], - &part[1], &part[2], &part[3]) != 4) { - return std::nullopt; - } - return CFX_FloatRect(part[0], part[1], part[0] + part[2], part[1] + part[3]); -} - void ExpectRectNear(const CFX_FloatRect& expected, const CFX_FloatRect& actual, float within = 1e-3f) { @@ -528,11 +504,9 @@ const struct { {kCaptionLeft, "the caption left of the icon"}, {kCaptionOver, "the caption over the icon"}}; -// The room the caption "Go" takes at `size` in the font the button's -// appearance writes it in: its width, and the height of its line, which is -// the font's ascent and descent, as PDFium's form filler measures a line. -// The tests' stand-in for Helvetica has its own. -CFX_SizeF CaptionRoomOf(FPDF_ANNOTATION annot, float size = 12) { +// The font a button's appearance writes its caption in: the one its +// resources name. +RetainPtr CaptionFontOf(FPDF_ANNOTATION annot) { RetainPtr appearance = AppearanceOf(annot); RetainPtr resources = appearance ? appearance->GetDict()->GetDictFor("Resources") : nullptr; @@ -540,7 +514,7 @@ CFX_SizeF CaptionRoomOf(FPDF_ANNOTATION annot, float size = 12) { resources ? resources->GetDictFor("Font") : nullptr; if (!fonts || fonts->size() == 0) { ADD_FAILURE() << "the appearance names no font"; - return CFX_SizeF(); + return nullptr; } RetainPtr dict; { @@ -553,6 +527,17 @@ CFX_SizeF CaptionRoomOf(FPDF_ANNOTATION annot, float size = 12) { pdfium::WrapRetain(const_cast(dict.Get()))); if (!font) { ADD_FAILURE() << "the appearance's font doesn't load"; + } + return font; +} + +// The room the caption "Go" takes at `size` in the font the button's +// appearance writes it in: its width, and the height of its line, which is +// the font's ascent and descent. The tests' stand-in for Helvetica has its +// own. +CFX_SizeF CaptionRoomOf(FPDF_ANNOTATION annot, float size = 12) { + RetainPtr font = CaptionFontOf(annot); + if (!font) { return CFX_SizeF(); } return CFX_SizeF( @@ -588,48 +573,105 @@ CFX_FloatRect CaptionInkOf(const CFX_FloatRect& part) { return CFX_FloatRect(x - 9, y - 6, x + 9, y + 6); } -// Checks that `caption` and `icon` share `plate` as `layout` says: the -// caption in a strip as high as its line, at the bottom or the top, or as -// wide as its text, at the right or the left, and the icon in the rest; or -// both in all of it. `room` is what the caption takes. -void ExpectPartsShare(int layout, - const CFX_FloatRect& plate, - const CFX_SizeF& room, - const CFX_FloatRect& caption, - const CFX_FloatRect& icon) { - constexpr float kWithin = 1e-2f; - if (layout == kCaptionOver) { - ExpectRectNear(plate, caption, kWithin); - ExpectRectNear(plate, icon, kWithin); - return; - } - CFX_FloatRect both = caption; - both.Union(icon); - ExpectRectNear(plate, both, kWithin); +// Where Acrobat 26 puts a caption's line and its icon's part in a button +// that shows both, in the appearance's own space: the rule SplitButton() +// draws by. Call b the border's width, `border`, counted twice for beveled +// and inset. The icon's part is the button's `box` less 2b at each edge +// (all of it when the icon fit says /FB) less a strip as deep as 3b and the +// caption's extent, its line's height below or above the icon and its width +// beside it. The caption's line is in the middle of the room between that +// part and a point Acrobat measures from: b above the bottom edge, 2b below +// the top edge, the right edge itself, 2b in from the left edge. When the +// strip leaves no room the icon is left out, and the room reaches the +// plate's far edge. Across, the line is in the middle. Over the icon, the +// line is in the middle of the plate. `room` is the line's width and +// height. +struct ButtonParts { + CFX_FloatRect caption; + CFX_FloatRect icon; // empty when the icon is left out +}; + +ButtonParts AcrobatButtonParts(int layout, + const CFX_FloatRect& box, + float border, + const CFX_SizeF& room, + bool fit_to_bounds = false) { + const float b = border; + CFX_FloatRect plate = box; + if (!fit_to_bounds) { + plate.Deflate(2 * b, 2 * b); + } + ButtonParts parts{CFX_FloatRect(), plate}; + // The line, `room` in size, with its middle at (x, y). + auto line_at = [&room](float x, float y) { + return CFX_FloatRect(x - room.width / 2, y - room.height / 2, + x + room.width / 2, y + room.height / 2); + }; + const float middle_x = (plate.left + plate.right) / 2; + const float middle_y = (plate.bottom + plate.top) / 2; switch (layout) { case kCaptionBelow: - EXPECT_NEAR(plate.bottom, caption.bottom, kWithin); - EXPECT_NEAR(room.height, caption.Height(), kWithin); - EXPECT_NEAR(caption.top, icon.bottom, kWithin); + parts.icon.bottom = box.bottom + 3 * b + room.height; + if (parts.icon.bottom >= plate.top) { + parts.icon = CFX_FloatRect(); + } + parts.caption = line_at( + middle_x, (box.bottom + b + + (parts.icon.IsEmpty() ? plate.top : parts.icon.bottom)) / + 2); break; case kCaptionAbove: - EXPECT_NEAR(plate.top, caption.top, kWithin); - EXPECT_NEAR(room.height, caption.Height(), kWithin); - EXPECT_NEAR(caption.bottom, icon.top, kWithin); + parts.icon.top = box.top - 3 * b - room.height; + if (parts.icon.top <= plate.bottom) { + parts.icon = CFX_FloatRect(); + } + parts.caption = line_at( + middle_x, (box.top - 2 * b + + (parts.icon.IsEmpty() ? plate.bottom : parts.icon.top)) / + 2); break; case kCaptionRight: - EXPECT_NEAR(plate.right, caption.right, kWithin); - EXPECT_NEAR(room.width, caption.Width(), kWithin); - EXPECT_NEAR(caption.left, icon.right, kWithin); + parts.icon.right = box.right - 3 * b - room.width; + if (parts.icon.right <= plate.left) { + parts.icon = CFX_FloatRect(); + } + parts.caption = line_at( + (box.right + (parts.icon.IsEmpty() ? plate.left : parts.icon.right)) / + 2, + middle_y); break; case kCaptionLeft: - EXPECT_NEAR(plate.left, caption.left, kWithin); - EXPECT_NEAR(room.width, caption.Width(), kWithin); - EXPECT_NEAR(caption.right, icon.left, kWithin); + parts.icon.left = box.left + 3 * b + room.width; + if (parts.icon.left >= plate.right) { + parts.icon = CFX_FloatRect(); + } + parts.caption = + line_at((box.left + 2 * b + + (parts.icon.IsEmpty() ? plate.right : parts.icon.left)) / + 2, + middle_y); break; default: - ADD_FAILURE() << "not a layout that shows both"; + parts.caption = line_at(middle_x, middle_y); + break; } + return parts; +} + +// Checks that a button drew its caption's line at `caption` and fitted its +// icon into `icon` as Acrobat's rule says (AcrobatButtonParts()). +void ExpectPartsShare(int layout, + const CFX_FloatRect& box, + float border, + const CFX_SizeF& room, + const CFX_FloatRect& caption, + const CFX_FloatRect& icon, + bool fit_to_bounds = false) { + constexpr float kWithin = 1e-2f; + const ButtonParts expected = + AcrobatButtonParts(layout, box, border, room, fit_to_bounds); + ExpectRectNear(expected.caption, caption, kWithin); + ExpectRectNear(expected.icon, icon, kWithin); } // What a button's appearance draws, read from its content whoever wrote it: @@ -698,6 +740,32 @@ ButtonContent ReadButtonContent(const std::string& content) { return read; } +// Where an appearance writes its caption "Go", in the appearance's own +// space: the box its line takes, from where its text starts and as wide as +// the text, from its baseline less the font's descent up to its ascent, in +// the font and at the size the appearance names. Nothing when it draws no +// caption. (Every caption is clipped to the button inside its border, so the +// clip doesn't say where a caption is.) +std::optional DrawnCaptionOf(FPDF_ANNOTATION annot) { + RetainPtr appearance = AppearanceOf(annot); + if (!appearance) { + return std::nullopt; + } + const ButtonContent read = ReadButtonContent(StreamBytes(appearance.Get())); + if (!read.caption_start || !read.caption_size) { + return std::nullopt; + } + RetainPtr font = CaptionFontOf(annot); + if (!font) { + return std::nullopt; + } + const float size = *read.caption_size; + const CFX_PointF start = *read.caption_start; + return CFX_FloatRect(start.x, start.y + font->GetTypeDescent() * size / 1000, + start.x + font->GetStringWidth("Go") * size / 1000, + start.y + font->GetTypeAscent() * size / 1000); +} + } // namespace class EPDFWidgetDrawingEmbedderTest : public EmbedderTest { @@ -878,7 +946,8 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, SetsReadsAndClearsAnIcon) { EXPECT_EQ("Form", appearance->GetDict()->GetNameFor("Subtype")); EXPECT_EQ(CFX_FloatRect(0, 0, 202, 102), appearance->GetDict()->GetRectFor("BBox")); - EXPECT_EQ("q\nQ\nq\n1 1 200 100 re W n\n1 0 0 1 1 1 cm\n/FRM Do\nQ\n", + // The border's width is 1 (no /BS), so the icon is fitted 2 in: 198 by 98. + EXPECT_EQ("q\nQ\nq\n2 2 198 98 re W n\n.98 0 0 .98 3 2 cm\n/FRM Do\nQ\n", StreamBytes(appearance.Get())); EXPECT_EQ(drawing, DrawnIconNumber(button.get())); // A generated button's appearance is no wrapper: its picture is its icon. @@ -1022,9 +1091,9 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, RefusesWithoutWriting) { EXPECT_EQ(0u, EPDFLayer_GetPromotedObjectCount(foreign.layer)); } -// The icon is fitted into the button less the border's width at each edge, -// the width /BS gives whether or not a colour paints it, and clipped there. -// /MK /IF /FB takes the whole button. +// The icon is fitted into the button less twice the border's width at each +// edge, as Acrobat 26 fits it, the width /BS gives whether or not a colour +// paints it, and clipped there. /MK /IF /FB takes the whole button. TEST_F(EPDFWidgetDrawingEmbedderTest, AnIconIsFittedInsideTheBorder) { const FS_RECTF kStands{100, 308, 308, 200}; // 208 by 108 const struct { @@ -1035,18 +1104,19 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, AnIconIsFittedInsideTheBorder) { CFX_FloatRect plate; CFX_FloatRect picture; } kCases[] = { - // No /BS: a border of 1. 206 by 106 inside, so the picture is 206 by - // 103 in its middle. + // No /BS: a border of 1. 204 by 104 inside it, so the picture is 204 + // by 102 in its middle. {"no /BS", {}, false, false, - CFX_FloatRect(1, 1, 207, 107), - CFX_FloatRect(1, 2.5f, 207, 105.5f)}, + CFX_FloatRect(2, 2, 206, 106), + CFX_FloatRect(2, 3, 206, 105)}, {"no border", 0.0f, false, false, CFX_FloatRect(0, 0, 208, 108), CFX_FloatRect(0, 2, 208, 106)}, - {"a border of 4", 4.0f, true, false, CFX_FloatRect(4, 4, 204, 104), - CFX_FloatRect(4, 4, 204, 104)}, + // 192 by 92 inside: the picture is 184 by 92 in its middle. + {"a border of 4", 4.0f, true, false, CFX_FloatRect(8, 8, 200, 100), + CFX_FloatRect(12, 8, 196, 100)}, {"a border of 4, fitted to the bounds", 4.0f, true, true, CFX_FloatRect(0, 0, 208, 108), CFX_FloatRect(0, 2, 208, 106)}, }; @@ -1077,7 +1147,11 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, AnIconIsFittedInsideTheBorder) { // The border is stroked before the picture is drawn, when it has a // colour. const std::string content = StreamBytes(AppearanceOf(button.get()).Get()); - EXPECT_EQ(expected.painted, content.find(" re S\n") != std::string::npos); + const size_t stroked = content.find(" re s\n"); + EXPECT_EQ(expected.painted, stroked != std::string::npos); + if (expected.painted) { + EXPECT_LT(stroked, content.find("/FRM Do")); + } } } } @@ -1387,13 +1461,14 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, ADrawingWithAMatrixIsPlacedByItsBox) { form->GetDict()->GetMatrixFor("Matrix")); } - // An icon: a button 204 by 104 with a border of 2 shows it at its size. + // An icon: a button 204 by 104 with a border of 2 fits it into 196 by 96, + // 4 in: 192 by 96 in the middle. ScopedFPDFAnnotation button = NewButton({100, 304, 304, 200}, 2.0f); ASSERT_TRUE(button); SetIcon(button.get(), drawing); const std::optional drawn = DrawnIconOf(button.get()); ASSERT_TRUE(drawn); - ExpectRectNear(CFX_FloatRect(2, 2, 202, 102), drawn->picture); + ExpectRectNear(CFX_FloatRect(6, 4, 198, 100), drawn->picture); // A mark: a widget 100 by 50 shows it at half its size. ScopedFPDFAnnotation widget = NewSignatureWidget({100, 150, 200, 100}); @@ -1490,7 +1565,7 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, ASavedFileHoldsTheIconInBothPlaces) { EXPECT_EQ(std::vector({icon}), DrawingsOf(reopened.get())); const std::optional drawn = DrawnIconOf(button.get()); ASSERT_TRUE(drawn); - ExpectRectNear(CFX_FloatRect(2, 2, 202, 102), drawn->picture); + ExpectRectNear(CFX_FloatRect(6, 4, 198, 100), drawn->picture); const Shown shown(page.get()); EXPECT_EQ(kRed, shown.At(150, 250)); EXPECT_EQ(kBlue, shown.At(250, 250)); @@ -1513,9 +1588,10 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, AnIconReadsUprightOnATurnedPage) { ASSERT_TRUE( EPDFAnnot_SetMKColor(button.get(), EPDF_MK_COLOR_BC, 0, 255, 0)); SetIcon(button.get(), AddDrawing(doc_.get())); + // 98 by 48 inside twice the border of 1: the picture is 96 by 48. const std::optional drawn = DrawnIconOf(button.get()); ASSERT_TRUE(drawn); - ExpectRectNear(CFX_FloatRect(1, 1, 101, 51), drawn->picture); + ExpectRectNear(CFX_FloatRect(3, 2, 99, 50), drawn->picture); } const std::string bytes = SavedBytes(doc_.get()); ASSERT_FALSE(bytes.empty()); @@ -1597,7 +1673,7 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, AForeignButtonKeepsItsIconInEveryLayout) { EXPECT_EQ(shows_caption, shown.HasInkIn(CFX_FloatRect(20, bottom, 122, bottom + 42))); if (shows_icon && shows_caption) { - ExpectPartsShare(layout, CFX_FloatRect(1, 1, 101, 41), + ExpectPartsShare(layout, CFX_FloatRect(0, 0, 102, 42), 1, CaptionRoomOf(button.get()), *caption, DrawnIconOf(button.get())->plate); } @@ -1645,8 +1721,8 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, AForeignIconOnlyButtonSurvivesARedraw) { EXPECT_EQ(kForeignIcon, DrawnIconNumber(button.get())); std::optional drawn = DrawnIconOf(button.get()); ASSERT_TRUE(drawn); - ExpectRectNear(CFX_FloatRect(1, 1, 101, 41), drawn->plate); - ExpectRectNear(CFX_FloatRect(11, 1, 91, 41), drawn->picture); + ExpectRectNear(CFX_FloatRect(2, 2, 100, 40), drawn->plate); + ExpectRectNear(CFX_FloatRect(13, 2, 89, 40), drawn->picture); EXPECT_EQ(kRed, ShownColorAt(page.get(), 51, 81)); EXPECT_EQ(kBlue, ShownColorAt(page.get(), 91, 81)); // An icon-only button shows no caption, though the file has one. @@ -1662,8 +1738,8 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, AForeignIconOnlyButtonSurvivesARedraw) { EXPECT_EQ(kForeignIcon, DrawnIconNumber(button.get())); drawn = DrawnIconOf(button.get()); ASSERT_TRUE(drawn); - ExpectRectNear(CFX_FloatRect(3, 3, 99, 39), drawn->plate); - ExpectRectNear(CFX_FloatRect(15, 3, 87, 39), drawn->picture); + ExpectRectNear(CFX_FloatRect(6, 6, 96, 36), drawn->plate); + ExpectRectNear(CFX_FloatRect(21, 6, 81, 36), drawn->picture); EXPECT_EQ(kRed, ShownColorAt(page.get(), 51, 81)); EXPECT_EQ(kBlue, ShownColorAt(page.get(), 91, 81)); @@ -1674,18 +1750,18 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, AForeignIconOnlyButtonSurvivesARedraw) { EXPECT_EQ(kForeignIcon, DrawnIconNumber(button.get())); drawn = DrawnIconOf(button.get()); ASSERT_TRUE(drawn); - ExpectRectNear(CFX_FloatRect(3, 3, 203, 103), drawn->picture); + ExpectRectNear(CFX_FloatRect(9, 6, 197, 100), drawn->picture); EXPECT_EQ(kRed, ShownColorAt(page.get(), 200, 300)); EXPECT_EQ(kBlue, ShownColorAt(page.get(), 300, 300)); - // Turned a quarter turn: laid out 106 by 206, the picture is 100 by 50 in + // Turned a quarter turn: laid out 106 by 206, the picture is 94 by 47 in // its middle and its left is at the bottom. ASSERT_TRUE(EPDFAnnot_SetMKRotation(button.get(), 90)); ASSERT_TRUE(EPDFAnnot_GenerateFormFieldAP(button.get())); EXPECT_EQ(kForeignIcon, DrawnIconNumber(button.get())); drawn = DrawnIconOf(button.get()); ASSERT_TRUE(drawn); - ExpectRectNear(CFX_FloatRect(3, 78, 103, 128), drawn->picture); + ExpectRectNear(CFX_FloatRect(6, 79.5f, 100, 126.5f), drawn->picture); EXPECT_EQ(kRed, ShownColorAt(page.get(), 253, 280)); EXPECT_EQ(kBlue, ShownColorAt(page.get(), 253, 326)); button.reset(); @@ -1998,7 +2074,7 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, AnIconOnlyButtonCanBeDrawnInMemory) { EXPECT_EQ(0u, drawn->normal_stream->GetObjNum()); EXPECT_EQ(CFX_FloatRect(0, 0, 102, 42), drawn->normal_stream->GetDict()->GetRectFor("BBox")); - EXPECT_EQ("q\nQ\nq\n1 1 100 40 re W n\n.4 0 0 .4 11 1 cm\n/FRM Do\nQ\n", + EXPECT_EQ("q\nQ\nq\n2 2 98 38 re W n\n.38 0 0 .38 13 2 cm\n/FRM Do\nQ\n", StreamBytes(drawn->normal_stream.Get())); EXPECT_EQ(kForeignIcon, drawn->normal_stream->GetDict() ->GetDictFor("Resources") @@ -2553,13 +2629,14 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, ListingDrawingsWritesNothing) { } // In the layouts that show a caption and an icon, a button that has both -// draws both, each in its part of the button inside the border: the caption -// in a strip as high as its line below or above the icon, or as wide as its -// text right or left of it, and the icon fitted into the rest. Over the icon -// both take all of it, and the caption is drawn last, on top. /MK /I still -// names the drawing, and the appearance draws that same form. +// draws both, as Acrobat 26 shares a button (AcrobatButtonParts()): the icon +// fitted into the button less twice the border at each edge and less the +// caption's strip, and the caption between the icon and the edge, below or +// above the icon, or right or left of it. Over the icon the caption is in +// the middle, drawn last, on top. /MK /I still names the drawing, and the +// appearance draws that same form. TEST_F(EPDFWidgetDrawingEmbedderTest, ACaptionAndAnIconEachTakeTheirPart) { - // 204 by 104 with a border of 2: 200 by 100 inside it, from (2, 2). + // 204 by 104 with a border of 2: the icon's room is 196 by 96 from (4, 4). const FS_RECTF kStands{100, 254, 304, 150}; ScopedFPDFAnnotation button = NewButton(kStands, 2.0f); ASSERT_TRUE(button); @@ -2570,33 +2647,42 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, ACaptionAndAnIconEachTakeTheirPart) { const CFX_SizeF room = CaptionRoomOf(button.get()); ASSERT_GT(room.width, 0); ASSERT_GT(room.height, 0); - - const float low = 2 + room.height; - const float high = 102 - room.height; - const float near = 2 + room.width; - const float far = 202 - room.width; + const float w = room.width; + const float h = room.height; + + // The icon's part ends 3 * 2 and the caption's extent in from the + // caption's edge. The caption is 2 * 2 from the bottom edge, 2.5 * 2 from + // the top, 1.5 * 2 from the right and 2.5 * 2 from the left, and in the + // middle across. + const float low = 6 + h; + const float high = 98 - h; + const float near = 6 + w; + const float far = 198 - w; + const float middle_x = 102 - w / 2; + const float middle_y = 52 - h / 2; // The picture is twice as wide as high, and stands in the middle of its - // part. Above or below the caption's strip it is as high as the room left, - // so it is the strip's height in from each side. Beside the caption's - // column it is as wide as the room left, so it is a quarter of the - // column's width in from the bottom and from the top. - const float in_x = room.height; - const float in_y = room.width / 4; + // part, as large as the part lets it be. + auto fitted = [](const CFX_FloatRect& part) { + const float scale = std::min(part.Width() / 200, part.Height() / 100); + const float x = (part.left + part.right) / 2; + const float y = (part.bottom + part.top) / 2; + return CFX_FloatRect(x - 100 * scale, y - 50 * scale, x + 100 * scale, + y + 50 * scale); + }; const struct { CFX_FloatRect caption; CFX_FloatRect icon; - CFX_FloatRect picture; } kExpected[] = { - {CFX_FloatRect(2, 2, 202, low), CFX_FloatRect(2, low, 202, 102), - CFX_FloatRect(2 + in_x, low, 202 - in_x, 102)}, - {CFX_FloatRect(2, high, 202, 102), CFX_FloatRect(2, 2, 202, high), - CFX_FloatRect(2 + in_x, 2, 202 - in_x, high)}, - {CFX_FloatRect(far, 2, 202, 102), CFX_FloatRect(2, 2, far, 102), - CFX_FloatRect(2, 2 + in_y, far, 102 - in_y)}, - {CFX_FloatRect(2, 2, near, 102), CFX_FloatRect(near, 2, 202, 102), - CFX_FloatRect(near, 2 + in_y, 202, 102 - in_y)}, - {CFX_FloatRect(2, 2, 202, 102), CFX_FloatRect(2, 2, 202, 102), - CFX_FloatRect(2, 2, 202, 102)}, + {CFX_FloatRect(middle_x, 4, middle_x + w, 4 + h), + CFX_FloatRect(4, low, 200, 100)}, + {CFX_FloatRect(middle_x, 99 - h, middle_x + w, 99), + CFX_FloatRect(4, 4, 200, high)}, + {CFX_FloatRect(201 - w, middle_y, 201, middle_y + h), + CFX_FloatRect(4, 4, far, 100)}, + {CFX_FloatRect(5, middle_y, 5 + w, middle_y + h), + CFX_FloatRect(near, 4, 200, 100)}, + {CFX_FloatRect(middle_x, middle_y, middle_x + w, middle_y + h), + CFX_FloatRect(4, 4, 200, 100)}, }; int index = 0; for (const auto& layout : kCaptionAndIconLayouts) { @@ -2609,19 +2695,23 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, ACaptionAndAnIconEachTakeTheirPart) { const std::optional icon = DrawnIconOf(button.get()); ASSERT_TRUE(icon); ExpectRectNear(expected.icon, icon->plate, 1e-2f); - ExpectRectNear(expected.picture, icon->picture, 1e-2f); + ExpectRectNear(fitted(expected.icon), icon->picture, 1e-2f); const std::optional caption = DrawnCaptionOf(button.get()); ASSERT_TRUE(caption); ExpectRectNear(expected.caption, *caption, 1e-2f); - // The icon first, the caption after it. + ExpectPartsShare(layout.layout, CFX_FloatRect(0, 0, 204, 104), 2, room, + *caption, icon->plate); + // The icon first, the caption after it, clipped to the button inside + // its border. const std::string content = StreamBytes(AppearanceOf(button.get()).Get()); EXPECT_LT(content.find("/FRM Do"), content.find("BT\n")); + EXPECT_NE(std::string::npos, content.find("q\n2 2 200 100 re W n\nBT\n")); // Shown: the picture where it lands, red at its left, and the caption in // the middle of its part and nowhere beside it. const Shown shown(page_.get(), 4); - const CFX_PointF red = RedPointOf(expected.picture); - const CFX_PointF blue = BluePointOf(expected.picture); + const CFX_PointF red = RedPointOf(fitted(expected.icon)); + const CFX_PointF blue = BluePointOf(fitted(expected.icon)); EXPECT_EQ(kRed, shown.At(100 + red.x, 150 + red.y)); EXPECT_EQ(kBlue, shown.At(100 + blue.x, 150 + blue.y)); CFX_FloatRect ink = CaptionInkOf(expected.caption); @@ -2635,9 +2725,10 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, ACaptionAndAnIconEachTakeTheirPart) { } } -// The caption and the icon share the button less the border's width at each -// edge, the width /BS gives whether or not a colour paints it. /MK /IF /FB -// shares the whole button, as it gives an icon alone the whole button. +// The caption and the icon share the button as Acrobat 26 does by the +// border's width, the width /BS gives whether or not a colour paints it. +// /MK /IF /FB gives the icon the whole button but its caption's strip, as it +// gives an icon alone the whole button. TEST_F(EPDFWidgetDrawingEmbedderTest, ACaptionAndAnIconShareWhatTheBorderLeaves) { const FS_RECTF kStands{100, 308, 308, 200}; // 208 by 108 @@ -2645,14 +2736,13 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, const char* name; std::optional border_width; bool fit_to_bounds; - CFX_FloatRect plate; + float border; // the width the rule counts } kCases[] = { // No /BS: a border of 1. - {"no /BS", {}, false, CFX_FloatRect(1, 1, 207, 107)}, - {"no border", 0.0f, false, CFX_FloatRect(0, 0, 208, 108)}, - {"a border of 4", 4.0f, false, CFX_FloatRect(4, 4, 204, 104)}, - {"a border of 4, fitted to the bounds", 4.0f, true, - CFX_FloatRect(0, 0, 208, 108)}, + {"no /BS", {}, false, 1}, + {"no border", 0.0f, false, 0}, + {"a border of 4", 4.0f, false, 4}, + {"a border of 4, fitted to the bounds", 4.0f, true, 4}, }; const unsigned int drawing = AddDrawing(doc_.get()); ASSERT_NE(0u, drawing); @@ -2674,8 +2764,9 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, ASSERT_TRUE(icon); const std::optional caption = DrawnCaptionOf(button.get()); ASSERT_TRUE(caption); - ExpectPartsShare(layout.layout, expected.plate, - CaptionRoomOf(button.get()), *caption, icon->plate); + ExpectPartsShare(layout.layout, CFX_FloatRect(0, 0, 208, 108), + expected.border, CaptionRoomOf(button.get()), *caption, + icon->plate, expected.fit_to_bounds); } } } @@ -2803,7 +2894,7 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, ACaptionAndAnIconTurnWithTheirButton) { ASSERT_TRUE(icon); const std::optional caption = DrawnCaptionOf(button.get()); ASSERT_TRUE(caption); - ExpectPartsShare(layout.layout, expected.frame, + ExpectPartsShare(layout.layout, expected.frame, 0, CaptionRoomOf(button.get()), *caption, icon->plate); buttons.push_back({stands, expected.turn, *icon, *caption}); } @@ -2877,7 +2968,7 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, ASSERT_TRUE(icon); const std::optional caption = DrawnCaptionOf(button.get()); ASSERT_TRUE(caption); - ExpectPartsShare(layout.layout, CFX_FloatRect(1, 1, 101, 51), room, + ExpectPartsShare(layout.layout, CFX_FloatRect(0, 0, 102, 52), 1, room, *caption, icon->plate); // Shown, a page point (x, y) is at (y, x) from the top left. This button // spans 100 to 202 across, and 100 + 60 * index to 152 + 60 * index @@ -3029,7 +3120,7 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, ASSERT_TRUE(icon); const std::optional caption = DrawnCaptionOf(button.get()); ASSERT_TRUE(caption); - ExpectPartsShare(layout.layout, CFX_FloatRect(1, 1, 101, 41), + ExpectPartsShare(layout.layout, CFX_FloatRect(0, 0, 102, 42), 1, CaptionRoomOf(button.get()), *caption, icon->plate); const float bottom = 10 + 50 * layout.layout; const Shown shown(page.get(), 4); @@ -3043,12 +3134,13 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, } } -// A caption that needs more than the button has takes all of it, and the -// icon is not drawn: the rule of PDFium's form filler. The button is then -// drawn as the layout that shows the caption alone draws it. /MK /I still -// names the picture. Over the icon nothing is shared, so both are drawn. -TEST_F(EPDFWidgetDrawingEmbedderTest, - ACaptionTooLargeForTheButtonIsDrawnAlone) { +// When the caption's strip leaves the icon no room, the icon is left out +// and the caption is drawn alone where the rule puts it (AcrobatButtonParts()), +// as Acrobat 26 does: below an icon, in the middle of the room from the +// border's width above the bottom edge to twice the border's width below the +// top edge, not in the middle of the button. /MK /I still names the picture. +// Over the icon nothing is shared, so both are drawn. +TEST_F(EPDFWidgetDrawingEmbedderTest, ACaptionThatLeavesTheIconNoRoomIsAlone) { const unsigned int drawing = AddDrawing(doc_.get()); ASSERT_NE(0u, drawing); const struct { @@ -3057,24 +3149,39 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, float font_size; int layouts[2]; } kCases[] = { - // 100 by 40 inside the border. A line at 48 is higher than 40. + // 104 by 44 with a border of 2: 96 by 36 inside twice the border. A + // line at 48 is higher than that. {"too high", {100, 244, 204, 200}, 48, {kCaptionBelow, kCaptionAbove}}, - // 14 by 100 inside the border. "Go" at 12 is 16 wide. + // 18 by 104: 10 by 96 inside twice the border. "Go" at 12 is wider. {"too wide", {100, 304, 118, 200}, 12, {kCaptionRight, kCaptionLeft}}, + // Acrobat's case: 80 by 30 with a border of 2, beveled (counted 4), + // "Go" at 12. 3 * 4 and a line of 12 leave no room under 22. + {"Acrobat's", {100, 230, 180, 200}, 12, {kCaptionBelow, kCaptionAbove}}, }; for (const auto& expected : kCases) { SCOPED_TRACE(expected.name); ScopedFPDFAnnotation button = NewButton(expected.stands, 2.0f); ASSERT_TRUE(button); - SetCaptionAndIcon(button.get(), drawing, 0, expected.font_size); - const std::string alone = StreamBytes(AppearanceOf(button.get()).Get()); - ASSERT_NE(std::string::npos, alone.find("BT\n")); + float border = 2; + if (std::string(expected.name) == "Acrobat's") { + ASSERT_TRUE( + EPDFAnnot_SetBorderStyle(button.get(), FPDF_ANNOT_BS_BEVELED, 2.0f)); + border = 4; + } + const CFX_FloatRect box(0, 0, expected.stands.right - expected.stands.left, + expected.stands.top - expected.stands.bottom); for (int layout : expected.layouts) { SCOPED_TRACE(layout); SetCaptionAndIcon(button.get(), drawing, layout, expected.font_size); - EXPECT_EQ(alone, StreamBytes(AppearanceOf(button.get()).Get())); EXPECT_EQ(0u, DrawnIconNumber(button.get())); + EXPECT_FALSE(DrawnIconOf(button.get())); EXPECT_EQ(drawing, EPDFAnnot_GetMKIcon(button.get(), EPDF_MK_ICON_I)); + const std::optional caption = DrawnCaptionOf(button.get()); + ASSERT_TRUE(caption); + const ButtonParts parts = AcrobatButtonParts( + layout, box, border, CaptionRoomOf(button.get(), expected.font_size)); + EXPECT_TRUE(parts.icon.IsEmpty()); + ExpectRectNear(parts.caption, *caption, 1e-2f); } SetCaptionAndIcon(button.get(), drawing, kCaptionOver, expected.font_size); EXPECT_EQ(drawing, DrawnIconNumber(button.get())); @@ -3083,56 +3190,57 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, } // A caption whose size is fitted to its room (a font size of 0) takes a -// third of the button, of its height below or above the icon and of its -// width beside it, and is fitted to that third: the rule of PDFium's form -// filler. +// third of the icon's room inside twice the border, of its height below or +// above the icon and of its width beside it, and is fitted to that third; +// the parts are then shared as for any caption (AcrobatButtonParts()). The +// fitted size is one of PDFium's steps, so the caption is no larger than +// its third, and in its middle. TEST_F(EPDFWidgetDrawingEmbedderTest, AFittedCaptionTakesAThirdOfTheButton) { - // 204 by 104 with a border of 2: 200 by 100 inside it, from (2, 2). + // 204 by 104 with a border of 2: the icon's room is 196 by 96 from (4, 4). ScopedFPDFAnnotation button = NewButton({100, 254, 304, 150}, 2.0f); ASSERT_TRUE(button); const unsigned int drawing = AddDrawing(doc_.get()); ASSERT_NE(0u, drawing); - const float third_up = 2 + 100.0f / 3; - const float third_down = 102 - 100.0f / 3; - const float third_along = 2 + 200.0f / 3; - const float third_back = 202 - 200.0f / 3; - const struct { - CFX_FloatRect caption; - CFX_FloatRect icon; - } kExpected[] = { - {CFX_FloatRect(2, 2, 202, third_up), - CFX_FloatRect(2, third_up, 202, 102)}, - {CFX_FloatRect(2, third_down, 202, 102), - CFX_FloatRect(2, 2, 202, third_down)}, - {CFX_FloatRect(third_back, 2, 202, 102), - CFX_FloatRect(2, 2, third_back, 102)}, - {CFX_FloatRect(2, 2, third_along, 102), - CFX_FloatRect(third_along, 2, 202, 102)}, - {CFX_FloatRect(2, 2, 202, 102), CFX_FloatRect(2, 2, 202, 102)}, - }; + const CFX_FloatRect box(0, 0, 204, 104); + const CFX_SizeF thirds(196.0f / 3, 96.0f / 3); int index = 0; for (const auto& layout : kCaptionAndIconLayouts) { SCOPED_TRACE(layout.name); - const auto& expected = kExpected[index++]; SetCaptionAndIcon(button.get(), drawing, layout.layout, 0); EXPECT_EQ(drawing, DrawnIconNumber(button.get())); const std::optional icon = DrawnIconOf(button.get()); ASSERT_TRUE(icon); - ExpectRectNear(expected.icon, icon->plate, 1e-2f); - const std::optional caption = DrawnCaptionOf(button.get()); - ASSERT_TRUE(caption); - ExpectRectNear(expected.caption, *caption, 1e-2f); - // The size the caption is written at fits its part. + // The third: as wide as the room beside the icon, and as high below or + // above it; over the icon, all of the room. + const bool stacked = + layout.layout == kCaptionBelow || layout.layout == kCaptionAbove; + const CFX_SizeF third = layout.layout == kCaptionOver ? CFX_SizeF(196, 96) + : stacked ? CFX_SizeF(196, thirds.height) + : CFX_SizeF(thirds.width, 96); + const ButtonParts parts = AcrobatButtonParts(layout.layout, box, 2, third); + ExpectRectNear(parts.icon, icon->plate, 1e-2f); + // The size the caption is written at fits its third, and the caption + // is in the third's middle. const float size = DrawnCaptionSizeOf(button.get()); EXPECT_GT(size, 0); - const CFX_SizeF room = CaptionRoomOf(button.get(), size); - EXPECT_LE(room.width, caption->Width()); - EXPECT_LE(room.height, caption->Height()); + const std::optional caption = DrawnCaptionOf(button.get()); + ASSERT_TRUE(caption); + constexpr float kWithin = 1e-2f; + EXPECT_GE(caption->left, parts.caption.left - kWithin); + EXPECT_LE(caption->right, parts.caption.right + kWithin); + EXPECT_GE(caption->bottom, parts.caption.bottom - kWithin); + EXPECT_LE(caption->top, parts.caption.top + kWithin); + EXPECT_NEAR(caption->left + caption->right, + parts.caption.left + parts.caption.right, kWithin); + EXPECT_NEAR(caption->bottom + caption->top, + parts.caption.bottom + parts.caption.top, kWithin); const Shown shown(page_.get(), 4); - CFX_FloatRect part = *caption; + CFX_FloatRect part = parts.caption; part.Translate(100, 150); EXPECT_TRUE(shown.HasInkIn(part)); + ++index; } + EXPECT_EQ(5, index); } // The generator can draw a button that shows a caption and an icon in @@ -3177,122 +3285,125 @@ TEST_F(EPDFWidgetDrawingEmbedderTest, ACaptionAndAnIconCanBeDrawnInMemory) { EXPECT_EQ(before, ObjectGraph(doc)); } -// How a button is shared between its caption and its icon is the rule of -// PDFium's own form filler (GetPushButtonAppStream() in -// fpdfsdk/cpdfsdk_appstream.cpp), which draws a button for upstream's -// viewers. Both draw the same seven buttons here, one in each layout, at a -// font size of 12 and at a fitted one: the icon is clipped to the same part -// and lands in the same place, and the caption is written at the same size -// from the same point. -TEST_F(EPDFWidgetDrawingEmbedderTest, AButtonIsSharedAsTheFormFillerSharesIt) { +// How a button is shared between its caption and its icon is Acrobat 26's +// rule, read from 244 buttons Acrobat drew itself (ten borders, three sizes, +// four layouts, a caption at 12 and at a fitted size). At a fixed size the +// button's size changes nothing and the border decides everything: call b +// its width, counted twice for beveled and inset. Acrobat fits the icon 2b +// in from every edge. Right of the icon the caption ends 1.5b from the +// right edge and starts 1.5b from the icon's part. Below the icon, the +// icon's part starts 3b and the caption's line up, and the line starts 2b +// up. Left of and above the icon (measured with a border of 1) the caption +// is 2.5b from its edge and 0.5b from the icon's part. Without a border +// everything touches. With a border of 4 on a button 30 high, the caption +// below leaves the icon no room, and Acrobat leaves the icon out. The +// caption's line here is the font's own: Acrobat's Helvetica line is 13.63 +// high at 12 with its baseline 3 up, its font's measure, not the layout's. +TEST_F(EPDFWidgetDrawingEmbedderTest, AButtonIsSharedAsAcrobatSharesIt) { constexpr float kWithin = 1e-2f; - // A border and a background that show, for the files kept to look at. - auto paint = [](FPDF_ANNOTATION button) { - ASSERT_TRUE(EPDFAnnot_SetMKColor(button, EPDF_MK_COLOR_BC, 0, 153, 0)); - ASSERT_TRUE(EPDFAnnot_SetMKColor(button, EPDF_MK_COLOR_BG, 255, 255, 204)); + const struct { + const char* name; + float width; + FPDF_ANNOT_BORDER_STYLE style; + float b; + } kBorders[] = { + {"none", 0, FPDF_ANNOT_BS_SOLID, 0}, + {"solid 1", 1, FPDF_ANNOT_BS_SOLID, 1}, + {"solid 2", 2, FPDF_ANNOT_BS_SOLID, 2}, + {"solid 3", 3, FPDF_ANNOT_BS_SOLID, 3}, + {"beveled 1", 1, FPDF_ANNOT_BS_BEVELED, 2}, + {"beveled 2", 2, FPDF_ANNOT_BS_BEVELED, 4}, + {"inset 1", 1, FPDF_ANNOT_BS_INSET, 2}, + {"inset 2", 2, FPDF_ANNOT_BS_INSET, 4}, + {"dashed 1", 1, FPDF_ANNOT_BS_DASHED, 1}, + {"underline 1", 1, FPDF_ANNOT_BS_UNDERLINE, 1}, }; - for (int font_size : {12, 0}) { - SCOPED_TRACE(font_size); - const std::string bytes = ForeignButtonsPdf( - /*with_fonts=*/true, /*with_appearances=*/false, font_size); - - // The form filler's, in a document of its own. - std::vector theirs; - std::string theirs_saved; - { - ScopedFPDFDocument document( - FPDF_LoadMemDocument(bytes.data(), bytes.size(), nullptr)); - ASSERT_TRUE(document); - FPDF_FORMHANDLE form = SetupFormFillEnvironment( - document.get(), JavaScriptOption::kDisableJavaScript); - ASSERT_TRUE(form); + const CFX_SizeF kSizes[] = {{80, 30}, {160, 70}, {300, 120}}; + const unsigned int drawing = AddDrawing(doc_.get()); + ASSERT_NE(0u, drawing); + for (const auto& border : kBorders) { + SCOPED_TRACE(border.name); + const float b = border.b; + for (const CFX_SizeF& size : kSizes) { + SCOPED_TRACE(size.width); + const float w = size.width; + const float h = size.height; + auto new_button = [&]() { + ScopedFPDFAnnotation button = NewButton({10, 10 + h, 10 + w, 10}); + EXPECT_TRUE(button); + EXPECT_TRUE( + EPDFAnnot_SetBorderStyle(button.get(), border.style, border.width)); + EXPECT_TRUE( + EPDFAnnot_SetMKColor(button.get(), EPDF_MK_COLOR_BC, 0, 0, 0)); + return button; + }; + + // The icon alone: 2b in from every edge. { - ScopedFPDFPage page(FPDF_LoadPage(document.get(), 0)); - ASSERT_TRUE(page); - FORM_OnAfterLoadPage(page.get(), form); - CPDFSDK_PageView* view = - CPDFSDKFormFillEnvironmentFromFPDFFormHandle(form) - ->GetOrCreatePageView(IPDFPageFromFPDFPage(page.get())); - ASSERT_TRUE(view); - for (int layout = 0; layout <= 6; ++layout) { - ScopedFPDFAnnotation button(FPDFPage_GetAnnot(page.get(), layout)); - ASSERT_TRUE(button); - paint(button.get()); - CPDFSDK_Widget* widget = - ToCPDFSDKWidget(view->GetAnnotByDict(DictOf(button.get()))); - ASSERT_TRUE(widget); - widget->ResetAppearance(std::nullopt, - CPDFSDK_Widget::kValueUnchanged); - RetainPtr appearance = AppearanceOf(button.get()); - ASSERT_TRUE(appearance); - theirs.push_back(ReadButtonContent(StreamBytes(appearance.Get()))); - } - FORM_OnBeforeClosePage(page.get(), form); + ScopedFPDFAnnotation button = new_button(); + SetIcon(button.get(), drawing); + const std::optional icon = DrawnIconOf(button.get()); + ASSERT_TRUE(icon); + ExpectRectNear(CFX_FloatRect(2 * b, 2 * b, w - 2 * b, h - 2 * b), + icon->plate, kWithin); } - FPDFDOC_ExitFormFillEnvironment(form); - theirs_saved = SavedBytes(document.get()); - } - - // Ours. - embedpdf_test::ScopedTestDocument document( - embedpdf_test::LoadMemDocumentForTest(bytes.data(), bytes.size(), - nullptr)); - ASSERT_TRUE(document); - { - ScopedFPDFPage page(FPDF_LoadPage(document.get(), 0)); - ASSERT_TRUE(page); - for (int layout = 0; layout <= 6; ++layout) { + for (int layout : + {kCaptionBelow, kCaptionAbove, kCaptionRight, kCaptionLeft}) { SCOPED_TRACE(layout); - ScopedFPDFAnnotation button(FPDFPage_GetAnnot(page.get(), layout)); - ASSERT_TRUE(button); - paint(button.get()); - ASSERT_TRUE(EPDFAnnot_GenerateFormFieldAP(button.get())); - const ButtonContent ours = - ReadButtonContent(StreamBytes(AppearanceOf(button.get()).Get())); - const ButtonContent& their = theirs[layout]; - - const bool shows_icon = layout != 0; - ASSERT_EQ(shows_icon, their.picture.has_value()); - ASSERT_EQ(shows_icon, ours.picture.has_value()); - if (shows_icon) { - ASSERT_TRUE(their.icon_part); - ASSERT_TRUE(ours.icon_part); - ExpectRectNear(*their.icon_part, *ours.icon_part, kWithin); - ExpectRectNear(*their.picture, *ours.picture, kWithin); + ScopedFPDFAnnotation button = new_button(); + SetCaptionAndIcon(button.get(), drawing, layout); + const CFX_SizeF room = CaptionRoomOf(button.get()); + const std::optional caption = + DrawnCaptionOf(button.get()); + ASSERT_TRUE(caption); + const std::optional icon = DrawnIconOf(button.get()); + const bool stacked = layout == kCaptionBelow || layout == kCaptionAbove; + if (b == 4 && h == 30 && stacked) { + // No room: the caption alone, in the middle of the room from b up + // (below) or 2b down (above) to the far side of the icon's room. + EXPECT_FALSE(icon); + EXPECT_EQ(0u, DrawnIconNumber(button.get())); + const float middle = layout == kCaptionBelow + ? (b + (h - 2 * b)) / 2 + : (2 * b + (h - 2 * b)) / 2; + EXPECT_NEAR(middle, (caption->bottom + caption->top) / 2, kWithin); + continue; } - const bool shows_caption = layout != 1; - ASSERT_EQ(shows_caption, their.caption_start.has_value()); - ASSERT_EQ(shows_caption, ours.caption_start.has_value()); - if (shows_caption) { - ASSERT_TRUE(their.caption_size); - ASSERT_TRUE(ours.caption_size); - EXPECT_EQ(*their.caption_size, *ours.caption_size); - EXPECT_NEAR(their.caption_start->x, ours.caption_start->x, kWithin); - EXPECT_NEAR(their.caption_start->y, ours.caption_start->y, kWithin); + ASSERT_TRUE(icon); + const CFX_FloatRect& part = icon->plate; + switch (layout) { + case kCaptionBelow: + EXPECT_NEAR(3 * b + room.height, part.bottom, kWithin); + EXPECT_NEAR(2 * b, caption->bottom, kWithin); + EXPECT_NEAR(h - 2 * b, part.top, kWithin); + break; + case kCaptionAbove: + EXPECT_NEAR(h - 3 * b - room.height, part.top, kWithin); + EXPECT_NEAR(h - 2.5f * b, caption->top, kWithin); + EXPECT_NEAR(2 * b, part.bottom, kWithin); + break; + case kCaptionRight: + EXPECT_NEAR(w - 1.5f * b, caption->right, kWithin); + EXPECT_NEAR(1.5f * b, caption->left - part.right, kWithin); + EXPECT_NEAR(2 * b, part.left, kWithin); + break; + case kCaptionLeft: + EXPECT_NEAR(2.5f * b, caption->left, kWithin); + EXPECT_NEAR(0.5f * b, part.left - caption->right, kWithin); + EXPECT_NEAR(w - 2 * b, part.right, kWithin); + break; + } + if (stacked) { + EXPECT_NEAR(2 * b, part.left, kWithin); + EXPECT_NEAR(w - 2 * b, part.right, kWithin); + EXPECT_NEAR(w, caption->left + caption->right, kWithin); + } else { + EXPECT_NEAR(2 * b, part.bottom, kWithin); + EXPECT_NEAR(h - 2 * b, part.top, kWithin); + EXPECT_NEAR(h, caption->bottom + caption->top, kWithin); } } } - if (font_size == 12) { - KeepSample(theirs_saved, "button-layouts-drawn-by-pdfium-form-filler"); - KeepSample(SavedBytes(document.get()), "button-layouts-drawn-by-us"); - // And the same buttons without an appearance, for a viewer that draws - // its own. - ScopedFPDFDocument undrawn( - FPDF_LoadMemDocument(bytes.data(), bytes.size(), nullptr)); - ASSERT_TRUE(undrawn); - ScopedFPDFPage page(FPDF_LoadPage(undrawn.get(), 0)); - ASSERT_TRUE(page); - for (int layout = 0; layout <= 6; ++layout) { - ScopedFPDFAnnotation button(FPDFPage_GetAnnot(page.get(), layout)); - ASSERT_TRUE(button); - paint(button.get()); - } - CPDFDocumentFromFPDFDocument(undrawn.get()) - ->GetMutableRoot() - ->GetMutableDictFor("AcroForm") - ->SetNewFor("NeedAppearances", true); - KeepSample(SavedBytes(undrawn.get()), "button-layouts-not-drawn"); - } } } diff --git a/fpdfsdk/epdf_widget_text_size_embeddertest.cpp b/fpdfsdk/epdf_widget_text_size_embeddertest.cpp new file mode 100644 index 0000000000..a359d9e3c5 --- /dev/null +++ b/fpdfsdk/epdf_widget_text_size_embeddertest.cpp @@ -0,0 +1,358 @@ +// Copyright 2026 CloudPDF LTD +// SPDX-License-Identifier: Apache-2.0 + +// A field's automatic text size (a /DA size of 0) and a check box's mark, as +// the appearance generator draws them for EPDFAnnot_GenerateFormFieldAP(). +// Acrobat 26 fits a field's text exactly, where PDFium stepped down a fixed +// ladder of sizes, and the numbers here are Acrobat's own wherever the +// field's width decides the size: they were read from fields Acrobat drew +// itself, each with a border of 1 (Nov 26 2026). + +#include +#include +#include +#include +#include +#include + +#include "core/fpdfapi/font/cpdf_font.h" +#include "core/fpdfapi/page/cpdf_annotcontext.h" +#include "core/fpdfapi/page/cpdf_docpagedata.h" +#include "core/fpdfapi/parser/cpdf_dictionary.h" +#include "core/fpdfapi/parser/cpdf_document.h" +#include "core/fpdfapi/parser/cpdf_stream.h" +#include "core/fpdfapi/parser/cpdf_stream_acc.h" +#include "core/fpdfdoc/cpdf_annot.h" +#include "core/fxcrt/fx_coordinates.h" +#include "fpdfsdk/cpdfsdk_helpers.h" +#include "fpdfsdk/epdf_edit_test_util.h" +#include "public/cpp/fpdf_scopers.h" +#include "public/epdf_annot.h" +#include "public/fpdf_annot.h" +#include "public/fpdfview.h" +#include "testing/embedder_test.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +// The sizes of CPVT's ladder, which a fitted size no longer snaps to. +constexpr std::array kLadder = { + 4, 6, 8, 9, 10, 12, 14, 18, 20, 25, 30, 35, 40, + 45, 50, 55, 60, 70, 80, 90, 100, 110, 120, 130, 144}; + +bool OnTheLadder(float size) { + return std::any_of(kLadder.begin(), kLadder.end(), [size](float step) { + return std::fabs(step - size) < 1e-3f; + }); +} + +// A file of one page whose widgets are `widgets` (each a widget and its +// field in one dictionary, without /Type, /Subtype and /P), in that order, +// every one with a black border 1 wide and the form's /DA: Helvetica at an +// automatic size. Object 4 is Helvetica and 5 ZapfDingbats. +std::string FieldsPdf(const std::vector& widgets) { + std::string refs; + for (size_t i = 0; i < widgets.size(); ++i) { + refs += std::to_string(6 + i) + " 0 R "; + } + std::vector objects = { + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [" + refs + + "] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 4 0 R /ZaDb 5 0 R " + ">> >> >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [" + refs + + "] >>", + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding " + "/WinAnsiEncoding >>", + "<< /Type /Font /Subtype /Type1 /BaseFont /ZapfDingbats >>", + }; + for (const std::string& widget : widgets) { + objects.push_back( + "<< /Type /Annot /Subtype /Widget /P 3 0 R /F 4 /BS << /W 1 /S /S >> " + "/MK << /BC [0 0 0] >> /DA (/Helv 0 Tf 0 g) " + + widget + " >>"); + } + return MakePdf(objects); +} + +// A field's /Rect, `width` by `height` at the lower left of the page. +std::string RectOf(float width, float height) { + return "/Rect [10 10 " + std::to_string(10 + width) + " " + + std::to_string(10 + height) + "]"; +} + +const CPDF_Dictionary* DictOf(FPDF_ANNOTATION annot) { + return CPDFAnnotContextFromFPDFAnnotation(annot)->GetAnnotDict(); +} + +// The bytes of a stream, filters applied. +std::string StreamBytes(const CPDF_Stream* stream) { + auto acc = pdfium::MakeRetain(pdfium::WrapRetain(stream)); + acc->LoadAllDataFiltered(); + const auto span = acc->GetSpan(); + return std::string(span.begin(), span.end()); +} + +// The normal appearance an annotation shows: its stream, or the state /AS +// names. +RetainPtr AppearanceOf(FPDF_ANNOTATION annot) { + return GetAnnotAP(DictOf(annot), CPDF_Annot::AppearanceMode::kNormal); +} + +// The size an appearance writes its text at: the number before its first +// Tf, or nothing. +std::optional DrawnSizeOf(const std::string& content) { + const size_t set = content.find(" Tf"); + if (set == std::string::npos) { + return std::nullopt; + } + const size_t start = content.rfind(' ', set - 1); + return strtof(content.c_str() + (start == std::string::npos ? 0 : start), + nullptr); +} + +// The font the appearance writes its text in: the first one its resources +// name. +RetainPtr FontOf(FPDF_ANNOTATION annot) { + RetainPtr appearance = AppearanceOf(annot); + RetainPtr resources = + appearance ? appearance->GetDict()->GetDictFor("Resources") : nullptr; + RetainPtr fonts = + resources ? resources->GetDictFor("Font") : nullptr; + if (!fonts || fonts->size() == 0) { + return nullptr; + } + RetainPtr dict; + { + CPDF_DictionaryLocker locker(fonts); + dict = ToDictionary(locker.begin()->second->GetDirect()); + } + CPDF_Document* doc = + CPDFAnnotContextFromFPDFAnnotation(annot)->GetPage()->GetDocument(); + return CPDF_DocPageData::FromDocument(doc)->GetFont( + pdfium::WrapRetain(const_cast(dict.Get()))); +} + +// How wide `text` is at `size` in `font`, in points. +float WidthOf(CPDF_Font* font, const char* text, float size) { + return font->GetStringWidth(text) * size / 1000; +} + +// The box every point of the paths in `content` from `from` on reaches: +// the numbers before each m, l and c. +CFX_FloatRect PathBoxOf(const std::string& content, size_t from) { + CFX_FloatRect box(1e6f, 1e6f, -1e6f, -1e6f); + std::vector numbers; + size_t at = from; + while (at < content.size()) { + while (at < content.size() && (content[at] == ' ' || content[at] == '\n')) { + ++at; + } + size_t end = at; + while (end < content.size() && content[end] != ' ' && + content[end] != '\n') { + ++end; + } + const std::string token = content.substr(at, end - at); + at = end; + if (token.empty()) { + continue; + } + if (token == "m" || token == "l" || token == "c") { + for (size_t i = 0; i + 1 < numbers.size(); i += 2) { + box.left = std::min(box.left, numbers[i]); + box.right = std::max(box.right, numbers[i]); + box.bottom = std::min(box.bottom, numbers[i + 1]); + box.top = std::max(box.top, numbers[i + 1]); + } + } + char* number_end = nullptr; + const float number = strtof(token.c_str(), &number_end); + if (number_end != token.c_str() && *number_end == '\0') { + numbers.push_back(number); + } else { + numbers.clear(); + } + } + return box; +} + +class EPDFWidgetTextSizeEmbedderTest : public EmbedderTest { + protected: + // Opens `widgets` (FieldsPdf()) and has the generator draw each. + void DrawFields(const std::vector& widgets) { + bytes_ = FieldsPdf(widgets); + doc_.reset(FPDF_LoadMemDocument(bytes_.data(), bytes_.size(), nullptr)); + ASSERT_TRUE(doc_); + page_.reset(FPDF_LoadPage(doc_.get(), 0)); + ASSERT_TRUE(page_); + ASSERT_EQ(static_cast(widgets.size()), + FPDFPage_GetAnnotCount(page_.get())); + for (size_t i = 0; i < widgets.size(); ++i) { + ScopedFPDFAnnotation widget( + FPDFPage_GetAnnot(page_.get(), static_cast(i))); + ASSERT_TRUE(widget); + ASSERT_TRUE(EPDFAnnot_GenerateFormFieldAP(widget.get())); + } + } + + ScopedFPDFAnnotation Widget(int index) { + return ScopedFPDFAnnotation(FPDFPage_GetAnnot(page_.get(), index)); + } + + void TearDown() override { + page_.reset(); + doc_.reset(); + EmbedderTest::TearDown(); + } + + std::string bytes_; + ScopedFPDFDocument doc_; + ScopedFPDFPage page_; +}; + +} // namespace + +// A value too long for its field shrinks until it fills the field's width +// inside twice the border at each side, whatever the field's height: 220 +// wide leaves 216, and Acrobat's Helvetica size there is 8.679. +TEST_F(EPDFWidgetTextSizeEmbedderTest, ALongValueFillsTheWidth) { + constexpr char kLong[] = + "The quick brown fox jumps over the lazy dog, twice over"; + const float kHeights[] = {14, 20, 30, 48}; + std::vector widgets; + for (float height : kHeights) { + widgets.push_back("/FT /Tx /T (long" + std::to_string(widgets.size()) + + ") /V (" + kLong + ") " + RectOf(220, height)); + } + DrawFields(widgets); + for (size_t i = 0; i < std::size(kHeights); ++i) { + SCOPED_TRACE(kHeights[i]); + ScopedFPDFAnnotation widget = Widget(static_cast(i)); + const std::optional size = + DrawnSizeOf(StreamBytes(AppearanceOf(widget.get()).Get())); + ASSERT_TRUE(size); + EXPECT_FALSE(OnTheLadder(*size)); + RetainPtr font = FontOf(widget.get()); + ASSERT_TRUE(font); + // To a thousandth of a point: the line is up to 0.03 short of the room. + EXPECT_NEAR(216, WidthOf(font.Get(), kLong, *size), 0.03f); + // The tests' stand-in for Helvetica is 0.2% narrower than Acrobat's. + EXPECT_NEAR(8.679f, *size, 0.02f); + } +} + +// A short value is as large as the field's height lets its line be: the +// font's ascent and descent fill the field inside its border, to a +// thousandth of a point, where PDFium stepped down to the size below +// (14 pt high: 10, where it fits 10.7). +TEST_F(EPDFWidgetTextSizeEmbedderTest, AShortValueFillsTheHeight) { + const float kHeights[] = {14, 20, 30, 48}; + std::vector widgets; + for (float height : kHeights) { + widgets.push_back("/FT /Tx /T (short" + std::to_string(widgets.size()) + + ") /V (Hello world) " + RectOf(220, height)); + } + DrawFields(widgets); + for (size_t i = 0; i < std::size(kHeights); ++i) { + SCOPED_TRACE(kHeights[i]); + ScopedFPDFAnnotation widget = Widget(static_cast(i)); + const std::optional size = + DrawnSizeOf(StreamBytes(AppearanceOf(widget.get()).Get())); + ASSERT_TRUE(size); + RetainPtr font = FontOf(widget.get()); + ASSERT_TRUE(font); + const float line = + (font->GetTypeAscent() - font->GetTypeDescent()) * *size / 1000; + EXPECT_NEAR(kHeights[i] - 2, line, 0.01f); + EXPECT_LT(WidthOf(font.Get(), "Hello world", *size), 216); + } +} + +// A field of several lines is at most 12, as in Acrobat, and smaller until +// the wrapped text fits: 220 by 80 holds the paragraph at 12, 220 by 40 at +// a size between two of PDFium's steps (Acrobat: 12 and 8.25). +TEST_F(EPDFWidgetTextSizeEmbedderTest, AFieldOfSeveralLinesIsAtMostTwelve) { + constexpr char kParagraph[] = + "Automatic text size fits this paragraph into the box. A longer " + "paragraph wraps onto more lines, and the size goes down until every " + "line fits inside the border of the field."; + const float kBoxes[][2] = {{220, 80}, {220, 40}}; + std::vector widgets; + for (const auto& box : kBoxes) { + widgets.push_back("/FT /Tx /Ff 4096 /T (lines" + + std::to_string(widgets.size()) + ") /V (" + kParagraph + + ") " + RectOf(box[0], box[1])); + } + DrawFields(widgets); + const std::optional roomy = + DrawnSizeOf(StreamBytes(AppearanceOf(Widget(0).get()).Get())); + ASSERT_TRUE(roomy); + EXPECT_EQ(12, *roomy); + { + const std::optional size = + DrawnSizeOf(StreamBytes(AppearanceOf(Widget(1).get()).Get())); + ASSERT_TRUE(size); + EXPECT_LT(*size, 12); + EXPECT_GT(*size, 4); + EXPECT_FALSE(OnTheLadder(*size)); + } +} + +// A list box's automatic size fits its widest option to its width inside +// twice the border at each side, at most 12: Acrobat draws the options of +// a list 120 wide at 8.199, and of one 200 wide at 12. Every option is +// drawn at that size. +TEST_F(EPDFWidgetTextSizeEmbedderTest, AListBoxFitsItsWidestOption) { + constexpr char kOptions[] = + "/Opt [(Option one) (A much longer option label here) (Three) (Four) " + "(Five) (Six)] /I [2] /V (Three)"; + DrawFields({ + std::string("/FT /Ch /T (narrow) ") + kOptions + " " + RectOf(120, 60), + std::string("/FT /Ch /T (wide) ") + kOptions + " " + RectOf(200, 40), + }); + const std::string narrow = StreamBytes(AppearanceOf(Widget(0).get()).Get()); + const std::optional size = DrawnSizeOf(narrow); + ASSERT_TRUE(size); + // The tests' stand-in for Helvetica is 0.2% narrower than Acrobat's. + EXPECT_NEAR(8.199f, *size, 0.02f); + RetainPtr font = FontOf(Widget(0).get()); + ASSERT_TRUE(font); + EXPECT_NEAR(116, + WidthOf(font.Get(), "A much longer option label here", *size), + 0.03f); + EXPECT_NE(std::string::npos, narrow.find("Six")); + const std::optional wide = + DrawnSizeOf(StreamBytes(AppearanceOf(Widget(1).get()).Get())); + ASSERT_TRUE(wide); + EXPECT_EQ(12, *wide); +} + +// A check box's check is as large as Acrobat's: ZapfDingbats' check mark at +// the size whose font box (0.963 of the size high) fills the box inside its +// border less the border's width at each side, so the mark is 0.719 / 0.963 +// of the box less 4 high with a border of 1 (Acrobat: 11.92 in a box of 20, +// 34.32 in one of 50), in the middle. +TEST_F(EPDFWidgetTextSizeEmbedderTest, ACheckIsAsLargeAsAcrobats) { + const float kSides[] = {10, 14, 20, 30, 50}; + std::vector widgets; + for (float side : kSides) { + widgets.push_back("/FT /Btn /T (check" + std::to_string(widgets.size()) + + ") /V /Yes /AS /Yes /MK << /BC [0 0 0] /CA (4) >> " + + RectOf(side, side)); + } + DrawFields(widgets); + for (size_t i = 0; i < std::size(kSides); ++i) { + const float side = kSides[i]; + SCOPED_TRACE(side); + ScopedFPDFAnnotation widget = Widget(static_cast(i)); + const std::string checked = StreamBytes(AppearanceOf(widget.get()).Get()); + // The check comes after the box's own block. + const size_t box_end = checked.find("Q\n"); + ASSERT_NE(std::string::npos, box_end); + const CFX_FloatRect mark = PathBoxOf(checked, box_end + 2); + EXPECT_NEAR(0.719f / 0.963f * (side - 4), mark.Height(), 1e-2f); + EXPECT_NEAR(side, mark.left + mark.right, 1e-2f); + EXPECT_NEAR(side, mark.bottom + mark.top, 1e-2f); + } +} diff --git a/testing/embedpdf_layer_mode_writers.txt b/testing/embedpdf_layer_mode_writers.txt index 474b5cf50b..9948ce4447 100644 --- a/testing/embedpdf_layer_mode_writers.txt +++ b/testing/embedpdf_layer_mode_writers.txt @@ -404,7 +404,7 @@ EPDFViewEmbedderTest.EPDFGetPageRotateByIndex 2 EPDFViewEmbedderTest.EPDFGetPageTabOrderByIndex 2 EPDFViewEmbedderTest.EPDFGetPageUserUnitByIndex 1 EPDFViewEmbedderTest.ImageOfAnotherDocumentDraws 4 -EPDFWidgetDrawingEmbedderTest.AButtonIsSharedAsTheFormFillerSharesIt 14 +EPDFWidgetDrawingEmbedderTest.AButtonIsSharedAsAcrobatSharesIt 607 EPDFWidgetDrawingEmbedderTest.AButtonWhoseCaptionCannotBeDrawnIsLeftAsItWas 5 EPDFWidgetDrawingEmbedderTest.AButtonWithoutAnIconDrawsItsCaptionAlone 17 EPDFWidgetDrawingEmbedderTest.ACaptionAndAnIconCanBeDrawnInMemory 3 @@ -412,7 +412,7 @@ EPDFWidgetDrawingEmbedderTest.ACaptionAndAnIconEachTakeTheirPart 16 EPDFWidgetDrawingEmbedderTest.ACaptionAndAnIconReadUprightOnATurnedPage 27 EPDFWidgetDrawingEmbedderTest.ACaptionAndAnIconShareWhatTheBorderLeaves 87 EPDFWidgetDrawingEmbedderTest.ACaptionAndAnIconTurnWithTheirButton 112 -EPDFWidgetDrawingEmbedderTest.ACaptionTooLargeForTheButtonIsDrawnAlone 21 +EPDFWidgetDrawingEmbedderTest.ACaptionThatLeavesTheIconNoRoomIsAlone 25 EPDFWidgetDrawingEmbedderTest.ACaptionWhoseFontIsMissingIsStillDrawnBesideItsIcon 12 EPDFWidgetDrawingEmbedderTest.AClearedIconThatWasTheAppearanceIsNotWrittenInto 70 EPDFWidgetDrawingEmbedderTest.AClearedPictureIsInNoFullSave 22