Skip to content

Wrong bbox in location for vertical font#708

Open
Vladimir-Burshnev wants to merge 2 commits into
integrationfrom
vertical-font-support
Open

Wrong bbox in location for vertical font#708
Vladimir-Burshnev wants to merge 2 commits into
integrationfrom
vertical-font-support

Conversation

@Vladimir-Burshnev

@Vladimir-Burshnev Vladimir-Burshnev commented Jul 14, 2026

Copy link
Copy Markdown

Closes: https://trello.com/c/SCBNY4Sg
pdf.js PR: veraPDF/pdf.js#30
veraPDF-validation PR: veraPDF/veraPDF-validation#735

Summary by CodeRabbit

  • New Features

    • Added support for reading vertical metrics from CID font dictionaries.
    • Added detection of vertical writing modes for CID fonts.
    • Added per-character vertical width lookup with configurable default fallback metrics.
    • Improved handling of CID font vertical metric ranges and individual character mappings.
  • Bug Fixes

    • Improved validation and error reporting for malformed CID font width data.

@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@MaximPlusov, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 50 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: aa3f6d2f-41bc-4166-a6de-9ffb8e3a1509

📥 Commits

Reviewing files that changed from the base of the PR and between 2db26a8 and 8870bc3.

📒 Files selected for processing (2)
  • src/main/java/org/verapdf/pd/font/CIDW2Array.java
  • src/main/java/org/verapdf/pd/font/CIDWArray.java
📝 Walkthrough

Walkthrough

This PR adds vertical metrics support for CID fonts: new classes CIDVerticalMetrics, CIDW2Array, and CIDW2ArrayRange parse and expose W2/DW2 vertical width data, PDCIDFont gains isVertical(), getVerticalWidth(), and getDefaultVMetrics() APIs, and CIDWArray's null handling and log messages are corrected.

Changes

Vertical Metrics for CID Fonts

Layer / File(s) Summary
Vertical metrics data model
src/main/java/org/verapdf/pd/font/CIDVerticalMetrics.java, src/main/java/org/verapdf/pd/font/CIDW2ArrayRange.java
New immutable classes storing displacement/position vector components and CID range bounds with containment and displacement accessors.
W2 array parsing and displacement lookup
src/main/java/org/verapdf/pd/font/CIDW2Array.java
Parses the W2 COSArray into explicit single mappings and CID ranges, extracting vertical metrics per entry, and resolves displacement per CID via lookup or range scan.
PDCIDFont vertical width integration
src/main/java/org/verapdf/pd/font/PDCIDFont.java
Adds isVertical(), getVerticalWidth(int), and getDefaultVMetrics(), caching a CIDW2Array and falling back to default vertical width derived from DW2 or a constant.
CIDWArray null handling and log message fixes
src/main/java/org/verapdf/pd/font/CIDWArray.java
Treats cidBegin as nullable Long with explicit null checks, standardizes invalid W-array log messages, and unifies the SEVERE log message text.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant PDCIDFont
  participant CIDW2Array
  participant CIDW2ArrayRange

  PDCIDFont->>CIDW2Array: new CIDW2Array(W2 array)
  CIDW2Array->>CIDW2Array: parse into singleMappings and ranges
  PDCIDFont->>CIDW2Array: getVerticalWidth(code) -> getDisplacement(cid)
  CIDW2Array->>CIDW2Array: check singleMappings
  CIDW2Array->>CIDW2ArrayRange: contains(cid)?
  CIDW2ArrayRange-->>CIDW2Array: displacement or none
  CIDW2Array-->>PDCIDFont: displacement or null
  PDCIDFont->>PDCIDFont: fallback to getDefaultVMetrics() if null
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title matches the PR’s main goal of fixing incorrect bounding boxes for vertical fonts.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch vertical-font-support

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/main/java/org/verapdf/pd/font/PDCIDFont.java (2)

146-157: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Cache the absence of W2 to avoid repeated lookups.

If the W2 array is missing or invalid, this.verticalMetrics remains null. As a result, every subsequent call to getVerticalWidth() will repeat the dictionary.getKey(ASAtom.W2) lookup. Consider caching the absence of the W2 array (e.g., by assigning a singleton empty CIDW2Array or using a boolean flag) to avoid redundant dictionary lookups per character.

Note: getWidth() exhibits the exact same pattern for the W array, so this optimization could be applied to both.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main/java/org/verapdf/pd/font/PDCIDFont.java` around lines 146 - 157,
Update getVerticalWidth so missing or invalid W2 data is cached instead of
leaving verticalMetrics null; use the existing CIDW2Array mechanism or a
dedicated flag, while preserving the default width result. Apply the same
absence-caching optimization to getWidth for the W array if it has the
equivalent lazy lookup pattern.

175-186: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Cache default vertical metrics and fix indentation.

getDefaultVMetrics() performs dictionary lookups and potentially allocates new Double[2] on every call. Since it is invoked by getVerticalWidth() per character, this can introduce a significant performance overhead. Consider caching the parsed DW2 metrics during initialization, similar to what is done for verticalMetrics.

Additionally:

  • Returning the mutable static array DEFAULT_CID_FONT_VERTICAL_WIDTH as a fallback risks accidental global state corruption if a downstream caller modifies the returned array. Caching a read-only or cloned copy can prevent this.
  • Lines 179, 181, and 183 inconsistently use tabs for indentation instead of spaces.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main/java/org/verapdf/pd/font/PDCIDFont.java` around lines 175 - 186,
