#!/usr/bin/env perl
use 5.010;
use strict;
use warnings;

our (@COLLECTIONS, $ESCAPE, $PER_LINE);

BEGIN {
    @COLLECTIONS = (
        { file => 'Adobe-Japan1-UCS2', name => 'japan1', ordering => 'Japan1', id => 'PDFMAKE_CID_COLLECTION_JAPAN1' },
        { file => 'Adobe-Korea1-UCS2', name => 'korea1', ordering => 'Korea1', id => 'PDFMAKE_CID_COLLECTION_KOREA1' },
        { file => 'Adobe-GB1-UCS2',    name => 'gb1',    ordering => 'GB1',    id => 'PDFMAKE_CID_COLLECTION_GB1' },
        { file => 'Adobe-CNS1-UCS2',   name => 'cns1',   ordering => 'CNS1',   id => 'PDFMAKE_CID_COLLECTION_CNS1' },
        { file => 'Adobe-KR-UCS2',     name => 'kr',     ordering => 'KR',     id => 'PDFMAKE_CID_COLLECTION_KR' },
    );
    $ESCAPE   = 0xFFFF;
    $PER_LINE = 12;
}

my ($source, $out) = @ARGV;
die "usage: tools/cidcompile <pdf2unicode directory> <output .c>\n"
    unless defined $source && defined $out && -d $source;

my $body = '';
for my $collection (@COLLECTIONS) {
    my $path = "$source/$collection->{file}";
    my ($map, $version) = read_cmap($path);
    $collection->{version} = $version;
    $body .= emit_collection($collection, $map);
}

open my $fh, '>', $out or die "$out: $!";
print {$fh} header(), $body, footer();
close $fh or die "$out: $!";

sub utf16_to_codepoints {
    my ($hex) = @_;
    die "odd UTF-16 string <$hex>" if length($hex) % 4;
    my @units = unpack 'n*', pack 'H*', $hex;
    my @codepoints;
    while (@units) {
        my $unit = shift @units;
        if ($unit >= 0xD800 && $unit <= 0xDBFF) {
            die "unpaired surrogate in <$hex>"
                unless @units && $units[0] >= 0xDC00 && $units[0] <= 0xDFFF;
            $unit = 0x10000 + (($unit - 0xD800) << 10) + (shift(@units) - 0xDC00);
        }
        elsif ($unit >= 0xDC00 && $unit <= 0xDFFF) {
            die "unpaired surrogate in <$hex>";
        }
        push @codepoints, $unit;
    }
    return \@codepoints;
}

sub read_cmap {
    my ($path) = @_;
    open my $in, '<', $path or die "$path: $!";
    my (%map, $mode, $version);
    while (my $line = <$in>) {
        $version = $1 if $line =~ m{^/CMapVersion\s+(\S+)};
        if ($line =~ /^\d+\s+begin(bfchar|bfrange)\b/) { $mode = $1; next }
        if ($line =~ /^end(?:bfchar|bfrange)\b/)       { $mode = undef; next }
        next unless $mode;
        if ($mode eq 'bfchar') {
            $line =~ /^<([0-9a-fA-F]{4})>\s*<([0-9a-fA-F]+)>\s*$/
                or die "$path line $.: not a bfchar entry";
            $map{ hex $1 } = utf16_to_codepoints($2);
            next;
        }
        $line =~ /^<([0-9a-fA-F]{4})>\s*<([0-9a-fA-F]{4})>\s*<([0-9a-fA-F]+)>\s*$/
            or die "$path line $.: not a bfrange entry";
        my ($low, $high, $start) = (hex $1, hex $2, $3);
        my $stem = substr $start, 0, -4;
        my $last = hex substr $start, -4;
        for my $cid ($low .. $high) {
            my $unit = $last + $cid - $low;
            die "$path line $.: range runs past the last code unit" if $unit > 0xFFFF;
            $map{$cid} = utf16_to_codepoints($stem . sprintf '%04X', $unit);
        }
    }
    close $in;
    die "$path: no mappings" unless %map;
    die "$path: no /CMapVersion" unless defined $version;
    return (\%map, $version);
}

sub emit_collection {
    my ($collection, $map) = @_;
    my $name  = $collection->{name};
    my $count = (sort { $b <=> $a } keys %$map)[0] + 1;
    my (@direct, @sequences, @pool);
    for my $cid (0 .. $count - 1) {
        my $codepoints = $map->{$cid};
        if (!$codepoints || (@$codepoints == 1 && $codepoints->[0] == 0)) {
            push @direct, 0;
        }
        elsif (@$codepoints == 1 && $codepoints->[0] < $ESCAPE) {
            push @direct, $codepoints->[0];
        }
        else {
            die "$name: sequence pool passes 65535 entries" if @pool > 0xFFFF;
            push @direct, $ESCAPE;
            push @sequences, [ $cid, scalar @pool ];
            push @pool, scalar(@$codepoints), @$codepoints;
        }
    }
    $collection->{count} = $count;

    my $text = sprintf "/* %s, CMap version %s: %d CIDs, %d of them through the sequence table. */\n\n",
        $collection->{file}, $collection->{version}, $count, scalar @sequences;
    $text .= "static const uint16_t ${name}_direct[$count] = {\n";
    $text .= rows(map { sprintf '0x%04X', $_ } @direct);
    $text .= "};\n\n";
    $text .= sprintf "static const cid_sequence_t %s_sequences[%d] = {\n", $name, scalar @sequences;
    $text .= rows(map { sprintf '{%d,%d}', @$_ } @sequences);
    $text .= "};\n\n";
    $text .= sprintf "static const uint32_t %s_pool[%d] = {\n", $name, scalar @pool;
    $text .= rows(map { $_ < 16 ? $_ : sprintf '0x%04X', $_ } @pool);
    $text .= "};\n\n";
    $collection->{sequence_count} = scalar @sequences;
    return $text;
}

