diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index c545161..fbefd26 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -14,8 +14,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - - name: Install CJK font fixture and PDF extraction utility - run: sudo apt-get install -y --no-install-recommends fonts-droid-fallback poppler-utils + - name: Install PDF, font and shaping test dependencies + run: sudo apt-get install -y --no-install-recommends fonts-droid-fallback poppler-utils libharfbuzz-bin libfribidi-bin - name: Detect minimum PHP from composer.json id: php_min run: | diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index 9f65254..adda46a 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -13,8 +13,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - - name: Install PDF extraction and CJK test fixtures - run: sudo apt-get install -y --no-install-recommends fonts-droid-fallback poppler-utils + - name: Install PDF and text shaping test dependencies + run: sudo apt-get install -y --no-install-recommends fonts-droid-fallback poppler-utils libharfbuzz-bin libfribidi-bin - name: Detect minimum PHP from composer.json id: php_min run: | diff --git a/.github/workflows/test-integration.yml b/.github/workflows/test-integration.yml index 9a49b71..5e078c6 100644 --- a/.github/workflows/test-integration.yml +++ b/.github/workflows/test-integration.yml @@ -13,8 +13,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - - name: Install CJK font fixture and PDF extraction utility - run: sudo apt-get install -y --no-install-recommends fonts-droid-fallback poppler-utils + - name: Install PDF, font and shaping test dependencies + run: sudo apt-get install -y --no-install-recommends fonts-droid-fallback poppler-utils libharfbuzz-bin libfribidi-bin - name: Detect minimum PHP from composer.json id: php_min run: | diff --git a/composer.json b/composer.json index e9fd61d..fc21ea1 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,8 @@ "css" ], "require": { - "php": "^8.2" + "php": "^8.2", + "symfony/process": "^7.0" }, "require-dev": { "bamarni/composer-bin-plugin": "^1.8", diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 1a77e3a..02120c5 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -36,6 +36,7 @@ theme: nav: - Home: index.md - Getting started: guides/getting-started.md + - Unicode fonts: guides/unicode-fonts.md - Examples: reference/examples.md - Visible signature use case: use-cases/visible-signatures.md diff --git a/docs/source/guides/unicode-fonts.md b/docs/source/guides/unicode-fonts.md new file mode 100644 index 0000000..37866f3 --- /dev/null +++ b/docs/source/guides/unicode-fonts.md @@ -0,0 +1,47 @@ + + + +# Unicode text in PDF XObjects + +The compiler preserves Unicode names using embedded TrueType fonts, a Type 0/CIDFontType2 font resource, and a `ToUnicode` map. Plain single-byte PDF Type 1 fonts do not cover Arabic, Hebrew, CJK, and many other scripts. + +## Configure fonts + +```php +use LibreSign\XObjectTemplate\Dto\CompileRequest; +use LibreSign\XObjectTemplate\Pdf\TemplateDocumentBuilder; +use LibreSign\XObjectTemplate\XObjectTemplateCompiler; + +$builder = (new TemplateDocumentBuilder())->withUnicodeFontFiles([ + '/path/to/embeddable/DejaVuSans.ttf', + '/path/to/embeddable/CJK-font.ttf', +]); +$compiler = new XObjectTemplateCompiler(documentBuilder: $builder); +$result = $compiler->compile(new CompileRequest( + html: '
Signed by محمد
', + width: 400, + height: 90, +)); +``` + +Only supply trusted, valid `.ttf` files with embedding rights. Fonts are loaded from explicitly configured paths, **not** discovered from arbitrary template input. The first configured font covering an entire line is preferred. Otherwise, the compiler selects fonts for contiguous runs without separating a grapheme (base character and its combining marks). Missing glyph coverage for a complete grapheme raises an exception rather than silently substituting a character. A mixed line such as `Signed by محمد / 山田太郎` can use both configured fonts. + +### Complex scripts + +HarfBuzz handles OpenType glyph substitution/positioning; FriBidi provides paragraph directions and visual ordering. Deployments that use Arabic, Hebrew or combining marks must provide the `hb-shape` and `fribidi` executables on `PATH`. For Debian/Ubuntu these are packaged as `libharfbuzz-bin` and `libfribidi-bin`. No native tools are required for the simpler direct-glyph path. A missing or failing native tool produces an error, never a silently incorrect PDF. + +Both tools are executed with argument arrays, a fixed timeout and limited input. The shaping font is a temporary private file, deleted in a `finally` block. Inputs are decoded and validated as Unicode scalars. + +For shaped text, FriBidi determines visual runs before font fallback. HarfBuzz receives the surrounding text context when a directional run is split across fonts, preserving joining behavior where the selected fonts support it. PDF appearance operators use exact glyph IDs and positioning with a logical Unicode `ActualText` span; font switches use the embedded font resources of the corresponding run. Different PDF extractors can report bidirectional text in visual order despite `ActualText`; test extraction with more than one independent reader when interoperability matters. + +### Signed PDF integration + +For signature appearance XObjects, the resource dictionary must be materialized **in the destination PDF document**, not simply embedded as PHP arrays. The `SignerPhpCoreXObjectResourceBuilder` adapter supplies the resources-builder closure to the compatible `SignerPHP/pdf-core` `AppearanceXObject`. Pass it using the named `resourcesBuilder:` parameter so older versions fail explicitly instead of ignoring an extra positional argument. This depends on the optional resource-builder API introduced in [SignerPHP/pdf-core PR #5](https://github.com/SignerPHP/pdf-core/pull/5). A consumer must first use a `pdf-core` version containing that API; older releases cannot process these indirect resources. + +Test signature appearance output cryptographically (CMS/ByteRange), structurally (font file, descendant font and `ToUnicode`) and visually. Passing just one of these checks is insufficient. + +### Limits + +* Complete font files are currently embedded; glyph subsetting is not implemented. This increases signed-PDF size. FontTools' `pyftsubset --retain-gids` is a possible **future** optimization, but needs reproducible tests for CID/GID stability and licensing before adoption. +* The library handles the scripts exercised by its integration matrix; it does not claim full OpenType coverage for every language, variation-selector sequence or color font. +* Complex shaping requires the external binaries at runtime and appropriate fonts in the deployment environment. diff --git a/docs/source/index.md b/docs/source/index.md index 250a6b7..4c8d2ab 100644 --- a/docs/source/index.md +++ b/docs/source/index.md @@ -8,6 +8,7 @@ ## Start here - [Getting started](guides/getting-started.md) +- [Unicode text and font resources](guides/unicode-fonts.md) - [Examples](reference/examples.md) - [Visible signature use case](use-cases/visible-signatures.md) diff --git a/src/Layout/TextLineBreaker.php b/src/Layout/TextLineBreaker.php index 86798ef..10434ea 100644 --- a/src/Layout/TextLineBreaker.php +++ b/src/Layout/TextLineBreaker.php @@ -277,8 +277,10 @@ private function splitWords(string $text): array */ private function splitCharacters(string $text): array { - $characters = preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY); + // A fallback line break must not split a combining sequence or + // another extended grapheme cluster into separate rendered lines. + preg_match_all('/\X/u', $text, $matches); - return $characters === false ? [] : $characters; + return $matches[0]; } } diff --git a/src/Pdf/ComplexTextShaperInterface.php b/src/Pdf/ComplexTextShaperInterface.php new file mode 100644 index 0000000..5da1a5f --- /dev/null +++ b/src/Pdf/ComplexTextShaperInterface.php @@ -0,0 +1,31 @@ +, + * advance: int, dx: int, dy: int, cluster: int, logical: int + * }> + */ + public function shape(string $text, TrueTypeFont $font): array; + + /** + * Resolve bidirectional order before splitting shaping runs among configured fonts. + * @param list $fonts + * @return list, + * advance: int, dx: int, dy: int, cluster: int, logical: int + * }> + */ + public function shapeWithFonts(string $text, array $fonts): array; +} diff --git a/src/Pdf/FriBidiParagraphMapper.php b/src/Pdf/FriBidiParagraphMapper.php new file mode 100644 index 0000000..03bcd4c --- /dev/null +++ b/src/Pdf/FriBidiParagraphMapper.php @@ -0,0 +1,151 @@ +, ?string): string $run */ + public function __construct( + private string $binary, + private Closure $run, + ) { + } + + /** + * @param list $characters + * @return list + */ + public function runs(string $text, array $characters): array + { + [$visual, $levels] = $this->bidiMaps($text, count($characters)); + return $this->visualRuns($characters, $visual, $levels); + } + + /** + * @return array{list, list} + */ + private function bidiMaps(string $text, int $count): array + { + $output = ($this->run)([ + $this->binary, + '--novisual', + '--ltov', + '--vtol', + '--levels', + '--basedir', + '--charset=UTF-8', + '--nopad', + ], $text . "\n"); + $lines = explode("\n", trim($output)); + if (count($lines) !== 4 || !str_starts_with($lines[0], 'Base direction: ')) { + throw new InvalidArgumentException('FriBidi returned an invalid paragraph map.'); + } + $visual = $this->parseMap($lines[1], $count); + $inverse = $this->parseMap($lines[2], $count); + $levels = $this->parseMap($lines[3], $count); + foreach ($visual as $logicalIndex => $visualIndex) { + if ($visualIndex < 0 || $visualIndex >= $count || $inverse[$visualIndex] !== $logicalIndex) { + throw new InvalidArgumentException('FriBidi returned inconsistent visual positions.'); + } + } + return [$visual, $levels]; + } + + /** @return list */ + private function parseMap(string $line, int $count): array + { + $tokens = preg_split('/\s+/', trim($line)); + if (count($tokens) !== $count) { + throw new InvalidArgumentException('FriBidi returned an inconsistent character map.'); + } + $values = []; + foreach ($tokens as $token) { + if (!ctype_digit($token)) { + throw new InvalidArgumentException('FriBidi returned a nonnumeric character map.'); + } + $values[] = intval($token); + } + return $values; + } + + /** + * @param list $characters + * @param list $visualPositions + * @param list $levels + * @return list + */ + private function visualRuns(array $characters, array $visualPositions, array $levels): array + { + $runs = []; + $start = 0; + $script = $this->scriptOf($characters[0]); + for ($i = 1, $length = count($characters); $i <= $length; $i++) { + $nextScript = $i < $length ? $this->scriptOf($characters[$i]) : ''; + if ($this->shouldContinueRun($i, $length, $levels, $start, $nextScript, $script)) { + $script = $nextScript !== '' ? $nextScript : $script; + continue; + } + /** @var non-empty-list $positions Run boundaries always contain at least one character. */ + $positions = array_slice($visualPositions, $start, $i - $start); + $runs[] = [ + 'text' => implode('', array_slice($characters, $start, $i - $start)), + 'rtl' => ($levels[$start] % 2) === 1, + 'visual' => min($positions), + 'start' => $start, + ]; + $start = $i; + $script = $nextScript; + } + usort($runs, static fn (array $first, array $second): int => $first['visual'] <=> $second['visual']); + return $runs; + } + + /** @param list $levels */ + private function shouldContinueRun( + int $index, + int $count, + array $levels, + int $start, + string $nextScript, + string $script, + ): bool { + return $index < $count + && $levels[$index] === $levels[$start] + && ($nextScript === $script || $nextScript === '' || $script === ''); + } + + private function scriptOf(string $character): string + { + // Marks inherit the base's script even when PCRE's Script_Extensions + // data assigns them to several scripts (or a different primary script). + if (preg_match('/\p{M}/u', $character) === 1) { + return ''; + } + $patterns = [ + '/\p{sc=Arabic}/u' => 'Arab', + '/\p{sc=Hebrew}/u' => 'Hebr', + '/\p{sc=Latin}/u' => 'Latn', + '/\p{sc=Cyrillic}/u' => 'Cyrl', + '/\p{sc=Greek}/u' => 'Grek', + '/\p{sc=Han}/u' => 'Hani', + '/\p{sc=Hiragana}/u' => 'Hira', + '/\p{sc=Katakana}/u' => 'Kana', + '/\p{sc=Hangul}/u' => 'Hang', + ]; + foreach ($patterns as $pattern => $script) { + if (preg_match($pattern, $character) === 1) { + return $script; + } + } + return ''; + } +} diff --git a/src/Pdf/HarfBuzzComplexTextShaper.php b/src/Pdf/HarfBuzzComplexTextShaper.php new file mode 100644 index 0000000..be76725 --- /dev/null +++ b/src/Pdf/HarfBuzzComplexTextShaper.php @@ -0,0 +1,160 @@ +, ?string): string */ + private Closure $run; + + /** + * @param ?Closure(list, ?string): string $commandRunner + */ + public function __construct( + private string $harfbuzzBinary = 'hb-shape', + private string $fribidiBinary = 'fribidi', + ?Closure $commandRunner = null, + private UnicodeScalarCodec $codec = new UnicodeScalarCodec(), + private TemporaryFontFile $temporaryFontFile = new TemporaryFontFile(), + ) { + $this->run = $commandRunner ?? (new NativeTextCommandRunner())->run(...); + } + + /** + * @return list, advance: int, + * dx: int, dy: int, cluster: int, logical: int + * }> + */ + public function shape(string $text, TrueTypeFont $font): array + { + $runs = $this->paragraphRuns($text); + if ($runs === []) { + return []; + } + $runShaper = new HarfBuzzRunShaper($this->harfbuzzBinary, $this->run, $this->codec); + return $this->temporaryFontFile->withFont( + $font->fontData(), + static function (string $path) use ($runs, $runShaper): array { + $result = []; + foreach ($runs as $run) { + foreach ($runShaper->shape($path, $run['text'], $run['rtl']) as $glyph) { + $glyph['logical'] = $run['start'] + $glyph['cluster']; + $result[] = $glyph; + } + } + return $result; + }, + ); + } + + /** + * @param list $fonts + * @return list, + * advance: int, dx: int, dy: int, cluster: int, logical: int + * }> + */ + public function shapeWithFonts(string $text, array $fonts): array + { + $runs = $this->fontRuns($this->paragraphRuns($text), $fonts); + $runShaper = new HarfBuzzRunShaper($this->harfbuzzBinary, $this->run, $this->codec); + $result = []; + foreach ($runs as $run) { + $glyphs = $this->temporaryFontFile->withFont( + $fonts[$run['fontIndex']]->fontData(), + static fn (string $path): array => $runShaper->shape( + $path, + $run['text'], + $run['rtl'], + $run['before'], + $run['after'], + ), + ); + foreach ($glyphs as $glyph) { + $result[] = $glyph + [ + 'logical' => $run['start'] + $glyph['cluster'], + 'fontIndex' => $run['fontIndex'], + ]; + } + } + return $result; + } + + /** @return list */ + private function paragraphRuns(string $text): array + { + $codepoints = $this->codec->decode($text); + if ($codepoints === []) { + return []; + } + if (count($codepoints) > 4096 || preg_match('/[\r\n\x00]/', $text) === 1) { + throw new InvalidArgumentException('Complex text must be a single line with at most 4096 Unicode scalars.'); + } + + /** @var list $characters */ + $characters = preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY); + $runs = (new FriBidiParagraphMapper($this->fribidiBinary, $this->run))->runs($text, $characters); + if (count($runs) > 32) { + throw new InvalidArgumentException('Complex text exceeds the safe number of shaping runs.'); + } + return $runs; + } + + /** + * @param list $bidiRuns + * @param list $fonts + * @return list + */ + private function fontRuns(array $bidiRuns, array $fonts): array + { + $result = []; + $selector = new UnicodeFontRunSelector(); + foreach ($bidiRuns as $bidiRun) { + $segments = $selector->runs($bidiRun['text'], $fonts); + if ($segments === null) { + throw new InvalidArgumentException( + 'Unicode text requires an embedded TrueType font covering every shaped glyph.', + ); + } + $segments = $this->withRunContext($segments, $bidiRun['start'], $bidiRun['rtl']); + array_push($result, ...$segments); + } + if (count($result) > 32) { + throw new InvalidArgumentException('Complex text exceeds the safe number of shaping runs.'); + } + return $result; + } + + /** + * @param list $segments + * @return list + */ + private function withRunContext(array $segments, int $start, bool $rtl): array + { + $before = ''; + $after = implode('', array_column($segments, 'text')); + $result = []; + foreach ($segments as $segment) { + $after = substr($after, strlen($segment['text'])); + $segment['start'] += $start; + $result[] = $segment + ['rtl' => $rtl, 'before' => $before, 'after' => $after]; + $before .= $segment['text']; + } + return $rtl ? array_reverse($result) : $result; + } +} diff --git a/src/Pdf/HarfBuzzRunShaper.php b/src/Pdf/HarfBuzzRunShaper.php new file mode 100644 index 0000000..8474d28 --- /dev/null +++ b/src/Pdf/HarfBuzzRunShaper.php @@ -0,0 +1,128 @@ +, ?string): string $run */ + public function __construct( + private string $binary, + private Closure $run, + private UnicodeScalarCodec $codec, + ) { + } + + /** + * @return list, advance: int, dx: int, dy: int, cluster: int}> + */ + public function shape( + string $fontPath, + string $text, + bool $rtl, + string $before = '', + string $after = '', + ): array { + return $this->mapClusters($this->shapeRun($fontPath, $text, $rtl, $before, $after), $text); + } + + /** + * @return list + */ + private function shapeRun(string $fontPath, string $text, bool $rtl, string $before, string $after): array + { + $arguments = [ + $this->binary, + '--no-glyph-names', + '--output-format=json', + '--font-size=1000', + '--direction=' . ($rtl ? 'rtl' : 'ltr'), + '--text=' . $text, + ]; + if ($before !== '') { + $arguments[] = '--text-before=' . $before; + } + if ($after !== '') { + $arguments[] = '--text-after=' . $after; + } + $arguments[] = $fontPath; + $output = ($this->run)($arguments, null); + try { + $result = json_decode($output, true, flags: JSON_THROW_ON_ERROR); + } catch (JsonException $error) { + throw new InvalidArgumentException('HarfBuzz returned invalid JSON.', previous: $error); + } + if (!is_array($result) || !array_is_list($result) || $result === []) { + throw new InvalidArgumentException('HarfBuzz returned no glyphs.'); + } + /** @psalm-suppress MixedAssignment JSON structure is validated by assertGlyph. */ + foreach ($result as $glyph) { + $this->assertGlyph($glyph); + } + /** @var list $result */ + return $result; + } + + private function assertGlyph(mixed $glyph): void + { + if (!is_array($glyph) || !isset($glyph['g'], $glyph['cl'], $glyph['ax'], $glyph['dx'], $glyph['dy'])) { + throw new InvalidArgumentException('HarfBuzz returned an invalid glyph position.'); + } + foreach (['g', 'cl', 'ax', 'dx', 'dy'] as $field) { + if (!isset($glyph[$field]) || !is_int($glyph[$field])) { + throw new InvalidArgumentException('HarfBuzz returned a noninteger glyph position.'); + } + } + if ($glyph['g'] <= 0 || $glyph['g'] > 65535) { + throw new InvalidArgumentException('HarfBuzz returned an invalid glyph index.'); + } + } + + /** + * @param list $glyphs + * @return list, advance: int, dx: int, dy: int, cluster: int}> + */ + private function mapClusters(array $glyphs, string $runText): array + { + $codepoints = $this->codec->decode($runText); + $clusters = array_column($glyphs, 'cl'); + sort($clusters, SORT_NUMERIC); + if (($clusters[0] ?? null) !== 0) { + throw new InvalidArgumentException('HarfBuzz returned incomplete Unicode cluster coverage.'); + } + $mapping = []; + foreach ($clusters as $index => $cluster) { + $next = $clusters[$index + 1] ?? count($codepoints); + if ($next > count($codepoints)) { + throw new InvalidArgumentException('HarfBuzz returned an invalid Unicode cluster boundary.'); + } + $mapping[$cluster] = array_slice($codepoints, $cluster, $next - $cluster); + } + $used = []; + $result = []; + foreach ($glyphs as $glyph) { + $cluster = $glyph['cl']; + $unicode = array_key_exists($cluster, $used) ? [0x200B] : $mapping[$cluster]; + $used[$cluster] = $unicode; + $result[] = [ + 'glyph' => $mapping[$cluster][0], + 'cluster' => $cluster, + 'glyphId' => $glyph['g'], + 'unicode' => $unicode, + 'advance' => $glyph['ax'], + 'dx' => $glyph['dx'], + 'dy' => $glyph['dy'], + ]; + } + return $result; + } +} diff --git a/src/Pdf/NativeTextCommandRunner.php b/src/Pdf/NativeTextCommandRunner.php new file mode 100644 index 0000000..453338d --- /dev/null +++ b/src/Pdf/NativeTextCommandRunner.php @@ -0,0 +1,30 @@ + $command + */ + public function run(array $command, ?string $stdin): string + { + try { + $process = new Process($command, null, ['LC_ALL' => 'C.UTF-8'], $stdin, 8.0); + $process->mustRun(); + return $process->getOutput(); + } catch (Throwable $error) { + throw new InvalidArgumentException('A working HarfBuzz/FriBidi runtime is required.', previous: $error); + } + } +} diff --git a/src/Pdf/StandardFontMetrics.php b/src/Pdf/StandardFontMetrics.php index 26a9d9e..f63c993 100644 --- a/src/Pdf/StandardFontMetrics.php +++ b/src/Pdf/StandardFontMetrics.php @@ -54,8 +54,10 @@ ]; /** @param list $unicodeFonts */ - public function __construct(private array $unicodeFonts = []) - { + public function __construct( + private array $unicodeFonts = [], + private ComplexTextShaperInterface $complexShaper = new HarfBuzzComplexTextShaper(), + ) { } public function measureString(string $fontAlias, float $fontSize, string $text): float @@ -86,19 +88,11 @@ public function measureString(string $fontAlias, float $fontSize, string $text): private function measureUnicode(float $fontSize, string $text): float { - $glyphs = (new DirectGlyphShaper())->shape($text); - foreach ($this->unicodeFonts as $font) { - $width = 0; - foreach ($glyphs as $glyph) { - $glyphId = $font->glyphFor($glyph['glyph']); - if ($glyphId === 0) { - continue 2; - } - $width += $font->widthForGlyph($glyphId); - } - return $width * $fontSize / 1000; + $plan = (new UnicodeTextPlanner($this->complexShaper))->plan($text, $this->unicodeFonts); + if ($plan === null) { + return 0.0; } - return 0.0; + return array_sum(array_column($plan['glyphs'], 'advance')) * $fontSize / 1000; } private function resolveCharacterWidth(string $fontAlias, string $character): float diff --git a/src/Pdf/TemplateDocumentBuilder.php b/src/Pdf/TemplateDocumentBuilder.php index 3e0ece6..d5a665f 100644 --- a/src/Pdf/TemplateDocumentBuilder.php +++ b/src/Pdf/TemplateDocumentBuilder.php @@ -64,6 +64,7 @@ public function __construct( ?Closure $clock = null, /** @var list */ private array $unicodeFonts = [], + private ComplexTextShaperInterface $complexShaper = new HarfBuzzComplexTextShaper(), ) { $this->clock = $clock ?? static fn (): int => hrtime(true); } @@ -74,15 +75,16 @@ public function build( int $startedAtNs, int $nodeCount = 0, ): CompileResult { + $unicode = new UnicodeTextResources($layout->lines, $this->unicodeFonts, $this->complexShaper); return new CompileResult( - contentStream: $this->buildContentStream($layout), - resources: $this->buildResources($layout), + contentStream: $this->buildContentStream($layout, $unicode), + resources: $this->buildResources($layout, $unicode), bbox: [0.0, 0.0, $request->width, $request->height], metadata: $this->buildMetadata($layout, $startedAtNs, $nodeCount), ); } - public function buildContentStream(LayoutResult $layout): string + public function buildContentStream(LayoutResult $layout, ?UnicodeTextResources $unicode = null): string { $stream = ['q']; @@ -94,7 +96,7 @@ public function buildContentStream(LayoutResult $layout): string $stream[] = $this->buildImageCommand($image); } - $unicode = new UnicodeTextResources($layout->lines, $this->unicodeFonts); + $unicode ??= new UnicodeTextResources($layout->lines, $this->unicodeFonts, $this->complexShaper); $this->appendTextCommands($stream, $layout->lines, $unicode); $stream[] = 'Q'; @@ -105,9 +107,9 @@ public function buildContentStream(LayoutResult $layout): string /** * @return array */ - public function buildResources(LayoutResult $layout): array + public function buildResources(LayoutResult $layout, ?UnicodeTextResources $unicode = null): array { - $unicode = new UnicodeTextResources($layout->lines, $this->unicodeFonts); + $unicode ??= new UnicodeTextResources($layout->lines, $this->unicodeFonts, $this->complexShaper); $resources = [ 'Font' => array_merge($this->fontResources, $unicode->fonts()), 'XObject' => [], @@ -144,19 +146,33 @@ public function buildMetadata(LayoutResult $layout, int $startedAtNs, int $nodeC */ public function withFontResources(array $fontResources): self { - return new self($this->pdfEscaper, $this->colorParser, $fontResources, $this->clock, $this->unicodeFonts); + return new self( + $this->pdfEscaper, + $this->colorParser, + $fontResources, + $this->clock, + $this->unicodeFonts, + $this->complexShaper, + ); } /** - * Configure embeddable TrueType fonts (in fallback order). The font must - * cover every Unicode character in each non-ASCII text line. + * Configure embeddable TrueType fonts (in fallback order). Each grapheme + * must be covered by one configured font. * * @param list $paths */ public function withUnicodeFontFiles(array $paths): self { $fonts = array_map(static fn (string $path): TrueTypeFont => new TrueTypeFont($path), $paths); - return new self($this->pdfEscaper, $this->colorParser, $this->fontResources, $this->clock, $fonts); + return new self( + $this->pdfEscaper, + $this->colorParser, + $this->fontResources, + $this->clock, + $fonts, + $this->complexShaper, + ); } /** @return list */ @@ -165,6 +181,11 @@ public function unicodeFonts(): array return $this->unicodeFonts; } + public function complexShaper(): ComplexTextShaperInterface + { + return $this->complexShaper; + } + private function buildImageCommand(LayoutImage $image): string { if ($image->clipBox === null) { diff --git a/src/Pdf/TemporaryFontFile.php b/src/Pdf/TemporaryFontFile.php new file mode 100644 index 0000000..4ac4bb4 --- /dev/null +++ b/src/Pdf/TemporaryFontFile.php @@ -0,0 +1,60 @@ +create = $create ?? static fn (): string|false => + tempnam(sys_get_temp_dir(), 'libresign-harfbuzz-font-'); + $this->write = $write ?? static fn (string $path, string $bytes): int|false => + file_put_contents($path, $bytes); + } + + /** + * @template T + * @param Closure(string):T $callback + * @return T + */ + public function withFont(string $bytes, Closure $callback): mixed + { + /** @var string|false $path */ + $path = ($this->create)(); + if ($path === false) { + throw new InvalidArgumentException('Unable to prepare temporary font data for shaping.'); + } + try { + /** @var int|false $written */ + $written = ($this->write)($path, $bytes); + if ($written !== strlen($bytes)) { + throw new InvalidArgumentException('Unable to write temporary font data for shaping.'); + } + return $callback($path); + } finally { + unlink($path); + } + } +} diff --git a/src/Pdf/UnicodeFontPdfWriter.php b/src/Pdf/UnicodeFontPdfWriter.php index 7facca6..ff31ccb 100644 --- a/src/Pdf/UnicodeFontPdfWriter.php +++ b/src/Pdf/UnicodeFontPdfWriter.php @@ -89,7 +89,7 @@ public function createWithFactories( } /** - * @return list}> + * @return list, glyphId?: int}> */ private function requireMappings(mixed $value): array { @@ -99,7 +99,7 @@ private function requireMappings(mixed $value): array foreach (array_keys($value) as $index) { $this->assertMapping($value[$index]); } - /** @var list}> $value */ + /** @var list, glyphId?: int}> $value */ return $value; } @@ -112,13 +112,14 @@ private function assertMapping(mixed $entry): void ) { throw new InvalidArgumentException('Invalid Unicode font mappings.'); } + $this->assertShapedGlyphId($entry); if (count(array_filter($entry['unicode'], 'is_int')) !== count($entry['unicode'])) { throw new InvalidArgumentException('Invalid Unicode scalar mapping.'); } } /** - * @param list}> $mappings + * @param list, glyphId?: int}> $mappings * @return array{list, string, list} */ private function collectMappings(TrueTypeFont $font, array $mappings): array @@ -130,7 +131,7 @@ private function collectMappings(TrueTypeFont $font, array $mappings): array $widths = []; $cmapEntries = []; foreach ($mappings as $index => $entry) { - $glyph = $font->glyphFor($entry['glyph']); + $glyph = $entry['glyphId'] ?? $font->glyphFor($entry['glyph']); if ($glyph === 0) { throw new InvalidArgumentException('Missing TrueType glyph for Unicode resource.'); } @@ -145,6 +146,17 @@ private function collectMappings(TrueTypeFont $font, array $mappings): array return [$widths, $cidMap, $cmapEntries]; } + /** @param array $entry */ + private function assertShapedGlyphId(array $entry): void + { + if (!array_key_exists('glyphId', $entry)) { + return; + } + if (!is_int($entry['glyphId']) || $entry['glyphId'] <= 0 || $entry['glyphId'] >= 65535) { + throw new InvalidArgumentException('Invalid shaped TrueType glyph index.'); + } + } + /** @param list $entries */ private function createToUnicode(array $entries): string { diff --git a/src/Pdf/UnicodeFontRunSelector.php b/src/Pdf/UnicodeFontRunSelector.php new file mode 100644 index 0000000..a268458 --- /dev/null +++ b/src/Pdf/UnicodeFontRunSelector.php @@ -0,0 +1,68 @@ + $fonts + * @return list|null + */ + public function runs(string $text, array $fonts): ?array + { + $fontIndex = $this->findFont($fonts, $this->codec->decode($text)); + if ($fontIndex !== null) { + return [['fontIndex' => $fontIndex, 'text' => $text, 'start' => 0]]; + } + + preg_match_all('/\X/u', $text, $matches); + /** @var list $runs */ + $runs = []; + $start = 0; + foreach ($matches[0] as $cluster) { + $scalars = $this->codec->decode($cluster); + $fontIndex = $this->findFont($fonts, $scalars); + if ($fontIndex === null) { + return null; + } + $clusterStart = $start; + $start += count($scalars); + $last = array_key_last($runs); + if ($last !== null && $runs[$last]['fontIndex'] === $fontIndex) { + $runs[$last]['text'] .= $cluster; + continue; + } + $runs[] = ['fontIndex' => $fontIndex, 'text' => $cluster, 'start' => $clusterStart]; + } + // Updating the last existing entry cannot create gaps in the list. + /** @var list $runs */ + return $runs; + } + + /** + * @param list $fonts + * @param list $codepoints + */ + private function findFont(array $fonts, array $codepoints): ?int + { + foreach ($fonts as $fontIndex => $font) { + foreach ($codepoints as $codepoint) { + if ($font->glyphFor($codepoint) === 0) { + continue 2; + } + } + return $fontIndex; + } + return null; + } +} diff --git a/src/Pdf/UnicodeTextPlanner.php b/src/Pdf/UnicodeTextPlanner.php new file mode 100644 index 0000000..e79b477 --- /dev/null +++ b/src/Pdf/UnicodeTextPlanner.php @@ -0,0 +1,76 @@ +, + * advance: int, dx: int, dy: int, cluster: int, logical: int + * } + */ +final readonly class UnicodeTextPlanner +{ + public function __construct( + private ComplexTextShaperInterface $complexShaper = new HarfBuzzComplexTextShaper(), + private UnicodeFontRunSelector $selector = new UnicodeFontRunSelector(), + ) { + } + + /** + * @param list $fonts + * @return array{positioned: bool, glyphs: list}|null + */ + public function plan(string $text, array $fonts): ?array + { + $runs = $this->selector->runs($text, $fonts); + if ($runs === null) { + return null; + } + + $complex = preg_match('/[\p{Arabic}\p{Hebrew}\p{M}]/u', $text) === 1; + if ($complex && count($runs) > 1) { + return ['positioned' => true, 'glyphs' => $this->complexShaper->shapeWithFonts($text, $fonts)]; + } + + $glyphs = []; + foreach ($runs as $run) { + $fontIndex = $run['fontIndex']; + $font = $fonts[$fontIndex]; + $shaped = $complex + ? $this->complexShaper->shape($run['text'], $font) + : $this->directGlyphs($run['text'], $font); + foreach ($shaped as $glyph) { + $glyph['fontIndex'] = $fontIndex; + $glyph['logical'] += $run['start']; + $glyphs[] = $glyph; + } + } + return ['positioned' => $complex || count($runs) > 1, 'glyphs' => $glyphs]; + } + + /** + * @return list, advance: int, dx: int, dy: int, cluster: int, logical: int + * }> + */ + private function directGlyphs(string $text, TrueTypeFont $font): array + { + $result = []; + foreach ((new DirectGlyphShaper())->shape($text) as $index => $glyph) { + $result[] = $glyph + [ + 'advance' => $font->widthForGlyph($font->glyphFor($glyph['glyph'])), + 'dx' => 0, + 'dy' => 0, + 'cluster' => $index, + 'logical' => $index, + ]; + } + return $result; + } +} diff --git a/src/Pdf/UnicodeTextResources.php b/src/Pdf/UnicodeTextResources.php index 8aaf9e3..ee527f0 100644 --- a/src/Pdf/UnicodeTextResources.php +++ b/src/Pdf/UnicodeTextResources.php @@ -10,27 +10,38 @@ use InvalidArgumentException; use LibreSign\XObjectTemplate\Layout\LayoutLine; -/** @internal Immutable per-layout Unicode resource preparation. */ +/** + * @internal Immutable per-layout Unicode resource preparation. + * @psalm-import-type Glyph from UnicodeTextPlanner + */ final readonly class UnicodeTextResources { /** * @var array}> + * mappings: list, glyphId?: int}> * }> */ private array $selected; - /** @var array}> */ + /** + * @var array, aliases: list, complex: bool, + * positions: list, x: float, y: float, fontSize: float, text: string + * }> + */ private array $lineBindings; /** * @param list $lines * @param list $fonts */ - public function __construct(array $lines, array $fonts) - { - $shaper = new DirectGlyphShaper(); + public function __construct( + array $lines, + array $fonts, + private ComplexTextShaperInterface $complexShaper = new HarfBuzzComplexTextShaper(), + ) { + $planner = new UnicodeTextPlanner($this->complexShaper); $selected = []; $bindings = []; @@ -38,62 +49,55 @@ public function __construct(array $lines, array $fonts) if (preg_match('/[^\x00-\x7f]/', $line->text) !== 1) { continue; } - $glyphs = $shaper->shape($line->text); - $fontIndex = $this->selectFont($fonts, $glyphs); - $alias = 'U' . ($fontIndex + 1); - $mappings = $selected[$alias]['mappings'] ?? []; - [$mappings, $cids] = $this->bindGlyphs($mappings, $glyphs); - $selected[$alias] = ['font' => $fonts[$fontIndex], 'mappings' => $mappings]; - $bindings[$index] = ['alias' => $alias, 'cids' => $cids]; + $plan = $planner->plan($line->text, $fonts); + if ($plan === null) { + throw new InvalidArgumentException( + 'Unicode text requires an embedded TrueType font covering every shaped glyph.', + ); + } + $cids = []; + $aliases = []; + foreach ($plan['glyphs'] as $glyph) { + $fontIndex = $glyph['fontIndex']; + $alias = 'U' . ($fontIndex + 1); + $mappings = $selected[$alias]['mappings'] ?? []; + $cids[] = $this->bindGlyph($mappings, $glyph); + $aliases[] = $alias; + $selected[$alias] = ['font' => $fonts[$fontIndex], 'mappings' => $mappings]; + } + $bindings[$index] = [ + 'alias' => $aliases[0], + 'cids' => $cids, + 'aliases' => $aliases, + 'complex' => $plan['positioned'], + 'positions' => $plan['glyphs'], + 'x' => $line->x, + 'y' => $line->y, + 'fontSize' => $line->fontSize, + 'text' => $line->text, + ]; } $this->selected = $selected; $this->lineBindings = $bindings; } /** - * @param list $fonts - * @param list}> $glyphs + * @param list, glyphId?: int}> $mappings + * @param-out list, glyphId?: int}> $mappings + * @param Glyph $glyph */ - private function selectFont(array $fonts, array $glyphs): int + private function bindGlyph(array &$mappings, array $glyph): int { - foreach ($fonts as $fontIndex => $font) { - if ($this->coversGlyphs($font, $glyphs)) { - return $fontIndex; - } + $mapping = ['glyph' => $glyph['glyph'], 'unicode' => $glyph['unicode']]; + if (isset($glyph['glyphId'])) { + $mapping['glyphId'] = $glyph['glyphId']; } - throw new InvalidArgumentException( - 'Unicode text requires an embedded TrueType font covering every shaped glyph.', - ); - } - - /** @param list}> $glyphs */ - private function coversGlyphs(TrueTypeFont $font, array $glyphs): bool - { - foreach ($glyphs as $glyph) { - if ($font->glyphFor($glyph['glyph']) === 0) { - return false; - } + $index = array_search($mapping, $mappings, true); + if ($index === false) { + $mappings[] = $mapping; + $index = count($mappings) - 1; } - return true; - } - - /** - * @param list}> $mappings - * @param list}> $glyphs - * @return array{list}>, list} - */ - private function bindGlyphs(array $mappings, array $glyphs): array - { - $cids = []; - foreach ($glyphs as $glyph) { - $index = array_search($glyph, $mappings, true); - if ($index === false) { - $mappings[] = $glyph; - $index = count($mappings) - 1; - } - $cids[] = $index + 1; - } - return [$mappings, $cids]; + return $index + 1; } /** @return array> */ @@ -120,10 +124,61 @@ public function textOperator(int $lineIndex, string $text, PdfEscaper $escaper): if ($binding === null) { return sprintf('(%s) Tj', $escaper->escapeLiteralString($text)); } + if ($binding['complex']) { + return $this->complexTextOperator($binding); + } $hex = ''; foreach ($binding['cids'] as $cid) { $hex .= sprintf('%04X', $cid); } return '<' . $hex . '> Tj'; } + /** + * @param array{alias: string, cids: list, aliases: list, complex: bool, + * positions: list, x: float, y: float, fontSize: float, text: string} $binding + */ + private function complexTextOperator(array $binding): string + { + $codec = new UnicodeScalarCodec(); + $unicodeHex = 'FEFF'; + foreach ($codec->decode($binding['text']) as $scalar) { + $unicodeHex .= $codec->encodeUtf16Hex($scalar); + } + + $commands = ['/Span << /ActualText <' . $unicodeHex . '> >> BDC']; + $advance = 0; + $positions = []; + foreach ($binding['cids'] as $index => $cid) { + $glyph = $binding['positions'][$index]; + $scale = $binding['fontSize'] / 1000.0; + $positions[] = [ + 'logical' => $glyph['logical'], + 'visual' => $index, + 'x' => $binding['x'] + ($advance + $glyph['dx']) * $scale, + 'y' => $binding['y'] + $glyph['dy'] * $scale, + 'cid' => $cid, + 'alias' => $binding['aliases'][$index], + ]; + $advance += $glyph['advance']; + } + // PDF text operators may be emitted in logical order, regardless of + // absolute glyph placement, so text extraction retains original order. + usort($positions, static fn (array $first, array $second): int => + ($first['logical'] <=> $second['logical']) ?: ($first['visual'] <=> $second['visual'])); + $currentAlias = $binding['alias']; + foreach ($positions as $position) { + if ($position['alias'] !== $currentAlias) { + $commands[] = sprintf('/%s %F Tf', $position['alias'], $binding['fontSize']); + $currentAlias = $position['alias']; + } + $commands[] = sprintf( + '1 0 0 1 %F %F Tm <%04X> Tj', + $position['x'], + $position['y'], + $position['cid'], + ); + } + $commands[] = 'EMC'; + return implode("\n", $commands); + } } diff --git a/src/XObjectTemplateCompiler.php b/src/XObjectTemplateCompiler.php index 06ac80e..39da8e2 100644 --- a/src/XObjectTemplateCompiler.php +++ b/src/XObjectTemplateCompiler.php @@ -41,7 +41,10 @@ public function __construct( $colorParser ?? new ColorParser(), ); $this->layoutEngine = $layoutEngine ?? new LinearLayoutEngine( - fontMetrics: new StandardFontMetrics($this->documentBuilder->unicodeFonts()), + fontMetrics: new StandardFontMetrics( + $this->documentBuilder->unicodeFonts(), + $this->documentBuilder->complexShaper(), + ), ); } diff --git a/tests/Integration/UnicodeTextScenarioTest.php b/tests/Integration/UnicodeTextScenarioTest.php index ffaed0a..e70a6af 100644 --- a/tests/Integration/UnicodeTextScenarioTest.php +++ b/tests/Integration/UnicodeTextScenarioTest.php @@ -8,12 +8,28 @@ namespace LibreSign\XObjectTemplate\Tests\Integration; use InvalidArgumentException; +use LibreSign\XObjectTemplate\Dto\CompileResult; use LibreSign\XObjectTemplate\Dto\CompileRequest; +use LibreSign\XObjectTemplate\Layout\LayoutLine; +use LibreSign\XObjectTemplate\Layout\LayoutResult; +use LibreSign\XObjectTemplate\Layout\TextLineBreaker; use LibreSign\XObjectTemplate\Pdf\SinglePagePdfExporter; +use LibreSign\XObjectTemplate\Pdf\SignerPhpCoreXObjectResourceBuilder; +use LibreSign\XObjectTemplate\Pdf\StandardFontMetrics; +use LibreSign\XObjectTemplate\Pdf\HarfBuzzComplexTextShaper; +use LibreSign\XObjectTemplate\Pdf\TrueTypeFont; use LibreSign\XObjectTemplate\Pdf\TemplateDocumentBuilder; use LibreSign\XObjectTemplate\XObjectTemplateCompiler; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; +use SignerPHP\PdfCore\AppearanceXObject; +use SignerPHP\PdfCore\PdfDocument; +use SignerPHP\PdfCore\SignatureAppearance; +use SignerPHP\PdfCore\PdfValue\PDFValueReference; +use SignerPHP\PdfCore\PdfValue\PDFValueSimple; +use SignerPHP\PdfCore\Service\IncrementalUpdateWriter; +use SignerPHP\PdfCore\Service\PdfDocumentPreparer; +use Symfony\Component\Process\Process; final class UnicodeTextScenarioTest extends TestCase { @@ -27,7 +43,8 @@ public function testEmbeddedUnicodeFontsRoundTripThroughPdfResources( $compiler = new XObjectTemplateCompiler(documentBuilder: $builder); $result = $compiler->compile(new CompileRequest( - html: '
' . htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '
', + html: '
{{ signer }}
', + context: ['signer' => $text], width: 450, height: 84, )); @@ -52,23 +69,7 @@ public function testEmbeddedUnicodeFontsRoundTripThroughPdfResources( ); } - self::assertNotSame( - '', - trim((string) shell_exec('command -v pdftotext 2>/dev/null')), - 'Poppler pdftotext is required for extraction tests.' - ); - - $file = tempnam(sys_get_temp_dir(), 'libresign-unicode-'); - self::assertNotFalse($file); - try { - file_put_contents($file, $pdf); - $output = shell_exec('pdftotext -layout ' . escapeshellarg($file) . ' - 2>/dev/null'); - self::assertNotNull($output, 'Poppler pdftotext must be installed.'); - $actual = trim(str_replace(["\u{202A}", "\u{202B}", "\u{202C}"], '', $output), " \t\n\r\0\x0B\f"); - self::assertSame($text, $actual); - } finally { - unlink($file); - } + $this->assertPreviewAndAppearance($result, $pdf, $text); } /** @return iterable */ @@ -80,51 +81,397 @@ public static function unicodeScriptProvider(): iterable yield 'French accents' => ['text' => 'Signé par Renée', 'fontPath' => $dejavu]; yield 'Greek' => ['text' => 'Αλέξανδρος', 'fontPath' => $dejavu]; yield 'Cyrillic' => ['text' => 'Иван Иванов', 'fontPath' => $dejavu]; + yield 'Polish extended Latin' => ['text' => 'Łukasz Żółć', 'fontPath' => $dejavu]; + yield 'Turkish extended Latin' => ['text' => 'İpek Şahin', 'fontPath' => $dejavu]; + yield 'Ukrainian Cyrillic' => ['text' => 'Іван Петренко', 'fontPath' => $dejavu]; + yield 'supplementary Unicode scalar' => ['text' => '𐌀', 'fontPath' => $dejavu]; + yield 'Simplified Chinese' => ['text' => '简体中文', 'fontPath' => $droid]; + yield 'Traditional Chinese' => ['text' => '繁體中文', 'fontPath' => $droid]; + yield 'Japanese with kana' => ['text' => '山田 たろう', 'fontPath' => $droid]; yield 'Japanese CJK' => ['text' => '山田太郎', 'fontPath' => $droid]; yield 'escaped punctuation' => ['text' => 'Assinado (João) \\ Teste', 'fontPath' => $dejavu]; } - public function testInvalidUnconfiguredUnicodeCannotSilentlyCorruptPdf(): void + public function testIssue33SixLanguageExamplesShareOneValidFontResourceDocument(): void { - $compiler = new XObjectTemplateCompiler(); - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Unicode text requires an embedded TrueType font'); - $compiler->compile(new CompileRequest(html: '
Signé
')); + $texts = ['Signé par Renée', 'Αλέξανδρος', 'Иван Иванов', 'محمد', 'דוד', '山田太郎']; + $html = implode('', array_map( + static fn (string $line): string => + '
' . htmlspecialchars($line, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '
', + $texts, + )); + $compiler = new XObjectTemplateCompiler( + documentBuilder: (new TemplateDocumentBuilder())->withUnicodeFontFiles([ + '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', + '/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf', + ]), + ); + $result = $compiler->compile(new CompileRequest(html: $html, width: 600, height: 400)); + + self::assertSame(6, $result->metadata['line_count']); + self::assertArrayHasKey('U1', $result->resources['Font']); + self::assertArrayHasKey('U2', $result->resources['Font']); + $pdf = (new SinglePagePdfExporter())->export($result); + self::assertSame(2, substr_count($pdf, '/Subtype /CIDFontType2')); + self::assertSame(2, substr_count($pdf, '/ToUnicode')); + + $this->assertPreviewAndAppearance($result, $pdf, implode("\n", $texts)); } - public function testUnicodeFontWithoutRequiredGlyphIsRejected(): void + #[DataProvider('mixedFontProvider')] + public function testMixedScriptLineUsesAllRequiredFontResources(string $text): void { - $font = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'; - self::assertFileExists($font); + $paths = [ + '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', + '/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf', + ]; + $fonts = array_map(static fn (string $path): TrueTypeFont => new TrueTypeFont($path), $paths); + $metrics = new StandardFontMetrics($fonts); + self::assertGreaterThan(0.0, $metrics->measureString('F1', 12.0, $text)); $compiler = new XObjectTemplateCompiler( - documentBuilder: (new TemplateDocumentBuilder())->withUnicodeFontFiles([$font]), + documentBuilder: (new TemplateDocumentBuilder())->withUnicodeFontFiles($paths), ); + $result = $compiler->compile(new CompileRequest( + html: '
{{ signer }}
', + context: ['signer' => $text], + width: 500, + height: 90, + )); + self::assertSame(1, $result->metadata['line_count']); + self::assertArrayHasKey('U1', $result->resources['Font']); + self::assertArrayHasKey('U2', $result->resources['Font']); + self::assertStringContainsString('/U1 ', $result->contentStream); + self::assertStringContainsString('/U2 ', $result->contentStream); + $pdf = (new SinglePagePdfExporter())->export($result); + self::assertSame(2, substr_count($pdf, '/Subtype /CIDFontType2')); + $this->assertPreviewAndAppearance($result, $pdf, $text); + } + + /** @return iterable */ + public static function mixedFontProvider(): iterable + { + yield 'Latin and Japanese' => ['text' => 'Renée 山田太郎']; + yield 'adjacent Latin and Japanese' => ['text' => 'Renée山田太郎']; + yield 'LTR with Arabic and Japanese' => ['text' => 'Signed by محمد / 山田太郎']; + yield 'RTL with Japanese' => ['text' => 'محمد 山田太郎']; + yield 'Hebrew and Japanese' => ['text' => 'דוד 山田太郎']; + yield 'Greek and Simplified Chinese' => ['text' => 'Αλέξανδρος 简体中文']; + yield 'Cyrillic and Traditional Chinese' => ['text' => 'Иван Иванов 繁體中文']; + yield 'Latin to CJK and back to Latin' => ['text' => 'Renée 山田太郎 João']; + yield 'combining accent and Japanese' => ['text' => "e\u{0301} 山田太郎"]; + } + + #[DataProvider('missingCoverageProvider')] + public function testUnsupportedUnicodeFailsInsteadOfReplacingCharacters(string $text, array $fonts): void + { + $builder = (new TemplateDocumentBuilder())->withUnicodeFontFiles($fonts); + $compiler = new XObjectTemplateCompiler(documentBuilder: $builder); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Unicode text requires an embedded TrueType font'); - $compiler->compile(new CompileRequest(html: '
山田太郎
')); + $compiler->compile(new CompileRequest(html: '
{{ name }}
', context: ['name' => $text])); } - #[DataProvider('unsupportedComplexScriptProvider')] - public function testComplexScriptsRequireExternalShapingEngine(string $text): void + /** @return iterable}> */ + public static function missingCoverageProvider(): iterable + { + $dejavu = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'; + $droid = '/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf'; + yield 'no configured font' => ['text' => 'Signé', 'fonts' => []]; + yield 'missing Japanese glyphs' => ['text' => '山田太郎', 'fonts' => [$dejavu]]; + yield 'missing Arabic glyphs' => ['text' => 'محمد', 'fonts' => [$droid]]; + yield 'missing Hebrew glyphs' => ['text' => 'דוד', 'fonts' => [$droid]]; + yield 'partial coverage in a mixed line' => ['text' => 'Renée 山田太郎', 'fonts' => [$dejavu]]; + yield 'missing supplementary scalar' => ['text' => "\u{10FFFF}", 'fonts' => [$dejavu, $droid]]; + } + + #[DataProvider('unicodeInputProvider')] + public function testUnicodeTemplateInputPreservesDecodedText(string $html, array $context, string $expected): void { $compiler = new XObjectTemplateCompiler( documentBuilder: (new TemplateDocumentBuilder())->withUnicodeFontFiles([ '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', + '/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf', ]), ); - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Complex-script text requires'); - $compiler->compile(new CompileRequest(html: '
' . $text . '
')); + $result = $compiler->compile(new CompileRequest(html: $html, width: 450, height: 90, context: $context)); + $this->assertPreviewAndAppearance($result, (new SinglePagePdfExporter())->export($result), $expected); + } + + /** @return iterable, expected: string}> */ + public static function unicodeInputProvider(): iterable + { + yield 'named HTML entities' => ['
Signé par Renée
', [], 'Signé par Renée']; + yield 'decimal entities' => ['
山田太郎
', [], '山田太郎']; + yield 'hexadecimal entities' => ['
محمد
', [], 'محمد']; + yield 'supplementary-plane entity' => ['
𐌀
', [], '𐌀']; + yield 'escaped context text and PDF punctuation' => [ + '
{{ signer }}
', ['signer' => 'João & (山田)'], + 'João & (山田)', + ]; + } + + #[DataProvider('complexScriptWidthProvider')] + public function testComplexScriptWidthsUseShapedGlyphAdvances(string $text): void + { + $font = new TrueTypeFont('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'); + $shaped = (new HarfBuzzComplexTextShaper())->shape($text, $font); + $expected = 0; + foreach ($shaped as $glyph) { + $expected += $glyph['advance']; + } + self::assertNotSame(0, $expected); + self::assertEqualsWithDelta( + $expected * 12.0 / 1000, + (new StandardFontMetrics([$font]))->measureString('F1', 12.0, $text), + 0.000001, + ); + } + + /** @return iterable */ + public static function complexScriptWidthProvider(): iterable + { + yield 'Arabic with diacritics' => ['text' => 'مُحَمَّد']; + yield 'Hebrew with vowel marks' => ['text' => 'שָׁלוֹם']; + yield 'decomposed accent' => ['text' => "e\u{0301}"]; + } + + #[DataProvider('complexScriptProvider')] + public function testComplexScriptsRenderAndExtractOriginalUnicode(string $text): void + { + $font = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'; + self::assertFileExists($font); + $compiler = new XObjectTemplateCompiler( + documentBuilder: (new TemplateDocumentBuilder())->withUnicodeFontFiles([$font]), + ); + $result = $compiler->compile(new CompileRequest( + html: '
{{ signer }}
', + context: ['signer' => $text], + width: 500, + height: 90, + )); + $actualTextHex = 'FEFF'; + foreach (\LibreSign\XObjectTemplate\Pdf\TrueTypeFont::codepoints($text) as $scalar) { + $actualTextHex .= \LibreSign\XObjectTemplate\Pdf\TrueTypeFont::utf16Hex($scalar); + } + self::assertStringContainsString('/ActualText <' . $actualTextHex . '>', $result->contentStream); + self::assertStringContainsString('/U1 ', $result->contentStream); + + $pdf = (new SinglePagePdfExporter())->export($result); + self::assertStringContainsString('/Subtype /CIDFontType2', $pdf); + $this->assertPreviewAndAppearance($result, $pdf, $text); } /** @return iterable */ - public static function unsupportedComplexScriptProvider(): iterable + public static function complexScriptProvider(): iterable { + yield 'Hebrew (issue #33)' => ['text' => 'דוד']; yield 'Hebrew' => ['text' => 'שלום']; + yield 'Persian with space' => ['text' => 'علی رضا']; + yield 'Arabic with punctuation and digits' => ['text' => 'د. أحمد 123']; yield 'Arabic' => ['text' => 'محمد']; + yield 'Arabic lam-alef ligature' => ['text' => 'لا']; + yield 'Arabic diacritics' => ['text' => 'مُحَمَّد']; + yield 'Arabic and Latin mixed' => ['text' => 'Signed by محمد 123']; + yield 'Hebrew vowel marks' => ['text' => 'שָׁלוֹם']; + yield 'Hebrew and Latin mixed' => ['text' => 'Signed by שלום 123']; yield 'combining accent' => ['text' => "e\u{0301}"]; } + #[DataProvider('shapingReferenceProvider')] + public function testPdfGlyphIdsAndPositionsMatchNativeShaping(string $text, string $direction): void + { + $fontPath = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'; + $font = new TrueTypeFont($fontPath); + $process = new Process([ + 'hb-shape', '--no-glyph-names', '--output-format=json', '--font-size=1000', + '--direction=' . $direction, '--text=' . $text, $fontPath, + ], null, ['LC_ALL' => 'C.UTF-8'], null, 20.0); + $process->mustRun(); + $reference = json_decode($process->getOutput(), true, flags: JSON_THROW_ON_ERROR); + self::assertNotEmpty($reference); + $layout = new LayoutResult([new LayoutLine($text, 15.0, 40.0, 20.0, 'F1', '#000000')], []); + $result = (new TemplateDocumentBuilder())->withUnicodeFontFiles([$fontPath])->build( + new CompileRequest(html: '', width: 500, height: 90), + $layout, + hrtime(true), + ); + $document = new PdfDocument(); + $resources = (new SignerPhpCoreXObjectResourceBuilder())->materialize($document, $result->resources); + $type0 = $document->getObject($resources['Font']['U1']->asObjectReferenceOrNull()); + self::assertNotNull($type0); + $descendant = $document->getObject($type0->getField('DescendantFonts')->val()[0]->asObjectReferenceOrNull()); + self::assertNotNull($descendant); + $cidMap = $document->getObject($descendant->getField('CIDToGIDMap')->asObjectReferenceOrNull()); + self::assertNotNull($cidMap); + $glyphIds = unpack('n*', $cidMap->getStream(false)); + self::assertIsArray($glyphIds); + + // The PDF stores glyph positions in logical text order, while the + // native reference is in visual order. Compare actual GIDs and + // absolute positions, not just ActualText or the CMap text. + $expected = []; + $advance = 0; + foreach ($reference as $glyph) { + $expected[] = [ + $glyph['g'], + sprintf('%.6F', 15.0 + ($advance + $glyph['dx']) * 0.02), + sprintf('%.6F', 40.0 + $glyph['dy'] * 0.02), + ]; + $advance += $glyph['ax']; + } + preg_match_all( + '/1 0 0 1 (-?\d+\.\d+) (-?\d+\.\d+) Tm <([0-9A-F]{4})> Tj/', + $result->contentStream, + $matches, + PREG_SET_ORDER, + ); + $actual = []; + foreach ($matches as [, $x, $y, $cid]) { + $actual[] = [$glyphIds[hexdec($cid) + 1], $x, $y]; + } + sort($actual); + sort($expected); + self::assertSame($expected, $actual); + self::assertEqualsWithDelta( + $advance * 0.02, + (new StandardFontMetrics([$font]))->measureString('F1', 20.0, $text), + 0.000001, + ); + } + + /** @return iterable */ + public static function shapingReferenceProvider(): iterable + { + yield 'Arabic joined letters' => ['محمد', 'rtl']; + yield 'Arabic ligature' => ['لا', 'rtl']; + yield 'Arabic stacked marks' => ['مُحَمَّد', 'rtl']; + yield 'Persian' => ['علی', 'rtl']; + yield 'Hebrew issue example' => ['דוד', 'rtl']; + yield 'Hebrew vowel marks' => ['שָׁלוֹם', 'rtl']; + yield 'Latin combining acute' => ["e\u{0301}", 'ltr']; + yield 'Latin multiple combining marks' => ["a\u{0308}\u{0301}", 'ltr']; + yield 'Greek combining accent' => ["α\u{0301}", 'ltr']; + yield 'Cyrillic combining breve' => ["и\u{0306}", 'ltr']; + } + + #[DataProvider('graphemeWrapProvider')] + public function testAutoWrapNeverSeparatesCombiningMarksFromTheirBase(string $text, array $expected): void + { + $font = new TrueTypeFont('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'); + $breaker = new TextLineBreaker(new StandardFontMetrics([$font])); + self::assertSame($expected, $breaker->wrap($text, 1.0, 'F1', 12.0, 'auto', 'normal')); + } + + /** @return iterable}> */ + public static function graphemeWrapProvider(): iterable + { + yield 'decomposed Latin accents' => ["e\u{0301}e\u{0301}", ["e\u{0301}-", "e\u{0301}"]]; + yield 'Hebrew stacked and single vowel marks' => ['שָׁלֹ', ['שָׁ-', 'לֹ']]; + yield 'Arabic vowel marks' => ['مُحَ', ['مُ-', 'حَ']]; + } + + private function assertPreviewAndAppearance(CompileResult $result, string $preview, string $expected): void + { + $appearance = $this->createAppearancePdf($result); + [$previewText, $previewRaster] = $this->readPdfEvidence($preview); + [$appearanceText, $appearanceRaster] = $this->readPdfEvidence($appearance); + foreach ([$previewText, $appearanceText] as $extracted) { + self::assertSame( + $expected, + implode("\n", array_map( + static fn (string $line): string => self::normalizePopplerVisualBidi(trim($line)), + explode("\n", trim($extracted, " \t\n\r\0\x0B\f")), + )), + 'The actual PDF must preserve the logical Unicode text, not just contain a CMap.', + ); + } + $parts = explode("\n", $previewRaster, 3); + self::assertSame('P4', $parts[0]); + self::assertCount(3, $parts); + self::assertNotSame('', trim($parts[2], "\0"), 'The rendered page must contain visible ink.'); + self::assertSame( + hash('sha256', $previewRaster), + hash('sha256', $appearanceRaster), + 'The actual destination appearance must render exactly like the standalone XObject.', + ); + } + + private function createAppearancePdf(CompileResult $result): string + { + $blank = (new SinglePagePdfExporter())->export(new CompileResult('', [], $result->bbox)); + $document = (new PdfDocumentPreparer())->prepare($blank); + $page = $document->getPageInfo()->getPage(0); + self::assertNotNull($page); + $annotation = $document->createObject([ + 'Type' => '/Annot', + 'Subtype' => '/Widget', + 'FT' => '/Sig', + 'F' => 132, + 'P' => new PDFValueReference($page->getOid()), + ]); + // Materialize through the public callback before attaching the resources. + // This exercises pdf-core v0.1.2 too; the automatic callback constructor + // integration requires the separately released pdf-core resource-builder API. + $builder = new SignerPhpCoreXObjectResourceBuilder(); + $resources = ($builder->resourcesBuilder())($document, $result->resources); + SignatureAppearance::new() + ->withRect($result->bbox) + ->withPdfDocument($document) + ->withAnnotationObject($annotation) + ->withPageRotate(new PDFValueSimple(0)) + ->withXObject(new AppearanceXObject($result->contentStream, $resources)) + ->generate(); + $page['Annots'] = [new PDFValueReference($annotation->getOid())]; + $document->addObject($page); + $pdf = (new IncrementalUpdateWriter())->write($document)->raw(); + self::assertTrue(str_starts_with($pdf, $blank), 'The previous PDF revision must remain unchanged.'); + // PdfDocument and PageInfo retain references to one another. Release + // their cycles before the next data set allocates several embedded fonts. + unset($document); + gc_collect_cycles(); + return $pdf; + } + + /** @return array{string, string} */ + private function readPdfEvidence(string $pdf): array + { + $path = tempnam(sys_get_temp_dir(), 'unicode-appearance-'); + self::assertNotFalse($path); + try { + self::assertSame(strlen($pdf), file_put_contents($path, $pdf)); + return [ + $this->runPdfTool(['pdftotext', '-raw', $path, '-']), + $this->runPdfTool(['pdftoppm', '-mono', '-r', '144', '-singlefile', $path]), + ]; + } finally { + unlink($path); + } + } + + /** @param list $command */ + private function runPdfTool(array $command): string + { + $process = new Process($command, null, ['LC_ALL' => 'C.UTF-8'], null, 20.0); + $process->mustRun(); + return $process->getOutput(); + } + + private static function normalizePopplerVisualBidi(string $text): string + { + // Poppler's pdftotext -raw emits RTL runs in visual order with RLE/PDF + // controls even for semantic PDF ActualText. Normalize only its + // presentation convention; the PDF itself retains logical Unicode. + $normalized = preg_replace_callback( + '/\x{202B}(.*?)\x{202C}/u', + static function (array $match): string { + $scalars = preg_split('//u', $match[1], -1, PREG_SPLIT_NO_EMPTY); + return $scalars === false ? '' : implode('', array_reverse($scalars)); + }, + $text, + ); + return $normalized ?? $text; + } + public function testAsciiRetainsLegacyFontStreamAndResources(): void { $result = (new XObjectTemplateCompiler())->compile(new CompileRequest(html: '
ASCII test
')); diff --git a/tests/Unit/Pdf/ComplexTextPositioningTest.php b/tests/Unit/Pdf/ComplexTextPositioningTest.php new file mode 100644 index 0000000..990414f --- /dev/null +++ b/tests/Unit/Pdf/ComplexTextPositioningTest.php @@ -0,0 +1,103 @@ +glyphs; + } + + public function shapeWithFonts(string $text, array $fonts): array + { + throw new \LogicException('This test only exercises one font.'); + } + }; + $resources = new UnicodeTextResources( + [new LayoutLine('שלום', 10.0, 20.0, 12.0, 'F1', '#000000')], + [$font], + $shaper, + ); + + $stream = $resources->textOperator(0, 'שלום', new PdfEscaper()); + $previousOffset = -1; + foreach ($expected as $command) { + $offset = strpos($stream, (string) $command); + self::assertNotFalse($offset, 'Each positioned glyph must be present in the PDF stream.'); + self::assertGreaterThan($previousOffset, $offset, 'Glyphs must be emitted in logical Unicode order.'); + $previousOffset = $offset; + } + self::assertSame('U1', $resources->aliasFor(0, 'F1')); + } + + /** @return iterable}> */ + public static function positionsProvider(): iterable + { + $g = static fn (int $scalar, int $logical, int $advance, int $dx, int $dy): array => [ + 'glyph' => $scalar, + 'glyphId' => 3, + 'unicode' => [$scalar], + 'advance' => $advance, + 'dx' => $dx, + 'dy' => $dy, + 'cluster' => $logical, + 'logical' => $logical, + ]; + yield 'glyphs in same cluster preserve their visual order' => [ + 'shaped' => [ + $g(0x05E9, 0, 350, 0, 0), + $g(0x05E9, 0, 0, 35, 160), + $g(0x05DC, 1, 300, -40, 0), + $g(0x05D5, 2, 500, 0, 0), + $g(0x05DD, 3, 450, 0, 0), + ], + 'expected' => [ + '1 0 0 1 10.000000 20.000000 Tm <0001> Tj', + '1 0 0 1 14.620000 21.920000 Tm <0001> Tj', + '1 0 0 1 13.720000 20.000000 Tm <0002> Tj', + '1 0 0 1 17.800000 20.000000 Tm <0003> Tj', + '1 0 0 1 23.800000 20.000000 Tm <0004> Tj', + ], + ]; + yield 'RTL glyph ordering, variable advances and offsets' => [ + 'shaped' => [ + $g(0x05DD, 3, 500, 50, 75), + $g(0x05D5, 2, 700, -25, -50), + $g(0x05DC, 1, 600, 0, 0), + $g(0x05E9, 0, 800, 0, 0), + ], + 'expected' => [ + '1 0 0 1 31.600000 20.000000 Tm <0004> Tj', + '1 0 0 1 24.400000 20.000000 Tm <0003> Tj', + '1 0 0 1 15.700000 19.400000 Tm <0002> Tj', + '1 0 0 1 10.600000 20.900000 Tm <0001> Tj', + ], + ]; + } +} diff --git a/tests/Unit/Pdf/FriBidiParagraphMapperTest.php b/tests/Unit/Pdf/FriBidiParagraphMapperTest.php new file mode 100644 index 0000000..b1bd17b --- /dev/null +++ b/tests/Unit/Pdf/FriBidiParagraphMapperTest.php @@ -0,0 +1,170 @@ +runs($input, $characters)); + self::assertCount(1, $calls); + self::assertSame($input . "\n", $calls[0][1]); + self::assertSame('fribidi-test', $calls[0][0][0]); + foreach (['--novisual', '--ltov', '--vtol', '--levels', '--charset=UTF-8', '--nopad'] as $option) { + self::assertContains($option, $calls[0][0]); + } + } + + /** @return iterable, inverse: list, levels: list, expected: list}> */ + public static function runsProvider(): iterable + { + yield 'latin and cyrillic split' => [ + 'AЖ', [0, 1], [0, 1], [0, 0], + [ + ['text' => 'A', 'rtl' => false, 'visual' => 0, 'start' => 0], + ['text' => 'Ж', 'rtl' => false, 'visual' => 1, 'start' => 1], + ], + ]; + yield 'Greek and East Asian scripts are itemized separately' => [ + 'AΩ山あア한', [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 0, 0, 0, 0, 0], + [ + ['text' => 'A', 'rtl' => false, 'visual' => 0, 'start' => 0], + ['text' => 'Ω', 'rtl' => false, 'visual' => 1, 'start' => 1], + ['text' => '山', 'rtl' => false, 'visual' => 2, 'start' => 2], + ['text' => 'あ', 'rtl' => false, 'visual' => 3, 'start' => 3], + ['text' => 'ア', 'rtl' => false, 'visual' => 4, 'start' => 4], + ['text' => '한', 'rtl' => false, 'visual' => 5, 'start' => 5], + ], + ]; + yield 'hebrew arabic same rtl embedding level' => [ + 'שم', [1, 0], [1, 0], [1, 1], + [ + ['text' => 'م', 'rtl' => true, 'visual' => 0, 'start' => 1], + ['text' => 'ש', 'rtl' => true, 'visual' => 1, 'start' => 0], + ], + ]; + yield 'mixed direction reverse run order' => [ + 'ABשم', [0, 1, 3, 2], [0, 1, 3, 2], [0, 0, 1, 1], + [ + ['text' => 'AB', 'rtl' => false, 'visual' => 0, 'start' => 0], + ['text' => 'م', 'rtl' => true, 'visual' => 2, 'start' => 3], + ['text' => 'ש', 'rtl' => true, 'visual' => 3, 'start' => 2], + ], + ]; + yield 'punctuation initial merges into following script' => [ + '!A', [0, 1], [0, 1], [0, 0], + [['text' => '!A', 'rtl' => false, 'visual' => 0, 'start' => 0]], + ]; + yield 'initial punctuation inherits first script then splits second' => [ + '!AЖ', [0, 1, 2], [0, 1, 2], [0, 0, 0], + [ + ['text' => '!A', 'rtl' => false, 'visual' => 0, 'start' => 0], + ['text' => 'Ж', 'rtl' => false, 'visual' => 2, 'start' => 2], + ], + ]; + yield 'punctuation after latin' => [ + 'A!', [0, 1], [0, 1], [0, 0], + [['text' => 'A!', 'rtl' => false, 'visual' => 0, 'start' => 0]], + ]; + yield 'two embedding levels with same Latin script' => [ + 'AB', [1, 0], [1, 0], [0, 1], + [ + ['text' => 'B', 'rtl' => true, 'visual' => 0, 'start' => 1], + ['text' => 'A', 'rtl' => false, 'visual' => 1, 'start' => 0], + ], + ]; + yield 'embedding level three is right to left' => [ + 'AB', [1, 0], [1, 0], [3, 3], + [['text' => 'AB', 'rtl' => true, 'visual' => 0, 'start' => 0]], + ]; + yield 'inherited Arabic mark does not create its own script run' => [ + "A\u{064E}", [0, 1], [0, 1], [0, 0], + [['text' => "A\u{064E}", 'rtl' => false, 'visual' => 0, 'start' => 0]], + ]; + yield 'script-specific Hebrew mark stays attached to a foreign base' => [ + "A\u{05B8}", [0, 1], [0, 1], [0, 0], + [['text' => "A\u{05B8}", 'rtl' => false, 'visual' => 0, 'start' => 0]], + ]; + yield 'inherited marks do not split Greek and Cyrillic runs' => [ + "α\u{0301}и\u{0306}", [0, 1, 2, 3], [0, 1, 2, 3], [0, 0, 0, 0], + [ + ['text' => "α\u{0301}", 'rtl' => false, 'visual' => 0, 'start' => 0], + ['text' => "и\u{0306}", 'rtl' => false, 'visual' => 2, 'start' => 2], + ], + ]; + yield 'combining mark inherits preceding script' => [ + "e\u{0301}", [0, 1], [0, 1], [0, 0], + [['text' => "e\u{0301}", 'rtl' => false, 'visual' => 0, 'start' => 0]], + ]; + yield 'even embedding level two is left to right' => [ + 'AB', [0, 1], [0, 1], [2, 2], + [['text' => 'AB', 'rtl' => false, 'visual' => 0, 'start' => 0]], + ]; + yield 'one neutral scalar' => [ + '!', [0], [0], [0], + [['text' => '!', 'rtl' => false, 'visual' => 0, 'start' => 0]], + ]; + } + + #[DataProvider('invalidMappingsProvider')] + public function testRejectsMalformedBidiMaps(string $output): void + { + $runner = static fn (): string => $output; + $this->expectException(InvalidArgumentException::class); + (new FriBidiParagraphMapper('fri', $runner))->runs('AB', ['A', 'B']); + } + + /** @return iterable */ + public static function invalidMappingsProvider(): iterable + { + yield 'missing header' => ["0 1\n0 1\n0 1\n0 0"]; + yield 'extra line' => ["Base direction: L\n0 1\n0 1\n0 0\nEXTRA"]; + yield 'missing line' => ["Base direction: L\n0 1\n0 1"]; + yield 'map too short' => ["Base direction: L\n0\n0 1\n0 0"]; + yield 'negative index' => ["Base direction: L\n0 -1\n0 1\n0 0"]; + yield 'noninteger' => ["Base direction: L\n0 x\n0 1\n0 0"]; + yield 'nonnumeric final level' => ["Base direction: L\n0 1\n0 1\n0 x"]; + yield 'nonnumeric first level' => ["Base direction: L\n0 1\n0 1\nx 0"]; + yield 'nonnumeric inverse' => ["Base direction: L\n0 1\n0 x\n0 0"]; + yield 'wrong inverse' => ["Base direction: L\n1 0\n0 1\n0 0"]; + yield 'duplicate index' => ["Base direction: L\n0 0\n0 1\n0 0"]; + yield 'out of range index' => ["Base direction: L\n0 2\n0 1\n0 0"]; + yield 'surplus level' => ["Base direction: L\n0 1\n0 1\n0 0 0"]; + } +} diff --git a/tests/Unit/Pdf/HarfBuzzComplexTextShaperTest.php b/tests/Unit/Pdf/HarfBuzzComplexTextShaperTest.php new file mode 100644 index 0000000..8a77614 --- /dev/null +++ b/tests/Unit/Pdf/HarfBuzzComplexTextShaperTest.php @@ -0,0 +1,236 @@ +withFont(static function (TrueTypeFont $font) use (&$commands, $runner): void { + $shaper = new HarfBuzzComplexTextShaper('harfbuzz-test', 'fribidi-test', $runner); + $result = $shaper->shape("e\u{0301}", $font); + self::assertSame([[ + 'glyph' => 0x65, 'cluster' => 0, 'glyphId' => 4, + 'unicode' => [0x65, 0x301], + 'advance' => 530, 'dx' => 12, 'dy' => -3, 'logical' => 0, + ]], $result); + self::assertCount(2, $commands); + self::assertSame("e\u{0301}\n", $commands[0][1]); + }); + } + + public function testSegmentsOpposingBidiRunsAndPreservesClusterOrigins(): void + { + $runner = static function (array $args): string { + if ($args[0] === 'fri') { + return "Base direction: L\n0 1 2 4 3\n0 1 2 4 3\n0 0 0 1 1\n"; + } + $text = substr((string) $args[5], strlen('--text=')); + if ($text === 'A B') { + return '[{"g":10,"cl":0,"ax":500,"dx":0,"dy":0},' + . '{"g":3,"cl":1,"ax":250,"dx":0,"dy":0},' + . '{"g":11,"cl":2,"ax":500,"dx":0,"dy":0}]'; + } + self::assertSame('של', $text); + self::assertContains('--direction=rtl', $args); + return '[{"g":12,"cl":1,"ax":550,"dx":0,"dy":0},' + . '{"g":13,"cl":0,"ax":650,"dx":0,"dy":0}]'; + }; + $this->withFont(static function (TrueTypeFont $font) use ($runner): void { + $shaped = (new HarfBuzzComplexTextShaper('hb', 'fri', $runner))->shape('A Bשל', $font); + self::assertSame([10, 3, 11, 12, 13], array_column($shaped, 'glyphId')); + self::assertSame([0, 1, 2, 4, 3], array_column($shaped, 'logical')); + self::assertSame([[65], [32], [66], [0x5DC], [0x5E9]], array_column($shaped, 'unicode')); + }); + } + + public function testMultipleGlyphsInOneClusterRetainOriginalTextOnce(): void + { + $runner = static function (array $args): string { + if ($args[0] === 'fri') { + return "Base direction: L\n0 1\n0 1\n0 0\n"; + } + return '[{"g":12,"cl":0,"ax":400,"dx":0,"dy":0},' + . '{"g":13,"cl":0,"ax":0,"dx":-50,"dy":200}]'; + }; + $this->withFont(static function (TrueTypeFont $font) use ($runner): void { + $shaped = (new HarfBuzzComplexTextShaper('hb', 'fri', $runner))->shape("e\u{0301}", $font); + self::assertSame([0x65, 0x301], $shaped[0]['unicode']); + self::assertSame([0x200B], $shaped[1]['unicode']); + self::assertSame([0, 0], array_column($shaped, 'logical')); + self::assertSame(-50, $shaped[1]['dx']); + self::assertSame(200, $shaped[1]['dy']); + }); + } + + public function testEmptyStringDoesNotSpawnProcesses(): void + { + $runner = static function (): never { + throw new \LogicException('No process should be started for empty text.'); + }; + $this->withFont(static function (TrueTypeFont $font) use ($runner): void { + self::assertSame([], (new HarfBuzzComplexTextShaper('hb', 'fri', $runner))->shape('', $font)); + }); + } + + #[DataProvider('badUnicodeProvider')] + public function testRejectsUnsafeInput(string $text, string $error): void + { + $runner = static function (): never { + throw new \LogicException('Rejected text must not invoke a process.'); + }; + $this->withFont(function (TrueTypeFont $font) use ($text, $error, $runner): void { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage($error); + (new HarfBuzzComplexTextShaper('hb', 'fri', $runner))->shape($text, $font); + }); + } + + /** @return iterable */ + public static function badUnicodeProvider(): iterable + { + yield 'invalid UTF-8' => ["\xFF", 'UTF-8']; + yield 'newline' => ["A\nB", 'single line']; + yield 'nul' => ["A\0B", 'single line']; + yield 'too many scalars' => [str_repeat('A', 4097), 'at most 4096']; + } + + #[DataProvider('badBidiProvider')] + public function testRejectsUntrustedFriBidiOutput(string $output): void + { + $runner = static fn (array $args): string => $output; + $this->withFont(function (TrueTypeFont $font) use ($runner): void { + $this->expectException(InvalidArgumentException::class); + (new HarfBuzzComplexTextShaper('hb', 'fri', $runner))->shape('AB', $font); + }); + } + + /** @return iterable */ + public static function badBidiProvider(): iterable + { + yield 'empty' => ['']; + yield 'not four lines' => ["Base direction: L\n0 1\n0 1"]; + yield 'invalid header' => ["direction: L\n0 1\n0 1\n0 0"]; + yield 'wrong map size' => ["Base direction: L\n0\n0 1\n0 0"]; + yield 'nonnumeric index' => ["Base direction: L\n0 X\n0 1\n0 0"]; + yield 'duplicate index' => ["Base direction: L\n0 0\n0 1\n0 0"]; + } + + #[DataProvider('badGlyphProvider')] + public function testRejectsUntrustedHarfBuzzOutput(string $output): void + { + $runner = static fn (array $args): string => $args[0] === 'fri' + ? "Base direction: L\n0\n0\n0\n" + : $output; + $this->withFont(function (TrueTypeFont $font) use ($runner): void { + $this->expectException(InvalidArgumentException::class); + (new HarfBuzzComplexTextShaper('hb', 'fri', $runner))->shape('A', $font); + }); + } + + /** @return iterable */ + public static function badGlyphProvider(): iterable + { + yield 'malformed JSON' => ['not-json']; + yield 'empty list' => ['[]']; + yield 'not a list' => ['{"g":3}']; + yield 'not a glyph' => ['[5]']; + yield 'missing position' => ['[{"g":3,"cl":0}]']; + yield 'string position' => ['[{"g":3,"cl":"0","ax":10,"dx":0,"dy":0}]']; + yield 'glyph zero' => ['[{"g":0,"cl":0,"ax":10,"dx":0,"dy":0}]']; + yield 'glyph overflow' => ['[{"g":65536,"cl":0,"ax":10,"dx":0,"dy":0}]']; + yield 'missing first cluster' => ['[{"g":3,"cl":1,"ax":10,"dx":0,"dy":0}]']; + yield 'negative cluster' => ['[{"g":3,"cl":-1,"ax":10,"dx":0,"dy":0}]']; + } + + public function testNativeExecutableFailureIsReported(): void + { + $this->withFont(function (TrueTypeFont $font): void { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('working HarfBuzz/FriBidi runtime is required'); + (new HarfBuzzComplexTextShaper('missing-fribidi-binary-for-test'))->shape('A', $font); + }); + } + + public function testAcceptsMaximumUnicodeScalarLength(): void + { + $count = 4096; + $characters = implode(' ', range(0, $count - 1)); + $levels = str_repeat('0 ', $count); + $runner = static fn (array $arguments): string => $arguments[0] === 'fri' + ? "Base direction: L\n" . $characters . "\n" . $characters . "\n" . $levels . "\n" + : '[{"g":3,"cl":0,"ax":600,"dx":0,"dy":0}]'; + $this->withFont(static function (TrueTypeFont $font) use ($runner, $count): void { + $result = (new HarfBuzzComplexTextShaper('hb', 'fri', $runner)) + ->shape(str_repeat('A', $count), $font); + self::assertCount(1, $result); + self::assertCount($count, $result[0]['unicode']); + }); + } + + #[DataProvider('shapingRunBoundaries')] + public function testLimitsNumberOfBidiShapingRuns(int $count, bool $rejected): void + { + $indexes = implode(' ', range(0, $count - 1)); + $levels = implode(' ', array_map(static fn (int $index): int => $index % 2, range(0, $count - 1))); + $runner = static fn (array $arguments): string => $arguments[0] === 'fri' + ? "Base direction: L\n" . $indexes . "\n" . $indexes . "\n" . $levels . "\n" + : '[{"g":3,"cl":0,"ax":600,"dx":0,"dy":0}]'; + $this->withFont(function (TrueTypeFont $font) use ($runner, $count, $rejected): void { + if ($rejected) { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('safe number of shaping runs'); + } + $actual = (new HarfBuzzComplexTextShaper('hb', 'fri', $runner)) + ->shape(str_repeat('A', $count), $font); + self::assertCount($count, $actual); + }); + } + + /** @return iterable */ + public static function shapingRunBoundaries(): iterable + { + yield 'maximum accepted' => [32, false]; + yield 'one above maximum' => [33, true]; + } + + /** @param Closure(TrueTypeFont):void $callback */ + private function withFont(Closure $callback): void + { + $path = tempnam(sys_get_temp_dir(), 'complex-text-font-'); + self::assertNotFalse($path); + try { + file_put_contents($path, SyntheticTrueTypeFontTest::makeFont()); + $callback(new TrueTypeFont($path)); + } finally { + unlink($path); + } + } +} diff --git a/tests/Unit/Pdf/HarfBuzzRunShaperTest.php b/tests/Unit/Pdf/HarfBuzzRunShaperTest.php new file mode 100644 index 0000000..7090c80 --- /dev/null +++ b/tests/Unit/Pdf/HarfBuzzRunShaperTest.php @@ -0,0 +1,110 @@ + 65, 'cluster' => 0, 'glyphId' => 65535, + 'unicode' => [65], 'advance' => 801, 'dx' => 17, 'dy' => -27], + ['glyph' => 66, 'cluster' => 1, 'glyphId' => 3, + 'unicode' => [66], 'advance' => 250, 'dx' => 0, 'dy' => 0], + ], $shaper->shape('/tmp/font.ttf', 'AB', true)); + self::assertSame([[ + ['hb-test', '--no-glyph-names', '--output-format=json', '--font-size=1000', + '--direction=rtl', '--text=AB', '/tmp/font.ttf'], + null, + ]], $calls); + } + + public function testSortsOutOfOrderClustersAndPreservesOriginalUnicode(): void + { + $runner = static fn (): string => + '[{"g":42,"cl":2,"ax":400,"dx":0,"dy":0},' + . '{"g":41,"cl":1,"ax":250,"dx":0,"dy":0},' + . '{"g":40,"cl":0,"ax":350,"dx":0,"dy":0}]'; + $shaped = (new HarfBuzzRunShaper('hb', $runner, new UnicodeScalarCodec())) + ->shape('/font.ttf', 'AéB', false); + self::assertSame([2, 1, 0], array_column($shaped, 'cluster')); + self::assertSame([[66], [0xE9], [65]], array_column($shaped, 'unicode')); + } + + public function testMultipleGlyphsFromSameClusterPreserveSequenceOnlyOnce(): void + { + $runner = static fn (): string => + '[{"g":10,"cl":0,"ax":400,"dx":0,"dy":0},' + . '{"g":11,"cl":0,"ax":0,"dx":-12,"dy":90}]'; + $shaped = (new HarfBuzzRunShaper('hb', $runner, new UnicodeScalarCodec())) + ->shape('/font.ttf', "e\u{301}", false); + self::assertSame([[101, 769], [0x200B]], array_column($shaped, 'unicode')); + self::assertSame([10, 11], array_column($shaped, 'glyphId')); + } + + public function testReusedClusterAfterAnotherClusterDoesNotDuplicateItsUnicode(): void + { + $runner = static fn (): string => + '[{"g":10,"cl":0,"ax":400,"dx":0,"dy":0},' + . '{"g":20,"cl":1,"ax":300,"dx":0,"dy":0},' + . '{"g":11,"cl":0,"ax":0,"dx":-10,"dy":120}]'; + $shaped = (new HarfBuzzRunShaper('hb', $runner, new UnicodeScalarCodec())) + ->shape('/font.ttf', 'AB', false); + self::assertSame([0, 1, 0], array_column($shaped, 'cluster')); + self::assertSame([[65], [66], [0x200B]], array_column($shaped, 'unicode')); + } + + #[DataProvider('malformedOutputProvider')] + public function testRejectsMalformedGlyphOutput(string $output, string $expectedError): void + { + $runner = static fn (): string => $output; + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage($expectedError); + (new HarfBuzzRunShaper('hb', $runner, new UnicodeScalarCodec())) + ->shape('/font.ttf', 'AB', false); + } + + /** @return iterable */ + public static function malformedOutputProvider(): iterable + { + yield 'invalid json' => ['not-json', 'invalid JSON']; + yield 'empty glyph result' => ['[]', 'no glyphs']; + yield 'json object' => ['{"g":12}', 'no glyphs']; + yield 'primitive' => ['true', 'no glyphs']; + yield 'null result' => ['null', 'no glyphs']; + yield 'non glyph' => ['[5]', 'invalid glyph position']; + yield 'missing glyph' => ['[{"cl":0,"ax":5,"dx":0,"dy":0}]', 'invalid glyph position']; + yield 'string g' => ['[{"g":"3","cl":0,"ax":5,"dx":0,"dy":0}]', 'noninteger glyph position']; + yield 'string cl' => ['[{"g":3,"cl":"0","ax":5,"dx":0,"dy":0}]', 'noninteger glyph position']; + yield 'string ax' => ['[{"g":3,"cl":0,"ax":"5","dx":0,"dy":0}]', 'noninteger glyph position']; + yield 'string dx' => ['[{"g":3,"cl":0,"ax":5,"dx":"0","dy":0}]', 'noninteger glyph position']; + yield 'string dy' => ['[{"g":3,"cl":0,"ax":5,"dx":0,"dy":"0"}]', 'noninteger glyph position']; + yield 'zero glyph' => ['[{"g":0,"cl":0,"ax":5,"dx":0,"dy":0}]', 'invalid glyph index']; + yield 'negative glyph' => ['[{"g":-1,"cl":0,"ax":5,"dx":0,"dy":0}]', 'invalid glyph index']; + yield 'glyph above max' => ['[{"g":65536,"cl":0,"ax":5,"dx":0,"dy":0}]', 'invalid glyph index']; + yield 'cluster missing start zero' => ['[{"g":3,"cl":1,"ax":5,"dx":0,"dy":0}]', 'incomplete Unicode cluster']; + yield 'negative cluster' => ['[{"g":3,"cl":-1,"ax":5,"dx":0,"dy":0}]', 'incomplete Unicode cluster']; + yield 'cluster beyond string length' => [ + '[{"g":3,"cl":0,"ax":5,"dx":0,"dy":0},{"g":4,"cl":3,"ax":4,"dx":0,"dy":0}]', + 'invalid Unicode cluster boundary', + ]; + } +} diff --git a/tests/Unit/Pdf/NativeTextCommandRunnerTest.php b/tests/Unit/Pdf/NativeTextCommandRunnerTest.php new file mode 100644 index 0000000..a8ba0fd --- /dev/null +++ b/tests/Unit/Pdf/NativeTextCommandRunnerTest.php @@ -0,0 +1,55 @@ +run( + [PHP_BINARY, '-r', 'echo getenv("LC_ALL"), ":", stream_get_contents(STDIN);'], + "e\u{0301}\n", + ); + self::assertSame("C.UTF-8:e\u{0301}\n", $result); + } finally { + if ($originalEnv === null) { + unset($_ENV['LC_ALL']); + } else { + $_ENV['LC_ALL'] = $originalEnv; + } + if ($original === false) { + putenv('LC_ALL'); + } else { + putenv('LC_ALL=' . $original); + } + } + } + + public function testNativeCommandFailsClosedWithoutShellInterpretation(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('working HarfBuzz/FriBidi runtime'); + (new NativeTextCommandRunner())->run(['definitely-not-an-executable-issue33'], null); + } + + public function testNativeCommandRejectsFailedExitStatus(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('working HarfBuzz/FriBidi runtime'); + (new NativeTextCommandRunner())->run([PHP_BINARY, '-r', 'exit(7);'], null); + } +} diff --git a/tests/Unit/Pdf/TemplateDocumentBuilderTest.php b/tests/Unit/Pdf/TemplateDocumentBuilderTest.php index 5b77f38..464c2eb 100644 --- a/tests/Unit/Pdf/TemplateDocumentBuilderTest.php +++ b/tests/Unit/Pdf/TemplateDocumentBuilderTest.php @@ -13,6 +13,8 @@ use LibreSign\XObjectTemplate\Layout\LayoutLine; use LibreSign\XObjectTemplate\Layout\LayoutResult; use LibreSign\XObjectTemplate\Pdf\TemplateDocumentBuilder; +use LibreSign\XObjectTemplate\Pdf\ComplexTextShaperInterface; +use LibreSign\XObjectTemplate\Pdf\TrueTypeFont; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use ReflectionMethod; @@ -67,6 +69,50 @@ public function testBuildCreatesDocumentPayloadParts(): void self::assertArrayHasKey('render_ms', $result->metadata); } + public function testOneBuildSharesUnicodeShapingBetweenStreamAndResources(): void + { + $shaper = new class implements ComplexTextShaperInterface { + public int $calls = 0; + + public function shape(string $text, TrueTypeFont $font): array + { + $this->calls++; + $result = []; + foreach (TrueTypeFont::codepoints($text) as $index => $codepoint) { + $result[] = [ + 'glyph' => $codepoint, + 'glyphId' => $font->glyphFor($codepoint), + 'unicode' => [$codepoint], + 'advance' => 500, + 'dx' => 0, + 'dy' => 0, + 'cluster' => $index, + 'logical' => $index, + ]; + } + return $result; + } + + public function shapeWithFonts(string $text, array $fonts): array + { + throw new \LogicException('This test only exercises one font.'); + } + }; + $builder = (new TemplateDocumentBuilder(complexShaper: $shaper)) + ->withUnicodeFontFiles(['/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf']); + $layout = new LayoutResult( + lines: [new LayoutLine('שלום', 10.0, 20.0, 12.0, 'F1', '#000000')], + images: [], + ); + + $result = $builder->build(new CompileRequest(html: '

שלום

'), $layout, 0); + + self::assertSame(1, $shaper->calls, 'Shaping must not run twice for one compiled document.'); + self::assertStringContainsString('/ActualText contentStream); + self::assertSame('U1', array_key_last($result->resources['Font'])); + self::assertCount(4, $result->resources['Font']['U1']['__Mappings']); + } + public function testBuildMetadataDefaultsNodeCountAndUsesRoundedMilliseconds(): void { $builder = new TemplateDocumentBuilder(clock: static fn (): int => 2_000_000); diff --git a/tests/Unit/Pdf/TemporaryFontFileTest.php b/tests/Unit/Pdf/TemporaryFontFileTest.php new file mode 100644 index 0000000..a033469 --- /dev/null +++ b/tests/Unit/Pdf/TemporaryFontFileTest.php @@ -0,0 +1,106 @@ +withFont("FONT\x00DATA", static function (string $temporary) use (&$path): string { + $path = $temporary; + self::assertFileExists($temporary); + self::assertSame("FONT\x00DATA", file_get_contents($temporary)); + self::assertSame(0600, fileperms($temporary) & 0777); + return hash_file('sha256', $temporary); + }); + self::assertSame(hash('sha256', "FONT\x00DATA"), $result); + self::assertNotNull($path); + self::assertFileDoesNotExist($path); + } + + public function testRemovesTemporaryFileWhenCallbackThrows(): void + { + $path = null; + try { + (new TemporaryFontFile())->withFont('FONT', static function (string $temporary) use (&$path): never { + $path = $temporary; + self::assertFileExists($temporary); + throw new RuntimeException('Worker failed.'); + }); + self::fail('Exception must propagate.'); + } catch (RuntimeException $exception) { + self::assertSame('Worker failed.', $exception->getMessage()); + } + self::assertNotNull($path); + self::assertFileDoesNotExist($path); + } + + public function testRejectsFailedTemporaryFileCreationWithoutInvokingWorker(): void + { + $file = new TemporaryFontFile(static fn (): false => false); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Unable to prepare temporary font data'); + $file->withFont('FONT', static function (): never { + throw new RuntimeException('Must not execute callback.'); + }); + } + + #[DataProvider('badWritesProvider')] + public function testRejectsIncompleteTemporaryFileWrite(int|false $writeResult): void + { + $path = tempnam(sys_get_temp_dir(), 'tempfont-fail-'); + self::assertNotFalse($path); + try { + $file = new TemporaryFontFile( + static fn (): string => $path, + static fn (string $name, string $bytes): int|false => $writeResult, + ); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Unable to write temporary font data'); + $file->withFont('FONT', static function (): never { + throw new RuntimeException('Must not execute callback.'); + }); + } finally { + self::assertFileDoesNotExist($path); + } + } + + /** @return iterable */ + public static function badWritesProvider(): iterable + { + yield 'failed write' => [false]; + yield 'zero bytes' => [0]; + yield 'partial write' => [3]; + yield 'more than written' => [5]; + } + + public function testCustomWriteCallbackReceivesExactData(): void + { + $path = tempnam(sys_get_temp_dir(), 'tempfont-success-'); + self::assertNotFalse($path); + $received = null; + $file = new TemporaryFontFile( + static fn (): string => $path, + static function (string $name, string $data) use (&$received): int { + $received = [$name, $data]; + return file_put_contents($name, $data); + }, + ); + self::assertSame(4, $file->withFont('DATA', static fn (string $name): int => filesize($name))); + self::assertSame([$path, 'DATA'], $received); + self::assertFileDoesNotExist($path); + } +} diff --git a/tests/Unit/Pdf/UnicodeFontPdfWriterTest.php b/tests/Unit/Pdf/UnicodeFontPdfWriterTest.php index 6d1fe91..5872d8c 100644 --- a/tests/Unit/Pdf/UnicodeFontPdfWriterTest.php +++ b/tests/Unit/Pdf/UnicodeFontPdfWriterTest.php @@ -198,6 +198,55 @@ public static function invalidResourceProvider(): iterable '__Mappings' => [['glyph' => 65, 'unicode' => [-1]]]]]; } + #[DataProvider('invalidShapedGlyphProvider')] + public function testRejectsInvalidShapedGlyphId(mixed $glyphId): void + { + $this->withFont(function (TrueTypeFont $font) use ($glyphId): void { + $objects = []; + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid shaped TrueType glyph index'); + try { + $this->writer()->create($objects, [ + '__TrueTypeFont' => $font, + '__Mappings' => [['glyph' => 0x41, 'glyphId' => $glyphId, 'unicode' => [0x41]]], + ]); + } finally { + self::assertSame([], $objects, 'Invalid glyphs must not create partial PDF objects.'); + } + }); + } + + /** @return iterable */ + public static function invalidShapedGlyphProvider(): iterable + { + yield 'negative index' => [-1]; + yield 'zero index' => [0]; + yield 'string' => ['2']; + yield 'float' => [2.0]; + yield 'null' => [null]; + yield 'highest impossible TrueType index' => [65535]; + yield 'over 16 bit' => [65536]; + } + + public function testShapedGlyphIdOverridesCmapAndEmbedsItsExactCid(): void + { + $this->withFont(function (TrueTypeFont $font): void { + self::assertSame(3, $font->glyphFor(0x41)); + $objects = []; + $this->writer()->create($objects, [ + '__TrueTypeFont' => $font, + '__Mappings' => [['glyph' => 0x41, 'glyphId' => 2, 'unicode' => [0x41]]], + ]); + [$cidDictionary, $cidMap] = unserialize($objects[2], ['allowed_classes' => false]); + self::assertSame([], $cidDictionary); + self::assertSame(pack('nn', 0, 2), $cidMap); + $cidFont = json_decode($objects[5], true, flags: JSON_THROW_ON_ERROR); + self::assertSame([1, [$font->widthForGlyph(2)]], $cidFont['W']); + [$unicodeDictionary, $toUnicode] = unserialize($objects[3], ['allowed_classes' => false]); + self::assertStringContainsString('<0001> <0041>', $toUnicode); + }); + } + private function writer(): UnicodeFontPdfWriter { return new UnicodeFontPdfWriter( diff --git a/tests/Unit/Pdf/UnicodeTextResourcesTest.php b/tests/Unit/Pdf/UnicodeTextResourcesTest.php index 2b65aa3..80dae9a 100644 --- a/tests/Unit/Pdf/UnicodeTextResourcesTest.php +++ b/tests/Unit/Pdf/UnicodeTextResourcesTest.php @@ -10,8 +10,12 @@ use InvalidArgumentException; use LibreSign\XObjectTemplate\Layout\LayoutLine; use LibreSign\XObjectTemplate\Pdf\PdfEscaper; +use LibreSign\XObjectTemplate\Pdf\HarfBuzzComplexTextShaper; +use LibreSign\XObjectTemplate\Pdf\StandardFontMetrics; +use LibreSign\XObjectTemplate\Pdf\UnicodeFontRunSelector; use LibreSign\XObjectTemplate\Pdf\TrueTypeFont; use LibreSign\XObjectTemplate\Pdf\UnicodeTextResources; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; final class UnicodeTextResourcesTest extends TestCase @@ -86,6 +90,151 @@ public function testFailsWhenNoFontCanCoverRequiredUnicodeScalars(): void }); } + public function testDirectFallbackGroupsFontsAndUsesConsistentPositionsAndWidths(): void + { + $this->withFonts([0xE9, 0x3A9], function (array $fonts): void { + $text = 'éêΩé'; + self::assertSame([ + ['fontIndex' => 0, 'text' => 'éê', 'start' => 0], + ['fontIndex' => 1, 'text' => 'Ω', 'start' => 2], + ['fontIndex' => 0, 'text' => 'é', 'start' => 3], + ], (new UnicodeFontRunSelector())->runs($text, $fonts)); + self::assertEqualsWithDelta( + 31.2, + (new StandardFontMetrics($fonts))->measureString('F1', 12.0, $text), + 0.000001, + ); + $resources = new UnicodeTextResources([$this->line($text)], $fonts); + self::assertSame('U1', $resources->aliasFor(0, 'F1')); + self::assertSame([ + ['glyph' => 0xE9, 'unicode' => [0xE9]], + ['glyph' => 0xEA, 'unicode' => [0xEA]], + ], $resources->fonts()['U1']['__Mappings']); + self::assertSame([['glyph' => 0x3A9, 'unicode' => [0x3A9]]], $resources->fonts()['U2']['__Mappings']); + self::assertSame(implode("\n", [ + '/Span << /ActualText >> BDC', + '1 0 0 1 0.000000 0.000000 Tm <0001> Tj', + '1 0 0 1 7.800000 0.000000 Tm <0002> Tj', + '/U2 12.000000 Tf', + '1 0 0 1 15.600000 0.000000 Tm <0001> Tj', + '/U1 12.000000 Tf', + '1 0 0 1 23.400000 0.000000 Tm <0001> Tj', + 'EMC', + ]), $resources->textOperator(0, $text, new PdfEscaper())); + }); + } + + public function testFallbackNeverSeparatesBaseAndCombiningMark(): void + { + $this->withFonts([0x65, 0x301], static function (array $fonts): void { + self::assertSame(3, $fonts[0]->glyphFor(0x65)); + self::assertSame(3, $fonts[1]->glyphFor(0x301)); + self::assertNull((new UnicodeFontRunSelector())->runs("e\u{0301}", $fonts)); + $fonts[] = new TrueTypeFont('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'); + self::assertSame([ + ['fontIndex' => 2, 'text' => "e\u{0301}", 'start' => 0], + ], (new UnicodeFontRunSelector())->runs("e\u{0301}", $fonts)); + }); + } + + public function testComplexFallbackKeepsJoiningContextAndVisualOrder(): void + { + $this->withFonts([0x628, 0x62D], static function (array $fonts): void { + $text = 'بحب'; + $commands = []; + $runner = static function (array $args, ?string $input) use (&$commands, $fonts, $text): string { + if ($args[0] === 'fri') { + self::assertSame($text . "\n", $input); + return "Base direction: R\n2 1 0\n2 1 0\n1 1 1\n"; + } + self::assertContains('--direction=rtl', $args); + $path = $args[array_key_last($args)]; + $fontData = file_get_contents($path); + $commands[] = [$args, $path]; + $glyph = $args[5] === '--text=ب' ? 3 : 4; + self::assertSame($fonts[$glyph === 3 ? 0 : 1]->fontData(), $fontData); + return sprintf('[{"g":%d,"cl":0,"ax":650,"dx":0,"dy":0}]', $glyph); + }; + $shaper = new HarfBuzzComplexTextShaper('hb', 'fri', $runner); + $glyphs = $shaper->shapeWithFonts($text, $fonts); + self::assertSame([2, 1, 0], array_column($glyphs, 'logical')); + self::assertSame([0, 1, 0], array_column($glyphs, 'fontIndex')); + self::assertSame([[0x628], [0x62D], [0x628]], array_column($glyphs, 'unicode')); + self::assertCount(3, $commands); + self::assertContains('--text-before=بح', $commands[0][0]); + self::assertNotContains('--text-after=', $commands[0][0]); + self::assertContains('--text-before=ب', $commands[1][0]); + self::assertContains('--text-after=ب', $commands[1][0]); + self::assertContains('--text-after=حب', $commands[2][0]); + self::assertNotContains('--text-before=', $commands[2][0]); + foreach ($commands as [, $path]) { + self::assertFileDoesNotExist($path); + } + }); + } + + public function testComplexFallbackRejectsUncoveredTextBeforeInvokingHarfBuzz(): void + { + $this->withFonts([0x628], function (array $fonts): void { + $runner = static function (array $args): string { + self::assertSame('fri', $args[0]); + return "Base direction: R\n0\n0\n1\n"; + }; + $shaper = new HarfBuzzComplexTextShaper('hb', 'fri', $runner); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Unicode text requires an embedded TrueType font'); + $shaper->shapeWithFonts('ح', $fonts); + }); + } + + public function testComplexFallbackTranslatesRunRelativeClustersToParagraphIndices(): void + { + $this->withFonts([0x41, 0x628], static function (array $fonts): void { + $runner = static function (array $args): string { + if ($args[0] === 'fri') { + return "Base direction: L\n0 2 1\n0 2 1\n0 1 1\n"; + } + if ($args[5] === '--text=A') { + return '[{"g":3,"cl":0,"ax":600,"dx":0,"dy":0}]'; + } + self::assertSame('--text=بة', $args[5]); + return '[{"g":4,"cl":1,"ax":600,"dx":0,"dy":0},{"g":3,"cl":0,"ax":600,"dx":0,"dy":0}]'; + }; + $glyphs = (new HarfBuzzComplexTextShaper('hb', 'fri', $runner))->shapeWithFonts('Aبة', $fonts); + self::assertSame([0, 2, 1], array_column($glyphs, 'logical')); + self::assertSame([0, 1, 1], array_column($glyphs, 'fontIndex')); + }); + } + + #[DataProvider('fontRunLimitProvider')] + public function testComplexFallbackLimitsTotalFontRunsNotJustBidiRuns(int $count, bool $reject): void + { + $this->withFonts([0x628, 0x62D], function (array $fonts) use ($count, $reject): void { + $indexes = implode(' ', range($count - 1, 0)); + $runner = static function (array $args) use ($indexes, $count): string { + if ($args[0] === 'fri') { + return "Base direction: R\n" . $indexes . "\n" . $indexes . "\n" . str_repeat('1 ', $count) . "\n"; + } + return '[{"g":3,"cl":0,"ax":650,"dx":0,"dy":0}]'; + }; + $shaper = new HarfBuzzComplexTextShaper('hb', 'fri', $runner); + $text = str_repeat('بح', intdiv($count, 2)) . ($count % 2 === 1 ? 'ب' : ''); + if ($reject) { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('safe number of shaping runs'); + } + $glyphs = $shaper->shapeWithFonts($text, $fonts); + self::assertCount($count, $glyphs); + }); + } + + /** @return iterable */ + public static function fontRunLimitProvider(): iterable + { + yield 'maximum accepted' => [32, false]; + yield 'one above maximum' => [33, true]; + } + private function line(string $text): LayoutLine { return new LayoutLine($text, 0.0, 0.0, 12.0, 'F1', '#000000');