Cache the parsed DW2 metrics during PDCIDFont initialization and have
getDefaultVMetrics() reuse that cached value instead of repeating dictionary
lookups and allocations. Ensure fallback results do not expose the mutable
DEFAULT_CID_FONT_VERTICAL_WIDTH array by returning a safe immutable or cloned
representation, while preserving the existing default-metrics behavior.
Normalize the indentation of the affected assignments and null checks to spaces.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/main/java/org/verapdf/pd/font/CIDW2Array.java`:
- Line 41: Update the logger declaration in CIDW2Array to use CIDW2Array.class,
then review the invalid W2-entry logging sites in the relevant methods and
change Level.FINE to Level.SEVERE if these errors should follow the PR’s unified
severity; keep the severity unchanged only if the existing behavior is
explicitly intentional.

In `@src/main/java/org/verapdf/pd/font/CIDWArray.java`:
- Around line 57-59: Update the cidBegin null-check in CIDWArray parsing to
return immediately after logging the invalid W array, matching the existing
width == null handling. This must prevent subsequent cidBegin.intValue() calls
and abort parsing before the token sequence becomes desynchronized.

---

Nitpick comments:
In `@src/main/java/org/verapdf/pd/font/PDCIDFont.java`:
- Around line 146-157: Update getVerticalWidth so missing or invalid W2 data is
cached instead of leaving verticalMetrics null; use the existing CIDW2Array
mechanism or a dedicated flag, while preserving the default width result. Apply
the same absence-caching optimization to getWidth for the W array if it has the
equivalent lazy lookup pattern.
- Around line 175-186: Cache the parsed DW2 metrics during PDCIDFont
initialization and have getDefaultVMetrics() reuse that cached value instead of
repeating dictionary lookups and allocations. Ensure fallback results do not
expose the mutable DEFAULT_CID_FONT_VERTICAL_WIDTH array by returning a safe
immutable or cloned representation, while preserving the existing
default-metrics behavior. Normalize the indentation of the affected assignments
and null checks to spaces.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c8dcd7ac-10fd-405e-969e-673d8cf832fa

📥 Commits

Reviewing files that changed from the base of the PR and between 57633dc and 2db26a8.

📒 Files selected for processing (5)
  • src/main/java/org/verapdf/pd/font/CIDVerticalMetrics.java
  • src/main/java/org/verapdf/pd/font/CIDW2Array.java
  • src/main/java/org/verapdf/pd/font/CIDW2ArrayRange.java
  • src/main/java/org/verapdf/pd/font/CIDWArray.java
  • src/main/java/org/verapdf/pd/font/PDCIDFont.java

*/
public class CIDW2Array {

private static final Logger LOGGER = Logger.getLogger(CIDWArray.class.getCanonicalName());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Fix logger initialization and verify the log level.

The logger is incorrectly initialized with CIDWArray.class instead of CIDW2Array.class.

Additionally, the PR objective mentions unifying the SEVERE log message for invalid W array entries. Please verify if the use of Level.FINE for W2 array invalidity errors (e.g., at lines 58, 66, and 104) is intentional, or if it should also be Level.SEVERE for consistency.

♻️ Proposed fix
-    private static final Logger LOGGER = Logger.getLogger(CIDWArray.class.getCanonicalName());
+    private static final Logger LOGGER = Logger.getLogger(CIDW2Array.class.getCanonicalName());
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private static final Logger LOGGER = Logger.getLogger(CIDWArray.class.getCanonicalName());
private static final Logger LOGGER = Logger.getLogger(CIDW2Array.class.getCanonicalName());
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main/java/org/verapdf/pd/font/CIDW2Array.java` at line 41, Update the
logger declaration in CIDW2Array to use CIDW2Array.class, then review the
invalid W2-entry logging sites in the relevant methods and change Level.FINE to
Level.SEVERE if these errors should follow the PR’s unified severity; keep the
severity unchanged only if the existing behavior is explicitly intentional.

Comment on lines +57 to +59
if (cidBegin == null) {
LOGGER.log(Level.FINE, "W array in CIDFont is invalid.");
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Missing early return after null check.

The cidBegin variable is checked for null, but execution continues. This will result in a NullPointerException when cidBegin.intValue() is later invoked on line 68 or 70.

Since the W array structure requires a strict sequence of values (c [w1 w2 ...] or c_first c_last w), failing to read cidBegin desynchronizes the parser. Parsing should be aborted here, just as it is when width == null below.

🐛 Proposed fix
                 if (cidBegin == null) {
                     LOGGER.log(Level.FINE, "W array in CIDFont is invalid.");
+                    return;
                 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (cidBegin == null) {
LOGGER.log(Level.FINE, "W array in CIDFont is invalid.");
}
if (cidBegin == null) {
LOGGER.log(Level.FINE, "W array in CIDFont is invalid.");
return;
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main/java/org/verapdf/pd/font/CIDWArray.java` around lines 57 - 59,
Update the cidBegin null-check in CIDWArray parsing to return immediately after
logging the invalid W array, matching the existing width == null handling. This
must prevent subsequent cidBegin.intValue() calls and abort parsing before the
token sequence becomes desynchronized.

@MaximPlusov MaximPlusov force-pushed the vertical-font-support branch from 2db26a8 to 8870bc3 Compare July 15, 2026 13:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants