Skip to content

/ToUnicode in PDF can be wrong if a glyph is mapped from multiple code points #4582

Closed

Description

@YDX-2147483647

Description

Compile the following on typst.app, download PDF, and copy the text.

#set text(lang: "zh", region: "CN", font: "Noto Serif CJK SC")
力量

You will get 力量 (U+F98A U+F97E in CJK Compatibility Ideographs), instead of 力量 (U+529B U+91CF in CJK Unified Ideographs).

CJK Compatibility Ideographs often look bizarre, because they fallback to the system font.

Screenshot of notepad.exe:
notepad screenshot

Continues #3416/#3435
Might relate to typst/webapp-issues#48

Cause

/ToUnicode in PDF maps glyphs to Unicode code points, making it possible to copy and search text.
However, sometimes a glyph in a font is shared by multiple code points.
There are 3 code points mapping to the glyph cid11384 in SourceHanSerifCN-Regular.otf (downloaded from Region Specific Subset OTFs Simplified Chinese (简体中文)):

(generated by a Python script)
from unicodedata import name

from fontTools.ttLib import TTFont

font = TTFont("SourceHanSerifCN-Regular.otf")
cmap = font["cmap"].getBestCmap()

the_character = "\u529b"
the_glyph = cmap[ord(the_character)]

for c, g in cmap.items():
    if g == the_glyph:
        print(f"{chr(c)} (U+{c:X} {name(chr(c))}): {g}")

print("---")

for c in "⼒力力":
    print(f"{c} (U+{ord(c):X} {name(c)}): {ord(c) in cmap = }")

Only one code point can be written to /ToUnicode, and Typst chooses U+F98A 力 (CJK compatibility).

Adobe’s implementation

Adobe explicitly maps the glyph to the most used one, U+529B 力 (CJK unified).

To UVS, Or Not To UVS - CJK Type Blog | Adobe:

A ToUnicode mapping file does exactly what its name suggests: it maps CIDs to Unicode code points, or to code point sequences. Unlike CMap resources that map Unicode code points to CIDs, or 'cmap' tables that map code points to GIDs that may also be CIDs, a ToUnicode mapping file specifies the inverse mapping. Some omissions and ambiguities can arise, either because a glyph is represented as a sequence, or it is mapped from multiple code points.

An excellent example of the latter is Adobe-Japan1-7 CID+1200, which is mapped from U+2F00 ⼀ KANGXI RADICAL ONE and U+4E00 一 (a CJK Unified Ideograph). If CID+1200 is included in a PDF, one would naturally expect U+4E00 一 to be copied, not U+2F00 ⼀ as its use is more obscure. The Adobe-Japan1-UCS2 ToUnicode mapping file makes this mapping preference explicit (04b0 is the zero-padded hexadecimal form of decimal 1200):

<04b0> <4e00>

https://github.com/adobe-type-tools/cmap-resources/blob/f5cf3bca7fdfeaceb77aa82847e974f2306c20b4/Adobe-GB1-6/cid2code.txt#L27-L29:

There may be cases of single CIDs being referenced in multiple encoding points within a single CMap file.
These cases are comma-delimited, within the same column.

CMap

/ToUnicode

Further example

#set page(height: auto, width: 30em)
#set text(lang: "zh", region: "CN", fallback: false)

#let fonts = (
  // "Linux Libertine", // no glyph
  // "Noto Serif", // no glyph
  "Noto Serif CJK SC",
  "Noto Sans CJK SC",
)

#for f in fonts {
  text(font: f)[
    #f

    - ⼒ U+2F12 Kangxi radical
    - 力 U+529B CJK unified
    - 力 U+F98A CJK compatibility

    地球发动机是人类建造的力量最大的机器,比如我们所在的华北794号,全功率运行时能向大地产生150亿吨的推力。

    #pagebreak()
  ]
}

Screenshot of the result in a nerd font:

Reproduction URL

No response

Operating system

Web app, Windows

Typst version

  • I am using the latest version of Typst