sub rows {
    my @items = @_;
    my $text = '';
    while (my @row = splice @items, 0, $PER_LINE) {
        $text .= '    ' . join(',', @row) . ",\n";
    }
    return $text;
}

sub header {
    return <<'C';
/*
 * pdfmake_cid_unicode.c - Unicode for the CIDs of the Adobe CJK character
 * collections: Adobe-Japan1, Adobe-Korea1, Adobe-GB1, Adobe-CNS1, Adobe-KR.
 *
 * GENERATED by tools/cidcompile from the pdf2unicode files of
 * https://github.com/adobe-type-tools/mapping-resources-pdf
 * Do not edit: change the tool and run it again.
 *
 * The tables are data from those files, which carry this notice:
 *
 * Copyright 1990-2023 Adobe. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * Neither the name of Adobe nor the names of its contributors may be
 * used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "pdfmake_cid_unicode.h"
#include <string.h>

/* A CID whose text is not one BMP codepoint: `offset` indexes the pool,
 * where a count is followed by that many codepoints. */
typedef struct {
    uint16_t cid;
    uint16_t offset;
} cid_sequence_t;

/* In a direct table 0 is a CID with no text and CID_ESCAPE one whose text
 * is in the sequence table. Every other value is the codepoint. */
#define CID_ESCAPE 0xFFFF

C
}

sub footer {
    my $rows = join '', map {
        sprintf "    { \"%s\", %d, %s_direct, %d, %s_sequences, %d, %s_pool },\n",
            $_->{ordering}, length $_->{ordering}, $_->{name}, $_->{count},
            $_->{name}, $_->{sequence_count}, $_->{name}
    } @COLLECTIONS;
    my $order = join ', ', map { $_->{id} } @COLLECTIONS;
    return <<"C";
typedef struct {
    const char           *ordering;
    size_t                ordering_len;
    const uint16_t       *direct;
    uint32_t              count;
    const cid_sequence_t *sequences;
    uint32_t              sequence_count;
    const uint32_t       *pool;
} cid_collection_t;

/* In the order of the PDFMAKE_CID_COLLECTION_* numbers, from 1:
 * $order. */
static const cid_collection_t collections[] = {
$rows};

#define COLLECTION_COUNT (sizeof(collections) / sizeof(collections[0]))

int pdfmake_cid_collection_by_ordering(const char *ordering, size_t len)
{
    size_t i;
    if (!ordering) return PDFMAKE_CID_COLLECTION_NONE;
    for (i = 0; i < COLLECTION_COUNT; i++) {
        if (collections[i].ordering_len == len
            && memcmp(collections[i].ordering, ordering, len) == 0)
            return (int)i + 1;
    }
    return PDFMAKE_CID_COLLECTION_NONE;
}

uint32_t pdfmake_cid_collection_size(int collection)
{
    if (collection < 1 || (size_t)collection > COLLECTION_COUNT) return 0;
    return collections[collection - 1].count;
}

size_t pdfmake_cid_to_unicode(int collection, uint32_t cid,
                              uint32_t *out, size_t max)
{
    const cid_collection_t *table;
    uint32_t low, high;
    uint16_t value;

    if (!out || max == 0) return 0;
    if (collection < 1 || (size_t)collection > COLLECTION_COUNT) return 0;
    table = &collections[collection - 1];
    if (cid >= table->count) return 0;

    value = table->direct[cid];
    if (value == 0) return 0;
    if (value != CID_ESCAPE) {
        out[0] = value;
        return 1;
    }

    low = 0;
    high = table->sequence_count;
    while (low < high) {
        uint32_t middle = low + (high - low) / 2;
        if (table->sequences[middle].cid < cid) low = middle + 1;
        else high = middle;
    }
    if (low < table->sequence_count && table->sequences[low].cid == cid) {
        const uint32_t *entry = table->pool + table->sequences[low].offset;
        size_t count = entry[0], i;
        if (count > max) count = max;
        for (i = 0; i < count; i++) out[i] = entry[1 + i];
        return count;
    }
    return 0;
}
C
}

__END__

=head1 NAME

cidcompile - compile Adobe's CID to Unicode files into the C tables PDF::Make ships

=head1 SYNOPSIS

    git clone https://github.com/adobe-type-tools/mapping-resources-pdf
    tools/cidcompile mapping-resources-pdf/pdf2unicode src/pdfmake_cid_unicode.c

=head1 DESCRIPTION

A CID font names its glyphs by number in a character collection. When such a
font has no ToUnicode map, the text of a glyph is whatever the collection says
that number is. Adobe publishes that as one file per collection, and this turns
the five of them into F<src/pdfmake_cid_unicode.c>.

This runs on the author's machine only. Its output is part of the dist, so
building PDF::Make never needs it or the files it reads.

Each collection becomes a table of one 16 bit value per CID. Zero is a CID with
no text. 0xFFFF sends the lookup to a second table, sorted by CID, for the CIDs
whose text is a codepoint above U+FFFF or a run of several codepoints. Any other
value is the codepoint itself.

The order of the collections in this file is the order of the
PDFMAKE_CID_COLLECTION numbers in F<include/pdfmake_cid_unicode.h>. Adding one
means adding it to both.

The tool dies on anything it does not recognise in a file, so a change of format
upstream is seen here and not in the extracted text.

=head1 SOURCE

The tables in the dist were built from commit
2dd5e53fb74a01718b9dfd448a0d1cce6fff2aa5 of mapping-resources-pdf. The files are
Copyright 1990-2023 Adobe and are under the BSD 3-Clause licence, which the
generated file reproduces.

=cut