Activity

  1. added
    bug
    on Jul 18, 2024
  2. Enter-tainer commented on Jul 18, 2024

    @Enter-tainer
    Contributor
  3. YDX-2147483647 commented on Jul 18, 2024

    @YDX-2147483647
    ContributorAuthor

    Besides, https://itextpdf.com/sites/default/files/2018-12/PP_Advanced_typography_in_PDF-compressed.pdf mentioned a transposed problem: multiple glyphs, one code point.

    IMG_9454

    But I cannot read this language, and have no idea if Typst supports it.

  4. LaurenzV commented on Jul 18, 2024

    @LaurenzV
    Collaborator

    Somewhat relevant issues: #526 #4225

  5. laurmaedje commented on Jul 18, 2024

    @laurmaedje
    Member

    Isn't this a direct duplicate of #4225?

  6. added
    pdf
    on Jul 18, 2024
  7. LaurenzV commented on Jul 18, 2024

    @LaurenzV
    Collaborator

    Not sure, but since this issue is pretty descriptive I think it makes sense to keep it open.

  8. laurmaedje commented on Jul 18, 2024

    @laurmaedje
    Member

    Yeah, I agree that this issue is very well written. Perhaps we could close the other one instead.

  9. YDX-2147483647 commented on Jul 18, 2024

    @YDX-2147483647
    ContributorAuthor

    Isn't this a direct duplicate of #4225?

    Well, I think Chinese and devanagari are two distinct issue.

    The slide I posted above (#4582 (comment)) describes #4225. (I unhide it from off-topic now.)

  10. laurmaedje commented on Jul 18, 2024

    @laurmaedje
    Member

    Okay, I guess we can keep both issues open. But I think a proper solution will fix both. Probably it is writing /ToUnicode for one (e.g. the most common) and then using /ActualText everywhere else.

  11. YDX-2147483647 commented on Jul 18, 2024

    @YDX-2147483647
    ContributorAuthor

    A rough example in European languages might be helpful.

    • Chinese: We write Apple in English, but Typst gives Αpple, where Α is U+391 GREEK CAPITAL LETTER ALPHA instead of U+41 LATIN CAPITAL LETTER A.
    • Indic: We write Äpfel (A+Umlaut, p, f, e, l) in German, but Typst gives Af¨pel (A, f, Umlaut, p, e, l).
  12. YDX-2147483647 commented on Jul 19, 2024

    @YDX-2147483647
    ContributorAuthor

    How the code point is chosen now

    Among Kangxi radical (⼒), CJK unified (力), CJK compatibility (力), Typst tends to choose CJK compatibility.
    But Apple, Microsoft, and Adobe products tend to choose Kangxi radical, according to the Chinese article mentioned in #4582 (comment) and a Japanese report of 有限会社サイパック.

    Typst chooses CJK compatibility because it has larger Unicode code point number.

    When write_normal_text(), Typst records the code point that occurs first for each glyph. Later in improve_glyph_sets(), Typst replaces code points from the font's cmap table. If a glyph is mapped from multiple code points, it gets replaced multiple times, and the largest code point wins at last.

    improve_glyph_sets(&mut resources.glyph_sets);

    pub fn improve_glyph_sets(glyph_sets: &mut HashMap<Font, BTreeMap<u16, EcoString>>) {

    for subtable in ttf.tables().cmap.into_iter().flat_map(|table| table.subtables) {
        …
    
        //+ println!("{subtable:?}");
        subtable.codepoints(|n| {
            let Some(c) = std::char::from_u32(n) else { return };
            …
    
            let Some(GlyphId(g)) = ttf.glyph_index(c) else { return };
            if glyph_set.contains_key(&g) {
                //+ if g == 9885 {
                //+     println!("{g:?}: {:?} → {c:?}", glyph_set.get(&g));
                //+ }
                glyph_set.insert(g, c.into());
            }
        });
    }
    Subtable { platform_id: Unicode, encoding_id: 3, format: SegmentMappingToDeltaValues(Subtable4 { ... }) }
    9885: Some("⼒") → '⼒'  # Kangxi radical (occurs first) → Kangxi radical
    9885: Some("⼒") → '力'  # Kangxi radical → CJK unified
    9885: Some("力") → '力'  # CJK unified → CJK compatibility
    Subtable { platform_id: Unicode, encoding_id: 4, format: SegmentedCoverage(Subtable12 { ... }) }
    9885: Some("力") → '⼒'  # CJK compatibility → Kangxi radical
    9885: Some("⼒") → '力'  # Kangxi radical → CJK unified
    9885: Some("力") → '力'  # CJK unified → CJK compatibility
    Subtable { platform_id: Unicode, encoding_id: 5, format: UnicodeVariationSequences(Subtable14 { ... }) }
    Subtable { platform_id: Windows, encoding_id: 1, format: SegmentMappingToDeltaValues(Subtable4 { ... }) }
    9885: Some("力") → '⼒'  # Same as last loop
    9885: Some("⼒") → '力'
    9885: Some("力") → '力'
    Subtable { platform_id: Windows, encoding_id: 10, format: SegmentedCoverage(Subtable12 { ... }) }
    9885: Some("力") → '⼒'  # Same as last loop
    9885: Some("⼒") → '力'
    9885: Some("力") → '力'

    OpenType offers tables for many platforms and encodings (Windows/Unicode, full repertoire / BMP, etc.), and Typst iterates all of them.

    Details on those tables

    getBestCmap - cmap: Character to Glyph Index Mapping Table — fontTools Documentation: (updated according to cmap - Character To Glyph Index Mapping Table (OpenType 1.9.1) - Typography | Microsoft Learn)

    By default it will search for the following (platform ID, platform encoding ID) pairs in order:

    (3, 10), # Windows Unicode full repertoire		[format 12 subtable]		d
    (0, 6),  # Unicode full repertoire (format 13 subtable)
    (0, 4),  # Unicode 2.0 full repertoire			[format 10 or 12 subtable]	b
    (3, 1),  # Windows Unicode BMP					[format 4 subtable]			c
    (0, 3),  # Unicode 2.0 BMP						[format 4 or 6 subtable]	a
    (0, 2),  # ISO/IEC 10646 semantics				[deprecated]
    (0, 1),  # Unicode 1.1 semantics				[deprecated]
    (0, 0)   # Unicode 1.0 semantics				[deprecated]
    

    This particular order matches what HarfBuzz uses to choose what subtable to use by default. This order prefers the largest-repertoire subtable, and among those, prefers the Windows-platform over the Unicode-platform as the former has wider support.

    ttf\_parser::cmap - Rust:

    In ttf-parser v0.12, only Face::character_mapping_subtables is supported. Then it changed to Face::tables().cmap in v0.13+. Typst upgraded ttf-parser from v0.12 to v0.15 in ed6550f.

  13. added 5 commits that reference this issue on Jul 19, 2024
    4b55e8a
    2e1e355
    360c1cd
    a7123b5
    ce40f9f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugpdf

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions