summaryrefslogtreecommitdiff
path: root/Build/source/texk/dvipdf-x/xsrc
diff options
context:
space:
mode:
Diffstat (limited to 'Build/source/texk/dvipdf-x/xsrc')
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/bmpimage.c466
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/cff.c1484
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/cff.h156
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/cff_dict.c720
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/cidtype0.c2075
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/cidtype2.c1126
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/dpxfile.c1175
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/dpxfile.h70
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/dpxutil.c651
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/dpxutil.h105
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/dvi.c2737
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/dvi.h103
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/dvipdfmx.c992
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/epdf.c906
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/epdf.h41
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/error.c92
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/error.h46
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/fontmap.c1513
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/fontmap.h109
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/jpegimage.c916
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/jpegimage.h36
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/mpost.c1671
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pdfcolor.c1530
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pdfcolor.h102
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pdfdev.c2000
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pdfdev.h231
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pdfdoc.c2331
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pdfdoc.h137
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pdfdraw.c1842
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pdfdraw.h172
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pdfencrypt.c539
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pdfnames.c488
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pdfnames.h52
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pdfobj.c3170
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pdfobj.h196
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pdfparse.c1078
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pdfximage.c924
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pdfximage.h92
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pngimage.c1013
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/pngimage.h43
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/sfnt.c652
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/spc_color.c192
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/spc_dvips.c1075
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/spc_html.c944
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/spc_pdfm.c2115
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/spc_tpic.c1151
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/spc_util.c796
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/spc_util.h44
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/specials.c619
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/tfm.c1209
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/truetype.c1009
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/tt_aux.c294
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/tt_aux.h39
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/tt_cmap.c1940
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/tt_cmap.h80
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/tt_glyf.c671
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/tt_post.c276
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/tt_table.c505
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/type0.c687
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/type0.h58
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/type1.c805
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/type1c.c750
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/vf.c1042
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/xbb.c511
-rw-r--r--Build/source/texk/dvipdf-x/xsrc/xbb.h31
65 files changed, 50625 insertions, 0 deletions
diff --git a/Build/source/texk/dvipdf-x/xsrc/bmpimage.c b/Build/source/texk/dvipdf-x/xsrc/bmpimage.c
new file mode 100644
index 00000000000..e09e37b238c
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/bmpimage.c
@@ -0,0 +1,466 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/*
+ * BMP SUPPORT:
+ */
+
+#include "system.h"
+#include "error.h"
+#include "mem.h"
+
+#include "pdfobj.h"
+
+#include "bmpimage.h"
+
+#define DIB_FILE_HEADER_SIZE 14
+#define DIB_CORE_HEADER_SIZE 14
+#define DIB_INFO_HEADER_SIZE 40
+
+#define DIB_COMPRESS_NONE 0
+#define DIB_COMPRESS_RLE8 1
+#define DIB_COMPRESS_RLE4 2
+
+#define DIB_HEADER_SIZE_MAX (DIB_FILE_HEADER_SIZE+DIB_INFO_HEADER_SIZE)
+
+static long read_raster_rle8 (unsigned char *data_ptr,
+ long width, long height, FILE *fp);
+static long read_raster_rle4 (unsigned char *data_ptr,
+ long width, long height, FILE *fp);
+
+int
+check_for_bmp (FILE *fp)
+{
+ unsigned char sigbytes[2];
+
+ if (!fp)
+ return 0;
+
+ rewind(fp);
+ if (fread(sigbytes, 1, sizeof(sigbytes), fp) != sizeof(sigbytes) ||
+ sigbytes[0] != 'B' || sigbytes[1] != 'M')
+ return 0;
+ else
+ return 1;
+
+ return 0;
+}
+
+int
+bmp_include_image (pdf_ximage *ximage, FILE *fp)
+{
+ pdf_obj *stream, *stream_dict, *colorspace;
+ ximage_info info;
+ unsigned char buf[DIB_HEADER_SIZE_MAX+4];
+ unsigned char *p;
+ long offset, hsize, compression;
+ long psize; /* Bytes per palette color: 3 for OS2, 4 for Win */
+ unsigned short bit_count; /* Bits per pix */
+ int num_palette, flip;
+ int i;
+ unsigned long biXPelsPerMeter, biYPelsPerMeter;
+
+ pdf_ximage_init_image_info(&info);
+
+ stream = stream_dict = colorspace = NULL;
+ p = buf;
+
+ rewind(fp);
+ if (fread(buf, 1, DIB_FILE_HEADER_SIZE + 4, fp)
+ != DIB_FILE_HEADER_SIZE + 4) {
+ WARN("Could not read BMP file header...");
+ }
+
+ if (p[0] != 'B' || p[1] != 'M') {
+ WARN("File not starting with \'B\' \'M\'... Not a BMP file?");
+ return -1;
+ }
+ p += 2;
+
+#define ULONG_LE(b) ((b)[0] + ((b)[1] << 8) +\
+ ((b)[2] << 16) + ((b)[3] << 24))
+#define USHORT_LE(b) ((b)[0] + ((b)[1] << 8))
+
+ /* fsize = ULONG_LE(p); */ p += 4;
+ if (ULONG_LE(p) != 0) {
+ WARN("Not a BMP file???");
+ return -1;
+ }
+ p += 4;
+ offset = ULONG_LE(p); p += 4;
+
+ /* info header */
+ hsize = ULONG_LE(p); p += 4;
+ if (fread(p, sizeof(char), hsize - 4, fp) != hsize - 4) {
+ WARN("Could not read BMP file header...");
+ return -1;
+ }
+ flip = 1;
+ if (hsize == DIB_CORE_HEADER_SIZE) {
+ info.width = USHORT_LE(p); p += 2;
+ info.height = USHORT_LE(p); p += 2;
+ if (USHORT_LE(p) != 1) {
+ WARN("Unknown bcPlanes value in BMP COREHEADER.");
+ return -1;
+ }
+ p += 2;
+ bit_count = USHORT_LE(p); p += 2;
+ compression = DIB_COMPRESS_NONE;
+ psize = 3;
+ } else if (hsize == DIB_INFO_HEADER_SIZE) {
+ info.width = ULONG_LE(p); p += 4;
+ info.height = ULONG_LE(p); p += 4;
+ if (USHORT_LE(p) != 1) {
+ WARN("Unknown biPlanes value in BMP INFOHEADER.");
+ return -1;
+ }
+ p += 2;
+ bit_count = USHORT_LE(p); p += 2;
+ compression = ULONG_LE(p); p += 4;
+ /* ignore biSizeImage */ p += 4;
+ biXPelsPerMeter = ULONG_LE(p); p += 4;
+ biYPelsPerMeter = ULONG_LE(p); p += 4;
+ info.xdensity = 72.0 / (biXPelsPerMeter * 0.0254);
+ info.ydensity = 72.0 / (biYPelsPerMeter * 0.0254);
+ if (info.height < 0) {
+ info.height = -info.height;
+ flip = 0;
+ }
+ psize = 4;
+ } else {
+ WARN("Unknown BMP header type.");
+ return -1;
+ }
+
+ if (bit_count < 24) {
+ if (bit_count != 1 &&
+ bit_count != 4 && bit_count != 8) {
+ WARN("Unsupported palette size: %ld", bit_count);
+ return -1;
+ }
+ num_palette = (offset - hsize - DIB_FILE_HEADER_SIZE) / psize;
+ info.bits_per_component = bit_count;
+ info.num_components = 1;
+ } else if (bit_count == 24) { /* full color */
+ num_palette = 1; /* dummy */
+ info.bits_per_component = 8;
+ info.num_components = 3;
+ } else {
+ WARN("Unkown BMP bitCount: %ld", bit_count);
+ return -1;
+ }
+
+ if (info.width == 0 || info.height == 0 || num_palette < 1) {
+ WARN("Invalid BMP file: width=%ld, height=%ld, #palette=%d",
+ info.width, info.height, num_palette);
+ return -1;
+ }
+
+ stream = pdf_new_stream(STREAM_COMPRESS);
+ stream_dict = pdf_stream_dict(stream);
+
+ if (bit_count < 24) {
+ pdf_obj *lookup;
+ unsigned char *palette, bgrq[4];
+
+ palette = NEW(num_palette*3+1, unsigned char);
+ for (i = 0; i < num_palette; i++) {
+ if (fread(bgrq, 1, psize, fp) != psize) {
+ WARN("Reading file failed...");
+ RELEASE(palette);
+ return -1;
+ }
+ /* BGR data */
+ palette[3*i ] = bgrq[2];
+ palette[3*i+1] = bgrq[1];
+ palette[3*i+2] = bgrq[0];
+ }
+ lookup = pdf_new_string(palette, num_palette*3);
+ RELEASE(palette);
+
+ colorspace = pdf_new_array();
+ pdf_add_array(colorspace, pdf_new_name("Indexed"));
+ pdf_add_array(colorspace, pdf_new_name("DeviceRGB"));
+ pdf_add_array(colorspace, pdf_new_number(num_palette-1));
+ pdf_add_array(colorspace, lookup);
+ } else {
+ colorspace = pdf_new_name("DeviceRGB");
+ }
+ pdf_add_dict(stream_dict, pdf_new_name("ColorSpace"), colorspace);
+
+ /* Raster data of BMP is four-byte aligned. */
+ {
+ long rowbytes, n;
+ unsigned char *stream_data_ptr = NULL;
+
+ rowbytes = (info.width * bit_count + 7) / 8;
+
+ seek_absolute(fp, offset);
+ if (compression == DIB_COMPRESS_NONE) {
+ long dib_rowbytes;
+ int padding;
+
+ padding = (rowbytes % 4) ? 4 - (rowbytes % 4) : 0;
+ dib_rowbytes = rowbytes + padding;
+ stream_data_ptr = NEW(rowbytes*info.height + padding,
+ unsigned char);
+ for (n = 0; n < info.height; n++) {
+ p = stream_data_ptr + n * rowbytes;
+ if (fread(p, 1, dib_rowbytes, fp) != dib_rowbytes) {
+ WARN("Reading BMP raster data failed...");
+ pdf_release_obj(stream);
+ RELEASE(stream_data_ptr);
+ return -1;
+ }
+ }
+ } else if (compression == DIB_COMPRESS_RLE8) {
+ stream_data_ptr = NEW(rowbytes*info.height, unsigned char);
+ if (read_raster_rle8(stream_data_ptr,
+ info.width, info.height, fp) < 0) {
+ WARN("Reading BMP raster data failed...");
+ pdf_release_obj(stream);
+ RELEASE(stream_data_ptr);
+ return -1;
+ }
+ } else if (compression == DIB_COMPRESS_RLE4) {
+ stream_data_ptr = NEW(rowbytes*info.height, unsigned char);
+ if (read_raster_rle4(stream_data_ptr,
+ info.width, info.height, fp) < 0) {
+ WARN("Reading BMP raster data failed...");
+ pdf_release_obj(stream);
+ RELEASE(stream_data_ptr);
+ return -1;
+ }
+ } else {
+ pdf_release_obj(stream);
+ return -1;
+ }
+
+ /* gbr --> rgb */
+ if (bit_count == 24) {
+ for (n = 0; n < info.width * info.height * 3; n += 3) {
+ unsigned char g;
+ g = stream_data_ptr[n];
+ stream_data_ptr[n ] = stream_data_ptr[n+2];
+ stream_data_ptr[n+2] = g;
+ }
+ }
+
+ if (flip) {
+ for (n = info.height - 1; n >= 0; n--) {
+ p = stream_data_ptr + n * rowbytes;
+ pdf_add_stream(stream, p, rowbytes);
+ }
+ } else {
+ pdf_add_stream(stream, stream_data_ptr, rowbytes*info.height);
+ }
+ RELEASE(stream_data_ptr);
+ }
+
+ pdf_ximage_set_image(ximage, &info, stream);
+
+ return 0;
+}
+
+static long
+read_raster_rle8 (unsigned char *data_ptr,
+ long width, long height, FILE *fp)
+{
+ long count = 0;
+ unsigned char *p, b0, b1;
+ long h, v, rowbytes;
+ int eol, eoi;
+
+ p = data_ptr;
+ rowbytes = width;
+ memset(data_ptr, 0, rowbytes*height);
+ for (v = 0, eoi = 0; v < height && !eoi; v++) {
+ for (h = 0, eol = 0; h < width && !eol; ) {
+
+ b0 = get_unsigned_byte(fp);
+ b1 = get_unsigned_byte(fp);
+ count += 2;
+
+ p = data_ptr + v * rowbytes + h;
+
+ if (b0 == 0x00) {
+ switch (b1) {
+ case 0x00: /* EOL */
+ eol = 1;
+ break;
+ case 0x01: /* EOI */
+ eoi = 1;
+ break;
+ case 0x02:
+ h += get_unsigned_byte(fp);
+ v += get_unsigned_byte(fp);
+ count += 2;
+ break;
+ default:
+ h += b1;
+ if (h > width) {
+ WARN("RLE decode failed...");
+ return -1;
+ }
+ if (fread(p, 1, b1, fp) != b1)
+ return -1;
+ count += b1;
+ if (b1 % 2) {
+ get_unsigned_byte(fp);
+ count++;
+ }
+ break;
+ }
+ } else {
+ h += b0;
+ if (h > width) {
+ WARN("RLE decode failed...");
+ return -1;
+ }
+ memset(p, b1, b0);
+ }
+ }
+
+ /* Check for EOL and EOI marker */
+ if (!eol && !eoi) {
+ b0 = get_unsigned_byte(fp);
+ b1 = get_unsigned_byte(fp);
+ if (b0 != 0x00) {
+ WARN("RLE decode failed...");
+ return -1;
+ } else if (b1 == 0x01) {
+ eoi = 1;
+ } else if (b1 != 0x00) {
+ WARN("RLE decode failed...");
+ return -1;
+ }
+ }
+
+ /* next row ... */
+ }
+
+ return count;
+}
+
+static long
+read_raster_rle4 (unsigned char *data_ptr,
+ long width, long height, FILE *fp)
+{
+ long count = 0;
+ unsigned char *p, b0, b1, b;
+ long h, v, rowbytes;
+ int eol, eoi, i, nbytes;
+
+ p = data_ptr;
+ rowbytes = (width + 1) / 2;
+ memset(data_ptr, 0, rowbytes*height);
+ for (v = 0, eoi = 0; v < height && !eoi; v++) {
+ for (h = 0, eol = 0; h < width && !eol; ) {
+
+ b0 = get_unsigned_byte(fp);
+ b1 = get_unsigned_byte(fp);
+ count += 2;
+
+ p = data_ptr + v * rowbytes + (h / 2);
+ if (b0 == 0x00) {
+ switch (b1) {
+ case 0x00: /* EOL */
+ eol = 1;
+ break;
+ case 0x01: /* EOI */
+ eoi = 1;
+ break;
+ case 0x02:
+ h += get_unsigned_byte(fp);
+ v += get_unsigned_byte(fp);
+ count += 2;
+ break;
+ default:
+ if (h + b1 > width) {
+ WARN("RLE decode failed...");
+ return -1;
+ }
+ nbytes = (b1 + 1)/2;
+ if (h % 2) { /* starting at hi-nib */
+ for (i = 0; i < nbytes; i++) {
+ b = get_unsigned_byte(fp);
+ *p++ |= (b >> 4) & 0x0f;
+ *p = (b << 4) & 0xf0;
+ }
+ } else {
+ if (fread(p, 1, nbytes, fp) != nbytes) {
+ return -1;
+ }
+ }
+ h += b1;
+ count += nbytes;
+ if (nbytes % 2) {
+ get_unsigned_byte(fp);
+ count++;
+ }
+ break;
+ }
+ } else {
+ if (h + b0 > width) {
+ WARN("RLE decode failed...");
+ return -1;
+ }
+ if (h % 2) {
+ *p++ = (b1 >> 4) & 0x0f;
+ b1 = ((b1 << 4) & 0xf0)|((b1 >> 4) & 0x0f);
+ b0--;
+ h++;
+ }
+ nbytes = (b0 + 1)/2;
+ memset(p, b1, nbytes);
+ h += b0;
+ if (h % 2)
+ p[nbytes-1] &= 0xf0;
+ }
+ }
+
+ /* Check for EOL and EOI marker */
+ if (!eol && !eoi) {
+ b0 = get_unsigned_byte(fp);
+ b1 = get_unsigned_byte(fp);
+ if (b0 != 0x00) {
+ WARN("No EOL/EOI marker. RLE decode failed...");
+ return -1;
+ } else if (b1 == 0x01) {
+ eoi = 1;
+ } else if (b1 != 0x00) {
+ WARN("No EOL/EOI marker. RLE decode failed...");
+ return -1;
+ }
+ }
+
+ /* next row ... */
+ }
+
+ return count;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/cff.c b/Build/source/texk/dvipdf-x/xsrc/cff.c
new file mode 100644
index 00000000000..5e98b6e097d
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/cff.c
@@ -0,0 +1,1484 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#include <stdio.h>
+#include <string.h>
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+#include "mfileio.h"
+
+#include "cff_limits.h"
+#include "cff_types.h"
+#include "cff_stdstr.h"
+#include "cff_dict.h"
+
+#include "cff.h"
+
+#define CFF_DEBUG 5
+#define CFF_DEBUG_STR "CFF"
+
+static unsigned long get_unsigned (sfnt *sfont, int n)
+{
+ unsigned long v = 0;
+
+ while (n-- > 0)
+ v = v*0x100u + sfnt_get_byte(sfont);
+
+ return v;
+}
+
+#define get_offset(s, n) get_unsigned((s), (n))
+#define get_card8(s) sfnt_get_byte((s))
+#define get_card16(s) sfnt_get_ushort((s))
+
+/*
+ * Read Header, Name INDEX, Top DICT INDEX, and String INDEX.
+ */
+cff_font *cff_open(sfnt *sfont, long offset, int n)
+{
+ cff_font *cff;
+ cff_index *idx;
+
+ cff = NEW(1, cff_font);
+
+ cff->fontname = NULL;
+ cff->index = n;
+ cff->sfont = sfont;
+ cff->offset = offset;
+ cff->filter = 0; /* not used */
+ cff->flag = 0;
+
+ cff->name = NULL;
+ cff->gsubr = NULL;
+ cff->encoding = NULL;
+ cff->charsets = NULL;
+ cff->fdselect = NULL;
+ cff->cstrings = NULL;
+ cff->fdarray = NULL;
+ cff->private = NULL;
+ cff->subrs = NULL;
+
+ cff->num_glyphs = 0;
+ cff->num_fds = 0;
+ cff->_string = NULL;
+
+ cff_seek_set(cff, 0);
+ cff->header.major = get_card8(cff->sfont);
+ cff->header.minor = get_card8(cff->sfont);
+ cff->header.hdr_size = get_card8(cff->sfont);
+ cff->header.offsize = get_card8(cff->sfont);
+ if (cff->header.offsize < 1 ||
+ cff->header.offsize > 4)
+ ERROR("invalid offsize data");
+
+ if (cff->header.major > 1 ||
+ cff->header.minor > 0) {
+ WARN("%s: CFF version %u.%u not supported.",
+ CFF_DEBUG_STR, cff->header.major, cff->header.minor);
+ cff_close(cff);
+ return NULL;
+ }
+
+ cff_seek_set(cff, (cff->header).hdr_size);
+
+ /* Name INDEX */
+ idx = cff_get_index(cff);
+ if (n > idx->count - 1) {
+ WARN("%s: Invalid CFF fontset index number.", CFF_DEBUG_STR);
+ cff_close(cff);
+ return NULL;
+ }
+
+ cff->name = idx;
+
+ cff->fontname = cff_get_name(cff);
+
+ /* Top DICT INDEX */
+ idx = cff_get_index(cff);
+ if (n > idx->count - 1)
+ ERROR("CFF Top DICT not exist...");
+ cff->topdict = cff_dict_unpack(idx->data + idx->offset[n] - 1,
+ idx->data + idx->offset[n + 1] - 1);
+ if (!cff->topdict)
+ ERROR("Parsing CFF Top DICT data failed...");
+ cff_release_index(idx);
+
+ if (cff_dict_known(cff->topdict, "CharstringType") &&
+ cff_dict_get(cff->topdict, "CharstringType", 0) != 2) {
+ WARN("Only Type 2 Charstrings supported...");
+ cff_close(cff);
+ return NULL;
+ }
+
+ if (cff_dict_known(cff->topdict, "SyntheticBase")) {
+ WARN("CFF Synthetic font not supported.");
+ cff_close(cff);
+ return NULL;
+ }
+
+ /* String INDEX */
+ cff->string = cff_get_index(cff);
+
+ /* offset to GSubr */
+ cff->gsubr_offset = cff->sfont->loc - offset;
+
+ /* Number of glyphs */
+ offset = (long) cff_dict_get(cff->topdict, "CharStrings", 0);
+ cff_seek_set(cff, offset);
+ cff->num_glyphs = get_card16(cff->sfont);
+
+ /* Check for font type */
+ if (cff_dict_known(cff->topdict, "ROS")) {
+ cff->flag |= FONTTYPE_CIDFONT;
+ } else {
+ cff->flag |= FONTTYPE_FONT;
+ }
+
+ /* Check for encoding */
+ if (cff_dict_known(cff->topdict, "Encoding")) {
+ offset = (long) cff_dict_get(cff->topdict, "Encoding", 0);
+ if (offset == 0) { /* predefined */
+ cff->flag |= ENCODING_STANDARD;
+ } else if (offset == 1) {
+ cff->flag |= ENCODING_EXPERT;
+ }
+ } else {
+ cff->flag |= ENCODING_STANDARD;
+ }
+
+ /* Check for charset */
+ if (cff_dict_known(cff->topdict, "charset")) {
+ offset = (long) cff_dict_get(cff->topdict, "charset", 0);
+ if (offset == 0) { /* predefined */
+ cff->flag |= CHARSETS_ISOADOBE;
+ } else if (offset == 1) {
+ cff->flag |= CHARSETS_EXPERT;
+ } else if (offset == 2) {
+ cff->flag |= CHARSETS_EXPSUB;
+ }
+ } else {
+ cff->flag |= CHARSETS_ISOADOBE;
+ }
+
+ cff_seek_set(cff, cff->gsubr_offset); /* seek back to GSubr */
+
+#ifdef XETEX
+ cff->ft_to_gid = NULL;
+#endif
+
+ return cff;
+}
+
+void
+cff_close (cff_font *cff)
+{
+ card16 i;
+
+ if (cff) {
+ if (cff->fontname) RELEASE(cff->fontname);
+ if (cff->name) cff_release_index(cff->name);
+ if (cff->topdict) cff_release_dict(cff->topdict);
+ if (cff->string) cff_release_index(cff->string);
+ if (cff->gsubr) cff_release_index(cff->gsubr);
+ if (cff->encoding) cff_release_encoding(cff->encoding);
+ if (cff->charsets) cff_release_charsets(cff->charsets);
+ if (cff->fdselect) cff_release_fdselect(cff->fdselect);
+ if (cff->cstrings) cff_release_index(cff->cstrings);
+ if (cff->fdarray) {
+ for (i=0;i<cff->num_fds;i++) {
+ if (cff->fdarray[i]) cff_release_dict(cff->fdarray[i]);
+ }
+ RELEASE(cff->fdarray);
+ }
+ if (cff->private) {
+ for (i=0;i<cff->num_fds;i++) {
+ if (cff->private[i]) cff_release_dict(cff->private[i]);
+ }
+ RELEASE(cff->private);
+ }
+ if (cff->subrs) {
+ for (i=0;i<cff->num_fds;i++) {
+ if (cff->subrs[i]) cff_release_index(cff->subrs[i]);
+ }
+ RELEASE(cff->subrs);
+ }
+ if (cff->_string)
+ cff_release_index(cff->_string);
+#ifdef XETEX
+ if (cff->ft_to_gid) RELEASE(cff->ft_to_gid);
+#endif
+ RELEASE(cff);
+ }
+
+ return;
+}
+
+char *
+cff_get_name (cff_font *cff)
+{
+ char *fontname;
+ l_offset len;
+ cff_index *idx;
+
+ idx = cff->name;
+ len = idx->offset[cff->index + 1] - idx->offset[cff->index];
+ fontname = NEW(len + 1, char);
+ memcpy(fontname, idx->data + idx->offset[cff->index] - 1, len);
+ fontname[len] = '\0';
+
+ return fontname;
+}
+
+long
+cff_set_name (cff_font *cff, char *name)
+{
+ cff_index *idx;
+
+ if (strlen(name) > 127)
+ ERROR("FontName string length too large...");
+
+ if (cff->name)
+ cff_release_index(cff->name);
+
+ cff->name = idx = NEW(1, cff_index);
+ idx->count = 1;
+ idx->offsize = 1;
+ idx->offset = NEW(2, l_offset);
+ (idx->offset)[0] = 1;
+ (idx->offset)[1] = strlen(name) + 1;
+ idx->data = NEW(strlen(name), card8);
+ memmove(idx->data, name, strlen(name)); /* no trailing '\0' */
+
+ return 5 + strlen(name);
+}
+
+long
+cff_put_header (cff_font *cff, card8 *dest, long destlen)
+{
+ if (destlen < 4)
+ ERROR("Not enough space available...");
+
+ *(dest++) = cff->header.major;
+ *(dest++) = cff->header.minor;
+ *(dest++) = 4; /* Additional data in between header and
+ * Name INDEX ignored.
+ */
+ /* We will set all offset (0) to four-byte integer. */
+ *(dest++) = 4;
+ cff->header.offsize = 4;
+
+ return 4;
+}
+
+/* Only read header part but not body */
+cff_index *
+cff_get_index_header (cff_font *cff)
+{
+ cff_index *idx;
+ card16 i, count;
+
+ idx = NEW(1, cff_index);
+
+ idx->count = count = get_card16(cff->sfont);
+ if (count > 0) {
+ idx->offsize = get_card8(cff->sfont);
+ if (idx->offsize < 1 || idx->offsize > 4)
+ ERROR("invalid offsize data");
+
+ idx->offset = NEW(count+1, l_offset);
+ for (i=0;i<count+1;i++) {
+ (idx->offset)[i] = get_offset(cff->sfont, idx->offsize);
+ }
+
+ if (idx->offset[0] != 1)
+ ERROR("cff_get_index(): invalid index data");
+
+ idx->data = NULL;
+ } else {
+ idx->offsize = 0;
+ idx->offset = NULL;
+ idx->data = NULL;
+ }
+
+ return idx;
+}
+
+cff_index *
+cff_get_index (cff_font *cff)
+{
+ cff_index *idx;
+ card16 i, count;
+ long length, nb_read, offset;
+
+ idx = NEW(1, cff_index);
+
+ idx->count = count = get_card16(cff->sfont);
+ if (count > 0) {
+ idx->offsize = get_card8(cff->sfont);
+ if (idx->offsize < 1 || idx->offsize > 4)
+ ERROR("invalid offsize data");
+
+ idx->offset = NEW(count + 1, l_offset);
+ for (i = 0 ; i < count + 1; i++) {
+ idx->offset[i] = get_offset(cff->sfont, idx->offsize);
+ }
+
+ if (idx->offset[0] != 1)
+ ERROR("Invalid CFF Index offset data");
+
+ length = idx->offset[count] - idx->offset[0];
+
+ idx->data = NEW(length, card8);
+ offset = 0;
+ while (length > 0) {
+ nb_read = sfnt_read(idx->data + offset, length, cff->sfont);
+ offset += nb_read;
+ length -= nb_read;
+ }
+ } else {
+ idx->offsize = 0;
+ idx->offset = NULL;
+ idx->data = NULL;
+ }
+
+ return idx;
+}
+
+long
+cff_pack_index (cff_index *idx, card8 *dest, long destlen)
+{
+ long len = 0;
+ long datalen;
+ card16 i;
+
+ if (idx->count < 1) {
+ if (destlen < 2)
+ ERROR("Not enough space available...");
+ memset(dest, 0, 2);
+ return 2;
+ }
+
+ len = cff_index_size(idx);
+ datalen = idx->offset[idx->count] - 1;
+
+ if (destlen < len)
+ ERROR("Not enough space available...");
+
+ *(dest++) = (idx->count >> 8) & 0xff;
+ *(dest++) = idx->count & 0xff;
+
+ if (datalen < 0xffUL) {
+ idx->offsize = 1;
+ *(dest++) = 1;
+ for (i = 0; i <= idx->count; i++) {
+ *(dest++) = (card8) (idx->offset[i] & 0xff);
+ }
+ } else if (datalen < 0xffffUL) {
+ idx->offsize = 2;
+ *(dest++) = 2;
+ for (i = 0; i <= idx->count; i++) {
+ *(dest++) = (card8) ((idx->offset[i] >> 8) & 0xff);
+ *(dest++) = (card8) ( idx->offset[i] & 0xff);
+ }
+ } else if (datalen < 0xffffffUL) {
+ idx->offsize = 3;
+ *(dest++) = 3;
+ for (i = 0; i <= idx->count; i++) {
+ *(dest++) = (card8)((idx->offset[i] >> 16) & 0xff);
+ *(dest++) = (card8)((idx->offset[i] >> 8) & 0xff);
+ *(dest++) = (card8)(idx->offset[i] & 0xff);
+ }
+ } else {
+ idx->offsize = 4;
+ *(dest++) = 4;
+ for (i = 0; i <= idx->count; i++) {
+ *(dest++) = (card8)((idx->offset[i] >> 24) & 0xff);
+ *(dest++) = (card8)((idx->offset[i] >> 16) & 0xff);
+ *(dest++) = (card8)((idx->offset[i] >> 8) & 0xff);
+ *(dest++) = (card8)(idx->offset[i] & 0xff);
+ }
+ }
+
+ memmove(dest, idx->data, idx->offset[idx->count] - 1);
+
+ return len;
+}
+
+long
+cff_index_size (cff_index *idx)
+{
+ if (idx->count > 0) {
+ l_offset datalen;
+
+ datalen = idx->offset[idx->count] - 1;
+ if (datalen < 0xffUL) {
+ idx->offsize = 1;
+ } else if (datalen < 0xffffUL) {
+ idx->offsize = 2;
+ } else if (datalen < 0xffffffUL) {
+ idx->offsize = 3;
+ } else {
+ idx->offsize = 4;
+ }
+ return (3 + (idx->offsize)*(idx->count + 1) + datalen);
+ } else {
+ return 2;
+ }
+}
+
+
+cff_index *cff_new_index (card16 count)
+{
+ cff_index *idx;
+
+ idx = NEW(1, cff_index);
+ idx->count = count;
+ idx->offsize = 0;
+
+ if (count > 0) {
+ idx->offset = NEW(count + 1, l_offset);
+ (idx->offset)[0] = 1;
+ } else {
+ idx->offset = NULL;
+ }
+ idx->data = NULL;
+
+ return idx;
+}
+
+void cff_release_index (cff_index *idx)
+{
+ if (idx) {
+ if (idx->data) {
+ RELEASE(idx->data);
+ }
+ if (idx->offset) {
+ RELEASE(idx->offset);
+ }
+ RELEASE(idx);
+ }
+}
+
+/* Strings */
+char *cff_get_string (cff_font *cff, s_SID id)
+{
+ char *result = NULL;
+ long len;
+
+ if (id < CFF_STDSTR_MAX) {
+ len = strlen(cff_stdstr[id]);
+ result = NEW(len+1, char);
+ memcpy(result, cff_stdstr[id], len);
+ result[len] = '\0';
+ } else if (cff && cff->string) {
+ cff_index *strings = cff->string;
+ id -= CFF_STDSTR_MAX;
+ if (id < strings->count) {
+ len = (strings->offset)[id+1] - (strings->offset)[id];
+ result = NEW(len + 1, char);
+ memmove(result, strings->data + (strings->offset)[id] - 1, len);
+ result[len] = '\0';
+ }
+ }
+
+ return result;
+}
+
+long cff_get_sid (cff_font *cff, const char *str)
+{
+ card16 i;
+
+ if (!cff || !str)
+ return -1;
+
+ /* I search String INDEX first. */
+ if (cff && cff->string) {
+ cff_index *idx = cff->string;
+ for (i = 0; i < idx->count; i++) {
+ if (strlen(str) == (idx->offset)[i+1] - (idx->offset)[i] &&
+ !memcmp(str, (idx->data)+(idx->offset)[i]-1, strlen(str)))
+ return (i + CFF_STDSTR_MAX);
+ }
+ }
+
+ for (i = 0; i < CFF_STDSTR_MAX; i++) {
+ if (!strcmp(str, cff_stdstr[i]))
+ return i;
+ }
+
+ return -1;
+}
+
+long cff_get_seac_sid (cff_font *cff, const char *str)
+{
+ card16 i;
+
+ if (!cff || !str)
+ return -1;
+
+ for (i = 0; i < CFF_STDSTR_MAX; i++) {
+ if (!strcmp(str, cff_stdstr[i]))
+ return i;
+ }
+
+ return -1;
+}
+
+int cff_match_string (cff_font *cff, const char *str, s_SID sid)
+{
+ card16 i;
+
+ if (sid < CFF_STDSTR_MAX) {
+ return ((!strcmp(str, cff_stdstr[sid])) ? 1 : 0);
+ } else {
+ i = sid - CFF_STDSTR_MAX;
+ if (cff == NULL || cff->string == NULL || i >= cff->string->count)
+ ERROR("Invalid SID");
+ if (strlen(str) == (cff->string->offset)[i+1] - (cff->string->offset)[i])
+ return (!memcmp(str,
+ (cff->string->data)+(cff->string->offset)[i]-1,
+ strlen(str))) ? 1 : 0;
+ }
+
+ return 0;
+}
+
+void cff_update_string (cff_font *cff)
+{
+ if (cff == NULL)
+ ERROR("CFF font not opened.");
+
+ if (cff->string)
+ cff_release_index(cff->string);
+ cff->string = cff->_string;
+ cff->_string = NULL;
+}
+
+s_SID cff_add_string (cff_font *cff, const char *str, int unique)
+/* Setting unique == 1 eliminates redundant or predefined strings. */
+{
+ card16 idx;
+ cff_index *strings;
+ l_offset offset, size;
+ long len = strlen(str);
+
+ if (cff == NULL)
+ ERROR("CFF font not opened.");
+
+ if (cff->_string == NULL)
+ cff->_string = cff_new_index(0);
+ strings = cff->_string;
+
+ if (unique) {
+ /* TODO: do binary search to speed things up */
+ for (idx = 0; idx < CFF_STDSTR_MAX; idx++) {
+ if (cff_stdstr[idx] && !strcmp(cff_stdstr[idx], str))
+ return idx;
+ }
+ for (idx = 0; idx < strings->count; idx++) {
+ size = strings->offset[idx+1] - strings->offset[idx];
+ offset = strings->offset[idx];
+ if (size == len && !memcmp(strings->data+offset-1, str, len))
+ return (idx + CFF_STDSTR_MAX);
+ }
+ }
+
+ offset = (strings->count > 0) ? strings->offset[strings->count] : 1;
+ strings->offset = RENEW(strings->offset, strings->count+2, l_offset);
+ if (strings->count == 0)
+ strings->offset[0] = 1;
+ idx = strings->count;
+ strings->count += 1;
+ strings->offset[strings->count] = offset + len;
+ strings->data = RENEW(strings->data, offset+len-1, card8);
+ memcpy(strings->data+offset-1, str, len);
+
+ return (idx + CFF_STDSTR_MAX);
+}
+
+/*
+ * Encoding and Charset
+ *
+ * Encoding and Charset arrays always begin with GID = 1.
+ */
+long cff_read_encoding (cff_font *cff)
+{
+ cff_encoding *encoding;
+ long offset, length;
+ card8 i;
+
+ if (cff->topdict == NULL) {
+ ERROR("Top DICT data not found");
+ }
+
+ if (!cff_dict_known(cff->topdict, "Encoding")) {
+ cff->flag |= ENCODING_STANDARD;
+ cff->encoding = NULL;
+ return 0;
+ }
+
+ offset = (long) cff_dict_get(cff->topdict, "Encoding", 0);
+ if (offset == 0) { /* predefined */
+ cff->flag |= ENCODING_STANDARD;
+ cff->encoding = NULL;
+ return 0;
+ } else if (offset == 1) {
+ cff->flag |= ENCODING_EXPERT;
+ cff->encoding = NULL;
+ return 0;
+ }
+
+ cff_seek_set(cff, offset);
+ cff->encoding = encoding = NEW(1, cff_encoding);
+ encoding->format = get_card8(cff->sfont);
+ length = 1;
+
+ switch (encoding->format & (~0x80)) {
+ case 0:
+ encoding->num_entries = get_card8(cff->sfont);
+ (encoding->data).codes = NEW(encoding->num_entries, card8);
+ for (i=0;i<(encoding->num_entries);i++) {
+ (encoding->data).codes[i] = get_card8(cff->sfont);
+ }
+ length += encoding->num_entries + 1;
+ break;
+ case 1:
+ {
+ cff_range1 *ranges;
+ encoding->num_entries = get_card8(cff->sfont);
+ encoding->data.range1 = ranges
+ = NEW(encoding->num_entries, cff_range1);
+ for (i=0;i<(encoding->num_entries);i++) {
+ ranges[i].first = get_card8(cff->sfont);
+ ranges[i].n_left = get_card8(cff->sfont);
+ }
+ length += (encoding->num_entries) * 2 + 1;
+ }
+ break;
+ default:
+ RELEASE(encoding);
+ ERROR("Unknown Encoding format");
+ break;
+ }
+
+ /* Supplementary data */
+ if ((encoding->format) & 0x80) {
+ cff_map *map;
+ encoding->num_supps = get_card8(cff->sfont);
+ encoding->supp = map = NEW(encoding->num_supps, cff_map);
+ for (i=0;i<(encoding->num_supps);i++) {
+ map[i].code = get_card8(cff->sfont);
+ map[i].glyph = get_card16(cff->sfont); /* SID */
+ }
+ length += (encoding->num_supps) * 3 + 1;
+ } else {
+ encoding->num_supps = 0;
+ encoding->supp = NULL;
+ }
+
+ return length;
+}
+
+long cff_pack_encoding (cff_font *cff, card8 *dest, long destlen)
+{
+ long len = 0;
+ cff_encoding *encoding;
+ card16 i;
+
+ if (cff->flag & HAVE_STANDARD_ENCODING || cff->encoding == NULL)
+ return 0;
+
+ if (destlen < 2)
+ ERROR("in cff_pack_encoding(): Buffer overflow");
+
+ encoding = cff->encoding;
+
+ dest[len++] = encoding->format;
+ dest[len++] = encoding->num_entries;
+ switch (encoding->format & (~0x80)) {
+ case 0:
+ if (destlen < len + encoding->num_entries)
+ ERROR("in cff_pack_encoding(): Buffer overflow");
+ for (i=0;i<(encoding->num_entries);i++) {
+ dest[len++] = (encoding->data).codes[i];
+ }
+ break;
+ case 1:
+ {
+ if (destlen < len + (encoding->num_entries)*2)
+ ERROR("in cff_pack_encoding(): Buffer overflow");
+ for (i=0;i<(encoding->num_entries);i++) {
+ dest[len++] = (encoding->data).range1[i].first & 0xff;
+ dest[len++] = (encoding->data).range1[i].n_left;
+ }
+ }
+ break;
+ default:
+ ERROR("Unknown Encoding format");
+ break;
+ }
+
+ if ((encoding->format) & 0x80) {
+ if (destlen < len + (encoding->num_supps)*3 + 1)
+ ERROR("in cff_pack_encoding(): Buffer overflow");
+ dest[len++] = encoding->num_supps;
+ for (i=0;i<(encoding->num_supps);i++) {
+ dest[len++] = (encoding->supp)[i].code;
+ dest[len++] = ((encoding->supp)[i].glyph >> 8) & 0xff;
+ dest[len++] = (encoding->supp)[i].glyph & 0xff;
+ }
+ }
+
+ return len;
+}
+
+/* input: code, output: glyph index */
+card16 cff_encoding_lookup (cff_font *cff, card8 code)
+{
+ card16 gid = 0;
+ cff_encoding *encoding;
+ card16 i;
+
+ if (cff->flag & (ENCODING_STANDARD|ENCODING_EXPERT)) {
+ ERROR("Predefined CFF encoding not supported yet");
+ } else if (cff->encoding == NULL) {
+ ERROR("Encoding data not available");
+ }
+
+ encoding = cff->encoding;
+
+ gid = 0;
+ switch (encoding->format & (~0x80)) {
+ case 0:
+ for (i = 0; i < encoding->num_entries; i++) {
+ if (code == (encoding->data).codes[i]) {
+ gid = i + 1;
+ break;
+ }
+ }
+ break;
+ case 1:
+ for (i = 0; i < encoding->num_entries; i++) {
+ if (code >= (encoding->data).range1[i].first &&
+ code <= (encoding->data).range1[i].first + (encoding->data).range1[i].n_left) {
+ gid += code - (encoding->data).range1[i].first + 1;
+ break;
+ }
+ gid += (encoding->data).range1[i].n_left + 1;
+ }
+ if (i == encoding->num_entries)
+ gid = 0;
+ break;
+ default:
+ ERROR("Unknown Encoding format.");
+ }
+
+ /* Supplementary data */
+ if (gid == 0 && ((encoding->format) & 0x80)) {
+ cff_map *map;
+ if (!encoding->supp)
+ ERROR("No CFF supplementary encoding data read.");
+ map = encoding->supp;
+ for (i=0;i<(encoding->num_supps);i++) {
+ if (code == map[i].code) {
+ gid = cff_charsets_lookup(cff, map[i].glyph);
+ break;
+ }
+ }
+ }
+
+ return gid;
+}
+
+void cff_release_encoding (cff_encoding *encoding)
+{
+ if (encoding) {
+ switch (encoding->format & (~0x80)) {
+ case 0:
+ if (encoding->data.codes)
+ RELEASE(encoding->data.codes);
+ break;
+ case 1:
+ if (encoding->data.range1)
+ RELEASE(encoding->data.range1);
+ break;
+ default:
+ ERROR("Unknown Encoding format.");
+ }
+ if (encoding->format & 0x80) {
+ if (encoding->supp)
+ RELEASE(encoding->supp);
+ }
+ RELEASE(encoding);
+ }
+}
+
+long cff_read_charsets (cff_font *cff)
+{
+ cff_charsets *charset;
+ long offset, length;
+ card16 count, i;
+
+ if (cff->topdict == NULL)
+ ERROR("Top DICT not available");
+
+ if (!cff_dict_known(cff->topdict, "charset")) {
+ cff->flag |= CHARSETS_ISOADOBE;
+ cff->charsets = NULL;
+ return 0;
+ }
+
+ offset = (long) cff_dict_get(cff->topdict, "charset", 0);
+
+ if (offset == 0) { /* predefined */
+ cff->flag |= CHARSETS_ISOADOBE;
+ cff->charsets = NULL;
+ return 0;
+ } else if (offset == 1) {
+ cff->flag |= CHARSETS_EXPERT;
+ cff->charsets = NULL;
+ return 0;
+ } else if (offset == 2) {
+ cff->flag |= CHARSETS_EXPSUB;
+ cff->charsets = NULL;
+ return 0;
+ }
+
+ cff_seek_set(cff, offset);
+ cff->charsets = charset = NEW(1, cff_charsets);
+ charset->format = get_card8(cff->sfont);
+ charset->num_entries = 0;
+
+ count = cff->num_glyphs - 1;
+ length = 1;
+
+ /* Not sure. Not well documented. */
+ switch (charset->format) {
+ case 0:
+ charset->num_entries = cff->num_glyphs - 1; /* no .notdef */
+ charset->data.glyphs = NEW(charset->num_entries, s_SID);
+ length += (charset->num_entries) * 2;
+ for (i=0;i<(charset->num_entries);i++) {
+ charset->data.glyphs[i] = get_card16(cff->sfont);
+ }
+ count = 0;
+ break;
+ case 1:
+ {
+ cff_range1 *ranges = NULL;
+ while (count > 0 && charset->num_entries < cff->num_glyphs) {
+ ranges = RENEW(ranges, charset->num_entries + 1, cff_range1);
+ ranges[charset->num_entries].first = get_card16(cff->sfont);
+ ranges[charset->num_entries].n_left = get_card8(cff->sfont);
+ count -= ranges[charset->num_entries].n_left + 1; /* no-overrap */
+ charset->num_entries += 1;
+ charset->data.range1 = ranges;
+ }
+ length += (charset->num_entries) * 3;
+ }
+ break;
+ case 2:
+ {
+ cff_range2 *ranges = NULL;
+ while (count > 0 && charset->num_entries < cff->num_glyphs) {
+ ranges = RENEW(ranges, charset->num_entries + 1, cff_range2);
+ ranges[charset->num_entries].first = get_card16(cff->sfont);
+ ranges[charset->num_entries].n_left = get_card16(cff->sfont);
+ count -= ranges[charset->num_entries].n_left + 1; /* non-overrapping */
+ charset->num_entries += 1;
+ }
+ charset->data.range2 = ranges;
+ length += (charset->num_entries) * 4;
+ }
+ break;
+ default:
+ RELEASE(charset);
+ ERROR("Unknown Charset format");
+ break;
+ }
+
+ if (count > 0)
+ ERROR("Charset data possibly broken");
+
+ return length;
+}
+
+long cff_pack_charsets (cff_font *cff, card8 *dest, long destlen)
+{
+ long len = 0;
+ card16 i;
+ cff_charsets *charset;
+
+ if (cff->flag & HAVE_STANDARD_CHARSETS || cff->charsets == NULL)
+ return 0;
+
+ if (destlen < 1)
+ ERROR("in cff_pack_charsets(): Buffer overflow");
+
+ charset = cff->charsets;
+
+ dest[len++] = charset->format;
+ switch (charset->format) {
+ case 0:
+ if (destlen < len + (charset->num_entries)*2)
+ ERROR("in cff_pack_charsets(): Buffer overflow");
+ for (i=0;i<(charset->num_entries);i++) {
+ s_SID sid = (charset->data).glyphs[i]; /* or CID */
+ dest[len++] = (sid >> 8) & 0xff;
+ dest[len++] = sid & 0xff;
+ }
+ break;
+ case 1:
+ {
+ if (destlen < len + (charset->num_entries)*3)
+ ERROR("in cff_pack_charsets(): Buffer overflow");
+ for (i=0;i<(charset->num_entries);i++) {
+ dest[len++] = ((charset->data).range1[i].first >> 8) & 0xff;
+ dest[len++] = (charset->data).range1[i].first & 0xff;
+ dest[len++] = (charset->data).range1[i].n_left;
+ }
+ }
+ break;
+ case 2:
+ {
+ if (destlen < len + (charset->num_entries)*4)
+ ERROR("in cff_pack_charsets(): Buffer overflow");
+ for (i=0;i<(charset->num_entries);i++) {
+ dest[len++] = ((charset->data).range2[i].first >> 8) & 0xff;
+ dest[len++] = (charset->data).range2[i].first & 0xff;
+ dest[len++] = ((charset->data).range2[i].n_left >> 8) & 0xff;
+ dest[len++] = (charset->data).range2[i].n_left & 0xff;
+ }
+ }
+ break;
+ default:
+ ERROR("Unknown Charset format");
+ break;
+ }
+
+ return len;
+}
+
+card16 cff_glyph_lookup (cff_font *cff, const char *glyph)
+{
+ card16 gid;
+ cff_charsets *charset;
+ card16 i, n;
+
+ if (cff->flag & (CHARSETS_ISOADOBE|CHARSETS_EXPERT|CHARSETS_EXPSUB)) {
+ ERROR("Predefined CFF charsets not supported yet");
+ } else if (cff->charsets == NULL) {
+ ERROR("Charsets data not available");
+ }
+
+ /* .notdef always have glyph index 0 */
+ if (!glyph || !strcmp(glyph, ".notdef")) {
+ return 0;
+ }
+
+ charset = cff->charsets;
+
+ gid = 0;
+ switch (charset->format) {
+ case 0:
+ for (i = 0; i < charset->num_entries; i++) {
+ gid++;
+ if (cff_match_string(cff, glyph, charset->data.glyphs[i])) {
+ return gid;
+ }
+ }
+ break;
+ case 1:
+ for (i = 0; i < charset->num_entries; i++) {
+ for (n = 0;
+ n <= charset->data.range1[i].n_left; n++) {
+ gid++;
+ if (cff_match_string(cff, glyph,
+ (s_SID)(charset->data.range1[i].first + n))) {
+ return gid;
+ }
+ }
+ }
+ break;
+ case 2:
+ for (i = 0; i <charset->num_entries; i++) {
+ for (n = 0;
+ n <= charset->data.range2[i].n_left; n++) {
+ gid++;
+ if (cff_match_string(cff, glyph,
+ (s_SID)(charset->data.range2[i].first + n))) {
+ return gid;
+ }
+ }
+ }
+ break;
+ default:
+ ERROR("Unknown Charset format");
+ }
+
+ return 0; /* not found, returns .notdef */
+}
+
+/* Input : SID or CID (16-bit unsigned int)
+ * Output: glyph index
+ */
+card16
+cff_charsets_lookup (cff_font *cff, card16 cid)
+{
+ card16 gid = 0;
+ cff_charsets *charset;
+ card16 i;
+
+ if (cff->flag & (CHARSETS_ISOADOBE|CHARSETS_EXPERT|CHARSETS_EXPSUB)) {
+ ERROR("Predefined CFF charsets not supported yet");
+ } else if (cff->charsets == NULL) {
+ ERROR("Charsets data not available");
+ }
+
+ if (cid == 0) {
+ return 0; /* GID 0 (.notdef) */
+ }
+
+ charset = cff->charsets;
+
+ gid = 0;
+ switch (charset->format) {
+ case 0:
+ for (i = 0; i <charset->num_entries; i++) {
+ if (cid == charset->data.glyphs[i]) {
+ gid = i + 1;
+ return gid;
+ }
+ }
+ break;
+ case 1:
+ for (i = 0; i < charset->num_entries; i++) {
+ if (cid >= charset->data.range1[i].first &&
+ cid <= charset->data.range1[i].first + charset->data.range1[i].n_left) {
+ gid += cid - charset->data.range1[i].first + 1;
+ return gid;
+ }
+ gid += charset->data.range1[i].n_left + 1;
+ }
+ break;
+ case 2:
+ for (i = 0; i < charset->num_entries; i++) {
+ if (cid >= charset->data.range2[i].first &&
+ cid <= charset->data.range2[i].first + charset->data.range2[i].n_left) {
+ gid += cid - charset->data.range2[i].first + 1;
+ return gid;
+ }
+ gid += charset->data.range2[i].n_left + 1;
+ }
+ break;
+ default:
+ ERROR("Unknown Charset format");
+ }
+
+ return 0; /* not found */
+}
+
+/* Input : GID
+ * Output: SID/CID (card16)
+ */
+card16
+cff_charsets_lookup_inverse (cff_font *cff, card16 gid)
+{
+ card16 sid = 0;
+ cff_charsets *charset;
+ card16 i;
+
+ if (cff->flag & (CHARSETS_ISOADOBE|CHARSETS_EXPERT|CHARSETS_EXPSUB)) {
+ ERROR("Predefined CFF charsets not supported yet");
+ } else if (cff->charsets == NULL) {
+ ERROR("Charsets data not available");
+ }
+
+ if (gid == 0) {
+ return 0; /* .notdef */
+ }
+
+ charset = cff->charsets;
+
+ sid = 0;
+ switch (charset->format) {
+ case 0:
+ if (gid - 1 >= charset->num_entries)
+ ERROR("Invalid GID.");
+ sid = charset->data.glyphs[gid - 1];
+ break;
+ case 1:
+ for (i = 0; i < charset->num_entries; i++) {
+ if (gid <= charset->data.range1[i].n_left + 1) {
+ sid = gid + charset->data.range1[i].first - 1;
+ break;
+ }
+ gid -= charset->data.range1[i].n_left + 1;
+ }
+ if (i == charset->num_entries)
+ ERROR("Invalid GID");
+ break;
+ case 2:
+ for (i = 0; i < charset->num_entries; i++) {
+ if (gid <= charset->data.range2[i].n_left + 1) {
+ sid = gid + charset->data.range2[i].first - 1;
+ break;
+ }
+ gid -= charset->data.range2[i].n_left + 1;
+ }
+ if (i == charset->num_entries)
+ ERROR("Invalid GID");
+ break;
+ default:
+ ERROR("Unknown Charset format");
+ }
+
+ return sid;
+}
+
+void
+cff_release_charsets (cff_charsets *charset)
+{
+ if (charset) {
+ switch (charset->format) {
+ case 0:
+ if (charset->data.glyphs)
+ RELEASE(charset->data.glyphs);
+ break;
+ case 1:
+ if (charset->data.range1)
+ RELEASE(charset->data.range1);
+ break;
+ case 2:
+ if (charset->data.range2)
+ RELEASE(charset->data.range2);
+ break;
+ default:
+ break;
+ }
+ RELEASE(charset);
+ }
+}
+
+/* CID-Keyed font specific */
+long cff_read_fdselect (cff_font *cff)
+{
+ cff_fdselect *fdsel;
+ long offset, length;
+ card16 i;
+
+ if (cff->topdict == NULL)
+ ERROR("Top DICT not available");
+
+ if (!(cff->flag & FONTTYPE_CIDFONT))
+ return 0;
+
+ offset = (long) cff_dict_get(cff->topdict, "FDSelect", 0);
+ cff_seek_set(cff, offset);
+ cff->fdselect = fdsel = NEW(1, cff_fdselect);
+ fdsel->format = get_card8(cff->sfont);
+
+ length = 1;
+
+ switch (fdsel->format) {
+ case 0:
+ fdsel->num_entries = cff->num_glyphs;
+ (fdsel->data).fds = NEW(fdsel->num_entries, card8);
+ for (i=0;i<(fdsel->num_entries);i++) {
+ (fdsel->data).fds[i] = get_card8(cff->sfont);
+ }
+ length += fdsel->num_entries;
+ break;
+ case 3:
+ {
+ cff_range3 *ranges;
+ fdsel->num_entries = get_card16(cff->sfont);
+ fdsel->data.ranges = ranges = NEW(fdsel->num_entries, cff_range3);
+ for (i=0;i<(fdsel->num_entries);i++) {
+ ranges[i].first = get_card16(cff->sfont);
+ ranges[i].fd = get_card8(cff->sfont);
+ }
+ if (ranges[0].first != 0)
+ ERROR("Range not starting with 0.");
+ if (cff->num_glyphs != get_card16(cff->sfont))
+ ERROR("Sentinel value mismatched with number of glyphs.");
+ length += (fdsel->num_entries) * 3 + 4;
+ }
+ break;
+ default:
+ RELEASE(fdsel);
+ ERROR("Unknown FDSelect format.");
+ break;
+ }
+
+ return length;
+}
+
+long cff_pack_fdselect (cff_font *cff, card8 *dest, long destlen)
+{
+ cff_fdselect *fdsel;
+ long len = 0;
+ card16 i;
+
+ if (cff->fdselect == NULL)
+ return 0;
+
+ if (destlen < 1)
+ ERROR("in cff_pack_fdselect(): Buffur overflow");
+
+ fdsel = cff->fdselect;
+
+ dest[len++] = fdsel->format;
+ switch (fdsel->format) {
+ case 0:
+ if (fdsel->num_entries != cff->num_glyphs)
+ ERROR("in cff_pack_fdselect(): Invalid data");
+ if (destlen < len + fdsel->num_entries)
+ ERROR("in cff_pack_fdselect(): Buffer overflow");
+ for (i=0;i<fdsel->num_entries;i++) {
+ dest[len++] = (fdsel->data).fds[i];
+ }
+ break;
+ case 3:
+ {
+ if (destlen < len + 2)
+ ERROR("in cff_pack_fdselect(): Buffer overflow");
+ len += 2;
+ for (i=0;i<(fdsel->num_entries);i++) {
+ if (destlen < len + 3)
+ ERROR("in cff_pack_fdselect(): Buffer overflow");
+ dest[len++] = ((fdsel->data).ranges[i].first >> 8) & 0xff;
+ dest[len++] = (fdsel->data).ranges[i].first & 0xff;
+ dest[len++] = (fdsel->data).ranges[i].fd;
+ }
+ if (destlen < len + 2)
+ ERROR("in cff_pack_fdselect(): Buffer overflow");
+ dest[len++] = (cff->num_glyphs >> 8) & 0xff;
+ dest[len++] = cff->num_glyphs & 0xff;
+ dest[1] = ((len/3 - 1) >> 8) & 0xff;
+ dest[2] = (len/3 - 1) & 0xff;
+ }
+ break;
+ default:
+ ERROR("Unknown FDSelect format.");
+ break;
+ }
+
+ return len;
+}
+
+void cff_release_fdselect (cff_fdselect *fdselect)
+{
+ if (fdselect) {
+ if (fdselect->format == 0) {
+ if (fdselect->data.fds) RELEASE(fdselect->data.fds);
+ } else if (fdselect->format == 3) {
+ if (fdselect->data.ranges) RELEASE(fdselect->data.ranges);
+ }
+ RELEASE(fdselect);
+ }
+}
+
+card8 cff_fdselect_lookup (cff_font *cff, card16 gid)
+{
+ card8 fd = 0xff;
+ cff_fdselect *fdsel;
+
+ if (cff->fdselect == NULL)
+ ERROR("in cff_fdselect_lookup(): FDSelect not available");
+
+ fdsel = cff->fdselect;
+
+ if (gid >= cff->num_glyphs)
+ ERROR("in cff_fdselect_lookup(): Invalid glyph index");
+
+ switch (fdsel->format) {
+ case 0:
+ fd = fdsel->data.fds[gid];
+ break;
+ case 3:
+ {
+ if (gid == 0) {
+ fd = (fdsel->data).ranges[0].fd;
+ } else {
+ card16 i;
+ for (i=1;i<(fdsel->num_entries);i++) {
+ if (gid < (fdsel->data).ranges[i].first)
+ break;
+ }
+ fd = (fdsel->data).ranges[i-1].fd;
+ }
+ }
+ break;
+ default:
+ ERROR("in cff_fdselect_lookup(): Invalid FDSelect format");
+ break;
+ }
+
+ if (fd >= cff->num_fds)
+ ERROR("in cff_fdselect_lookup(): Invalid Font DICT index");
+
+ return fd;
+}
+
+long cff_read_subrs (cff_font *cff)
+{
+ long len = 0;
+ long offset;
+ int i;
+
+ if ((cff->flag & FONTTYPE_CIDFONT) && cff->fdarray == NULL) {
+ cff_read_fdarray(cff);
+ }
+
+ if (cff->private == NULL)
+ cff_read_private(cff);
+
+ if (cff->gsubr == NULL) {
+ cff_seek_set(cff, cff->gsubr_offset);
+ cff->gsubr = cff_get_index(cff);
+ }
+
+ cff->subrs = NEW(cff->num_fds, cff_index *);
+ if (cff->flag & FONTTYPE_CIDFONT) {
+ for (i=0;i<cff->num_fds;i++) {
+ if (cff->private[i] == NULL ||
+ !cff_dict_known(cff->private[i], "Subrs")) {
+ (cff->subrs)[i] = NULL;
+ } else {
+ offset = (long) cff_dict_get(cff->fdarray[i], "Private", 1);
+ offset += (long) cff_dict_get(cff->private[i], "Subrs", 0);
+ cff_seek_set(cff, offset);
+ (cff->subrs)[i] = cff_get_index(cff);
+ len += cff_index_size((cff->subrs)[i]);
+ }
+ }
+ } else {
+ if (cff->private[0] == NULL ||
+ !cff_dict_known(cff->private[0], "Subrs")) {
+ (cff->subrs)[0] = NULL;
+ } else {
+ offset = (long) cff_dict_get(cff->topdict, "Private", 1);
+ offset += (long) cff_dict_get(cff->private[0], "Subrs", 0);
+ cff_seek_set(cff, offset);
+ (cff->subrs)[0] = cff_get_index(cff);
+ len += cff_index_size((cff->subrs)[0]);
+ }
+ }
+
+ return len;
+}
+
+long cff_read_fdarray (cff_font *cff)
+{
+ long len = 0;
+ cff_index *idx;
+ long offset, size;
+ card16 i;
+
+ if (cff->topdict == NULL)
+ ERROR("in cff_read_fdarray(): Top DICT not found");
+
+ if (!(cff->flag & FONTTYPE_CIDFONT))
+ return 0;
+
+ /* must exist */
+ offset = (long) cff_dict_get(cff->topdict, "FDArray", 0);
+ cff_seek_set(cff, offset);
+ idx = cff_get_index(cff);
+ cff->num_fds = (card8)idx->count;
+ cff->fdarray = NEW(idx->count, cff_dict *);
+ for (i=0;i<idx->count;i++) {
+ card8 *data = idx->data + (idx->offset)[i] - 1;
+ size = (idx->offset)[i+1] - (idx->offset)[i];
+ if (size > 0) {
+ (cff->fdarray)[i] = cff_dict_unpack(data, data+size);
+ } else {
+ (cff->fdarray)[i] = NULL;
+ }
+ }
+ len = cff_index_size(idx);
+ cff_release_index(idx);
+
+ return len;
+}
+
+long cff_read_private (cff_font *cff)
+{
+ long len = 0;
+ card8 *data;
+ long offset, size;
+
+ if (cff->flag & FONTTYPE_CIDFONT) {
+ int i;
+
+ if (cff->fdarray == NULL)
+ cff_read_fdarray(cff);
+
+ cff->private = NEW(cff->num_fds, cff_dict *);
+ for (i=0;i<cff->num_fds;i++) {
+ if (cff->fdarray[i] != NULL &&
+ cff_dict_known(cff->fdarray[i], "Private") &&
+ (size = (long) cff_dict_get(cff->fdarray[i], "Private", 0))
+ > 0) {
+ offset = (long) cff_dict_get(cff->fdarray[i], "Private", 1);
+ cff_seek_set(cff, offset);
+ data = NEW(size, card8);
+ if (sfnt_read(data, size, cff->sfont) != size)
+ ERROR("reading file failed");
+ (cff->private)[i] = cff_dict_unpack(data, data+size);
+ RELEASE(data);
+ len += size;
+ } else {
+ (cff->private)[i] = NULL;
+ }
+ }
+ } else {
+ cff->num_fds = 1;
+ cff->private = NEW(1, cff_dict *);
+ if (cff_dict_known(cff->topdict, "Private") &&
+ (size = (long) cff_dict_get(cff->topdict, "Private", 0)) > 0) {
+ offset = (long) cff_dict_get(cff->topdict, "Private", 1);
+ cff_seek_set(cff, offset);
+ data = NEW(size, card8);
+ if (sfnt_read(data, size, cff->sfont) != size)
+ ERROR("reading file failed");
+ cff->private[0] = cff_dict_unpack(data, data+size);
+ RELEASE(data);
+ len += size;
+ } else {
+ (cff->private)[0] = NULL;
+ len = 0;
+ }
+ }
+
+ return len;
+}
+
+#ifdef XETEX
+unsigned short* cff_get_ft_to_gid(cff_font *cff)
+{
+ return cff->ft_to_gid;
+}
+#endif
diff --git a/Build/source/texk/dvipdf-x/xsrc/cff.h b/Build/source/texk/dvipdf-x/xsrc/cff.h
new file mode 100644
index 00000000000..9772d6d2a31
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/cff.h
@@ -0,0 +1,156 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _CFF_H_
+#define _CFF_H_
+
+#include "mfileio.h"
+#include "cff_types.h"
+
+#include "sfnt.h"
+
+/* Flag */
+#define FONTTYPE_CIDFONT (1 << 0)
+#define FONTTYPE_FONT (1 << 1)
+#define FONTTYPE_MMASTER (1 << 2)
+
+#define ENCODING_STANDARD (1 << 3)
+#define ENCODING_EXPERT (1 << 4)
+
+#define CHARSETS_ISOADOBE (1 << 5)
+#define CHARSETS_EXPERT (1 << 6)
+#define CHARSETS_EXPSUB (1 << 7)
+
+#define HAVE_STANDARD_ENCODING (ENCODING_STANDARD|ENCODING_EXPERT)
+#define HAVE_STANDARD_CHARSETS \
+ (CHARSETS_ISOADOBE|CHARSETS_EXPERT|CHARSETS_EXPSUB)
+
+#define CFF_STRING_NOTDEF 65535
+
+typedef struct
+{
+ char *fontname; /* FontName */
+
+ /* - CFF structure - */
+ cff_header header; /* CFF Header */
+ cff_index *name; /* Name INDEX */
+ cff_dict *topdict; /* Top DICT (single) */
+ cff_index *string; /* String INDEX */
+ cff_index *gsubr; /* Global Subr INDEX */
+ cff_encoding *encoding; /* Encodings */
+ cff_charsets *charsets; /* Charsets */
+ cff_fdselect *fdselect; /* FDSelect, CIDFont only */
+ cff_index *cstrings; /* CharStrings */
+ cff_dict **fdarray; /* CIDFont only */
+ cff_dict **private; /* per-Font DICT */
+ cff_index **subrs; /* Local Subr INDEX, per-Private DICT */
+
+ /* -- extra data -- */
+ l_offset offset; /* non-zero for OpenType or PostScript wrapped */
+ l_offset gsubr_offset;
+ card16 num_glyphs; /* number of glyphs (CharString INDEX count) */
+ card8 num_fds; /* number of Font DICT */
+
+ /* Updated String INDEX.
+ * Please fix this. We should separate input and output.
+ */
+ cff_index *_string;
+
+#ifdef XETEX
+ unsigned short *ft_to_gid;
+#endif
+
+ sfnt *sfont;
+ int filter; /* not used, ASCII Hex filter if needed */
+
+ int index; /* CFF fontset index */
+ int flag; /* Flag: see above */
+} cff_font;
+
+extern cff_font *cff_open (sfnt *sfont, long offset, int idx);
+extern void cff_close (cff_font *cff);
+
+#define cff_seek_set(c, p) sfnt_seek_set (((c)->sfont), ((c)->offset) + (p));
+
+/* CFF Header */
+extern long cff_put_header (cff_font *cff, card8 *dest, long destlen);
+
+/* CFF INDEX */
+extern cff_index *cff_get_index (cff_font *cff);
+extern cff_index *cff_get_index_header (cff_font *cff);
+extern void cff_release_index (cff_index *idx);
+extern cff_index *cff_new_index (card16 count);
+extern long cff_index_size (cff_index *idx);
+extern long cff_pack_index (cff_index *idx, card8 *dest, long destlen);
+
+/* Name INDEX */
+extern char *cff_get_name (cff_font *cff);
+extern long cff_set_name (cff_font *cff, char *name);
+
+/* Global and Local Subrs INDEX */
+extern long cff_read_subrs (cff_font *cff);
+
+/* Encoding */
+extern long cff_read_encoding (cff_font *cff);
+extern long cff_pack_encoding (cff_font *cff, card8 *dest, long destlen);
+extern card16 cff_encoding_lookup (cff_font *cff, card8 code);
+extern void cff_release_encoding (cff_encoding *encoding);
+
+/* Charsets */
+extern long cff_read_charsets (cff_font *cff);
+extern long cff_pack_charsets (cff_font *cff, card8 *dest, long destlen);
+
+/* Returns GID of PS name "glyph" */
+extern card16 cff_glyph_lookup (cff_font *cff, const char *glyph);
+/* Returns GID of glyph with SID/CID "cid" */
+extern card16 cff_charsets_lookup (cff_font *cff, card16 cid);
+extern void cff_release_charsets (cff_charsets *charset);
+/* Returns SID or CID */
+extern card16 cff_charsets_lookup_inverse (cff_font *cff, card16 gid);
+
+/* FDSelect */
+extern long cff_read_fdselect (cff_font *cff);
+extern long cff_pack_fdselect (cff_font *cff, card8 *dest, long destlen);
+extern card8 cff_fdselect_lookup (cff_font *cff, card16 gid);
+extern void cff_release_fdselect (cff_fdselect *fdselect);
+
+/* Font DICT(s) */
+extern long cff_read_fdarray (cff_font *cff);
+
+/* Private DICT(s) */
+extern long cff_read_private (cff_font *cff);
+
+#ifdef XETEX
+extern unsigned short* cff_get_ft_to_gid(cff_font *cff);
+#endif
+
+/* String */
+extern int cff_match_string (cff_font *cff, const char *str, s_SID sid);
+extern char *cff_get_string (cff_font *cff, s_SID id);
+extern long cff_get_sid (cff_font *cff, const char *str);
+extern long cff_get_seac_sid (cff_font *cff, const char *str);
+extern s_SID cff_add_string (cff_font *cff, const char *str, int unique);
+extern void cff_update_string (cff_font *cff);
+
+#define cff_is_stdstr(s) (cff_get_sid(NULL, (s)) >= 0)
+
+#endif /* _CFF_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/cff_dict.c b/Build/source/texk/dvipdf-x/xsrc/cff_dict.c
new file mode 100644
index 00000000000..96b30ef5d55
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/cff_dict.c
@@ -0,0 +1,720 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+/*
+ * CFF Font Dictionary
+ *
+ * Adobe Technical Note #5176 "The Compact Font Format Specification"
+ */
+
+#include <math.h>
+#include <stdlib.h>
+#include <errno.h>
+
+#include "error.h"
+#include "mem.h"
+
+#ifndef CFF_DEBUG_STR
+#define CFF_DEBUG_STR "CFF"
+#define CFF_DEBUG 5
+#endif
+
+/* work_buffer for get_real() */
+#include "mfileio.h"
+
+#include "cff_types.h"
+#include "cff_limits.h"
+
+/* #include "cff_string.h" */
+#include "cff_dict.h"
+/* cff_update_dict requires this. */
+#include "cff.h"
+
+#define CFF_PARSE_OK 0
+#define CFF_ERROR_PARSE_ERROR -1
+#define CFF_ERROR_STACK_OVERFLOW -2
+#define CFF_ERROR_STACK_UNDERFLOW -3
+#define CFF_ERROR_STACK_RANGECHECK -4
+
+#define DICT_ENTRY_MAX 16
+cff_dict *cff_new_dict (void)
+{
+ cff_dict *dict;
+
+ dict = NEW(1, cff_dict);
+ dict->max = DICT_ENTRY_MAX;
+ dict->count = 0;
+ dict->entries = NEW(dict->max, cff_dict_entry);
+
+ return dict;
+}
+
+void cff_release_dict (cff_dict *dict)
+{
+ if (dict) {
+ if (dict->entries) {
+ int i;
+ for (i=0;i<dict->count;i++) {
+ if ((dict->entries)[i].values)
+ RELEASE((dict->entries)[i].values);
+ }
+ RELEASE(dict->entries);
+ }
+ RELEASE(dict);
+ }
+}
+
+/*
+ * Operand stack:
+ * only numbers are stored (as double)
+ *
+ * Operand types:
+ *
+ * number : double (integer or real)
+ * boolean: stored as a number
+ * SID : stored as a number
+ * array : array of numbers
+ * delta : array of numbers
+ */
+
+#define CFF_DICT_STACK_LIMIT 64
+static int stack_top = 0;
+static double arg_stack[CFF_DICT_STACK_LIMIT];
+
+/*
+ * CFF DICT encoding:
+ * TODO: default values
+ */
+
+#define CFF_LAST_DICT_OP1 22
+#define CFF_LAST_DICT_OP2 39
+#define CFF_LAST_DICT_OP (CFF_LAST_DICT_OP1 + CFF_LAST_DICT_OP2)
+
+static struct {
+ const char *opname;
+ int argtype;
+} dict_operator[CFF_LAST_DICT_OP] = {
+ {"version", CFF_TYPE_SID},
+ {"Notice", CFF_TYPE_SID},
+ {"FullName", CFF_TYPE_SID},
+ {"FamilyName", CFF_TYPE_SID},
+ {"Weight", CFF_TYPE_SID},
+ {"FontBBox", CFF_TYPE_ARRAY},
+ {"BlueValues", CFF_TYPE_DELTA},
+ {"OtherBlues", CFF_TYPE_DELTA},
+ {"FamilyBlues", CFF_TYPE_DELTA},
+ {"FamilyOtherBlues", CFF_TYPE_DELTA},
+ {"StdHW", CFF_TYPE_NUMBER},
+ {"StdVW", CFF_TYPE_NUMBER},
+ {NULL, -1}, /* first byte of two-byte operator */
+ /* Top */
+ {"UniqueID", CFF_TYPE_NUMBER},
+ {"XUID", CFF_TYPE_ARRAY},
+ {"charset", CFF_TYPE_OFFSET},
+ {"Encoding", CFF_TYPE_OFFSET},
+ {"CharStrings", CFF_TYPE_OFFSET},
+ {"Private", CFF_TYPE_SZOFF}, /* two numbers (size and offset) */
+ /* Private */
+ {"Subrs", CFF_TYPE_OFFSET},
+ {"defaultWidthX", CFF_TYPE_NUMBER},
+ {"nominalWidthX", CFF_TYPE_NUMBER},
+ /* Operator 2 */
+ {"Copyright", CFF_TYPE_SID},
+ {"IsFixedPitch", CFF_TYPE_BOOLEAN},
+ {"ItalicAngle", CFF_TYPE_NUMBER},
+ {"UnderlinePosition", CFF_TYPE_NUMBER},
+ {"UnderlineThickness", CFF_TYPE_NUMBER},
+ {"PaintType", CFF_TYPE_NUMBER},
+ {"CharstringType", CFF_TYPE_NUMBER},
+ {"FontMatrix", CFF_TYPE_ARRAY},
+ {"StrokeWidth", CFF_TYPE_NUMBER},
+ {"BlueScale", CFF_TYPE_NUMBER},
+ {"BlueShift", CFF_TYPE_NUMBER},
+ {"BlueFuzz", CFF_TYPE_NUMBER},
+ {"StemSnapH", CFF_TYPE_DELTA},
+ {"StemSnapV", CFF_TYPE_DELTA},
+ {"ForceBold", CFF_TYPE_BOOLEAN},
+ {NULL, -1},
+ {NULL, -1},
+ {"LanguageGroup", CFF_TYPE_NUMBER},
+ {"ExpansionFactor", CFF_TYPE_NUMBER},
+ {"InitialRandomSeed", CFF_TYPE_NUMBER},
+ {"SyntheticBase", CFF_TYPE_NUMBER},
+ {"PostScript", CFF_TYPE_SID},
+ {"BaseFontName", CFF_TYPE_SID},
+ {"BaseFontBlend", CFF_TYPE_DELTA}, /* MMaster ? */
+ {NULL, -1},
+ {NULL, -1},
+ {NULL, -1},
+ {NULL, -1},
+ {NULL, -1},
+ {NULL, -1},
+ /* CID-Keyed font */
+ {"ROS", CFF_TYPE_ROS}, /* SID SID number */
+ {"CIDFontVersion", CFF_TYPE_NUMBER},
+ {"CIDFontRevision", CFF_TYPE_NUMBER},
+ {"CIDFontType", CFF_TYPE_NUMBER},
+ {"CIDCount", CFF_TYPE_NUMBER},
+ {"UIDBase", CFF_TYPE_NUMBER},
+ {"FDArray", CFF_TYPE_OFFSET},
+ {"FDSelect", CFF_TYPE_OFFSET},
+ {"FontName", CFF_TYPE_SID},
+};
+
+/* Parse DICT data */
+static double get_integer (card8 **data, card8 *endptr, int *status)
+{
+ long result = 0;
+ card8 b0, b1, b2;
+
+ b0 = *(*data)++;
+ if (b0 == 28 && *data < endptr - 2) { /* shortint */
+ b1 = *(*data)++;
+ b2 = *(*data)++;
+ result = b1*256+b2;
+ if (result > 0x7fffL)
+ result -= 0x10000L;
+ } else if (b0 == 29 && *data < endptr - 4) { /* longint */
+ int i;
+ result = *(*data)++;
+ if (result > 0x7f)
+ result -= 0x100;
+ for (i=0;i<3;i++) {
+ result = result*256+(**data);
+ *data += 1;
+ }
+ } else if (b0 >= 32 && b0 <= 246) { /* int (1) */
+ result = b0 - 139;
+ } else if (b0 >= 247 && b0 <= 250) { /* int (2) */
+ b1 = *(*data)++;
+ result = (b0-247)*256+b1+108;
+ } else if (b0 >= 251 && b0 <= 254) {
+ b1 = *(*data)++;
+ result = -(b0-251)*256-b1-108;
+ } else {
+ *status = CFF_ERROR_PARSE_ERROR;
+ }
+
+ return (double) result;
+}
+
+/* Simply uses strtod */
+static double get_real(card8 **data, card8 *endptr, int *status)
+{
+ double result = 0.0;
+ int nibble = 0, pos = 0;
+ int len = 0, fail = 0;
+
+ if (**data != 30 || *data >= endptr -1) {
+ *status = CFF_ERROR_PARSE_ERROR;
+ return 0.0;
+ }
+
+ *data += 1; /* skip first byte (30) */
+
+ pos = 0;
+ while ((! fail) && len < WORK_BUFFER_SIZE - 2 && *data < endptr) {
+ /* get nibble */
+ if (pos % 2) {
+ nibble = **data & 0x0f;
+ *data += 1;
+ } else {
+ nibble = (**data >> 4) & 0x0f;
+ }
+ if (nibble >= 0x00 && nibble <= 0x09) {
+ work_buffer[len++] = nibble + '0';
+ } else if (nibble == 0x0a) { /* . */
+ work_buffer[len++] = '.';
+ } else if (nibble == 0x0b || nibble == 0x0c) { /* E, E- */
+ work_buffer[len++] = 'e';
+ if (nibble == 0x0c)
+ work_buffer[len++] = '-';
+ } else if (nibble == 0x0e) { /* `-' */
+ work_buffer[len++] = '-';
+ } else if (nibble == 0x0d) { /* skip */
+ /* do nothing */
+ } else if (nibble == 0x0f) { /* end */
+ work_buffer[len++] = '\0';
+ if (((pos % 2) == 0) && (**data != 0xff)) {
+ fail = 1;
+ }
+ break;
+ } else { /* invalid */
+ fail = 1;
+ }
+ pos++;
+ }
+
+ /* returned values */
+ if (fail || nibble != 0x0f) {
+ *status = CFF_ERROR_PARSE_ERROR;
+ } else {
+ char *s;
+ result = strtod(work_buffer, &s);
+ if (*s != 0 || errno == ERANGE) {
+ *status = CFF_ERROR_PARSE_ERROR;
+ }
+ }
+
+ return result;
+}
+
+/* operators */
+static void add_dict (cff_dict *dict,
+ card8 **data, card8 *endptr, int *status)
+{
+ int id, argtype;
+
+ id = **data;
+ if (id == 0x0c) {
+ *data += 1;
+ if (*data >= endptr ||
+ (id = **data + CFF_LAST_DICT_OP1) >= CFF_LAST_DICT_OP) {
+ *status = CFF_ERROR_PARSE_ERROR;
+ return;
+ }
+ } else if (id >= CFF_LAST_DICT_OP1) {
+ *status = CFF_ERROR_PARSE_ERROR;
+ return;
+ }
+
+ argtype = dict_operator[id].argtype;
+ if (dict_operator[id].opname == NULL || argtype < 0) {
+ *status = CFF_ERROR_PARSE_ERROR;
+ return;
+ }
+
+ if (dict->count >= dict->max) {
+ dict->max += DICT_ENTRY_MAX;
+ dict->entries = RENEW(dict->entries, dict->max, cff_dict_entry);
+ }
+
+ (dict->entries)[dict->count].id = id;
+ (dict->entries)[dict->count].key = dict_operator[id].opname;
+ if (argtype == CFF_TYPE_NUMBER ||
+ argtype == CFF_TYPE_BOOLEAN ||
+ argtype == CFF_TYPE_SID ||
+ argtype == CFF_TYPE_OFFSET) {
+ /* check for underflow here, as exactly one operand is expected */
+ if (stack_top < 1) {
+ *status = CFF_ERROR_STACK_UNDERFLOW;
+ return;
+ }
+ stack_top--;
+ (dict->entries)[dict->count].count = 1;
+ (dict->entries)[dict->count].values = NEW(1, double);
+ (dict->entries)[dict->count].values[0] = arg_stack[stack_top];
+ dict->count += 1;
+ } else {
+ /* just ignore operator if there were no operands provided;
+ don't treat this as underflow (e.g. StemSnapV in TemporaLGCUni-Italic.otf) */
+ if (stack_top > 0) {
+ (dict->entries)[dict->count].count = stack_top;
+ (dict->entries)[dict->count].values = NEW(stack_top, double);
+ while (stack_top > 0) {
+ stack_top--;
+ (dict->entries)[dict->count].values[stack_top] = arg_stack[stack_top];
+ }
+ dict->count += 1;
+ }
+ }
+
+ *data += 1;
+
+ return;
+}
+
+/*
+ * All operands are treated as number or array of numbers.
+ * Private: two numbers, size and offset
+ * ROS : three numbers, SID, SID, and a number
+ */
+cff_dict *cff_dict_unpack (card8 *data, card8 *endptr)
+{
+ cff_dict *dict;
+ int status = CFF_PARSE_OK;
+
+ stack_top = 0;
+
+ dict = cff_new_dict();
+ while (data < endptr && status == CFF_PARSE_OK) {
+ if (*data < 22) { /* operator */
+ add_dict(dict, &data, endptr, &status);
+ } else if (*data == 30) { /* real - First byte of a sequence (variable) */
+ if (stack_top < CFF_DICT_STACK_LIMIT) {
+ arg_stack[stack_top] = get_real(&data, endptr, &status);
+ stack_top++;
+ } else {
+ status = CFF_ERROR_STACK_OVERFLOW;
+ }
+ } else if (*data == 255 || (*data >= 22 && *data <= 27)) { /* reserved */
+ data++;
+ } else { /* everything else are integer */
+ if (stack_top < CFF_DICT_STACK_LIMIT) {
+ arg_stack[stack_top] = get_integer(&data, endptr, &status);
+ stack_top++;
+ } else {
+ status = CFF_ERROR_STACK_OVERFLOW;
+ }
+ }
+ }
+
+ if (status != CFF_PARSE_OK) {
+ ERROR("%s: Parsing CFF DICT failed. (error=%d)", CFF_DEBUG_STR, status);
+ } else if (stack_top != 0) {
+ WARN("%s: Garbage in CFF DICT data.", CFF_DEBUG_STR);
+ stack_top = 0;
+ }
+
+ return dict;
+}
+
+/* Pack DICT data */
+static long pack_integer (card8 *dest, long destlen, long value)
+{
+ long len = 0;
+
+ if (value >= -107 && value <= 107) {
+ if (destlen < 1)
+ ERROR("%s: Buffer overflow.", CFF_DEBUG_STR);
+ dest[0] = (value + 139) & 0xff;
+ len = 1;
+ } else if (value >= 108 && value <= 1131) {
+ if (destlen < 2)
+ ERROR("%s: Buffer overflow.", CFF_DEBUG_STR);
+ value = 0xf700u + value - 108;
+ dest[0] = (value >> 8) & 0xff;
+ dest[1] = value & 0xff;
+ len = 2;
+ } else if (value >= -1131 && value <= -108) {
+ if (destlen < 2)
+ ERROR("%s: Buffer overflow.", CFF_DEBUG_STR);
+ value = 0xfb00u - value - 108;
+ dest[0] = (value >> 8) & 0xff;
+ dest[1] = value & 0xff;
+ len = 2;
+ } else if (value >= -32768 && value <= 32767) { /* shortint */
+ if (destlen < 3)
+ ERROR("%s: Buffer overflow.", CFF_DEBUG_STR);
+ dest[0] = 28;
+ dest[1] = (value >> 8) & 0xff;
+ dest[2] = value & 0xff;
+ len = 3;
+ } else { /* longint */
+ if (destlen < 5)
+ ERROR("%s: Buffer overflow.", CFF_DEBUG_STR);
+ dest[0] = 29;
+ dest[1] = (value >> 24) & 0xff;
+ dest[2] = (value >> 16) & 0xff;
+ dest[3] = (value >> 8) & 0xff;
+ dest[4] = value & 0xff;
+ len = 5;
+ }
+
+ return len;
+}
+
+static long pack_real (card8 *dest, long destlen, double value)
+{
+ int i = 0, pos = 2;
+ char buffer[32];
+
+ if (destlen < 2)
+ ERROR("%s: Buffer overflow.", CFF_DEBUG_STR);
+
+ dest[0] = 30;
+
+ if (value == 0.0) {
+ dest[1] = 0x0f;
+ return 2;
+ }
+
+ if (value < 0.0) {
+ dest[1] = 0xe0;
+ value *= -1.0;
+ pos++;
+ }
+
+ /* To avoid the problem with Mac OS X 10.4 Quartz,
+ * change the presion of the real numbers
+ * on June 27, 2007 for musix20.pfb */
+ sprintf(buffer, "%.13g", value);
+
+ for (i = 0; buffer[i] != '\0'; i++) {
+ unsigned char ch = 0;
+ if (buffer[i] == '.') {
+ ch = 0x0a;
+ } else if (buffer[i] >= '0' && buffer[i] <= '9') {
+ ch = buffer[i] - '0';
+ } else if (buffer[i] == 'e') {
+ ch = (buffer[++i] == '-' ? 0x0c : 0x0b);
+ } else {
+ ERROR("%s: Invalid character.", CFF_DEBUG_STR);
+ }
+
+ if (destlen < pos/2 + 1)
+ ERROR("%s: Buffer overflow.", CFF_DEBUG_STR);
+
+ if (pos % 2) {
+ dest[pos/2] += ch;
+ } else {
+ dest[pos/2] = (ch << 4);
+ }
+ pos++;
+ }
+
+ if (pos % 2) {
+ dest[pos/2] += 0x0f;
+ pos++;
+ } else {
+ if (destlen < pos/2 + 1)
+ ERROR("%s: Buffer overflow.", CFF_DEBUG_STR);
+ dest[pos/2] = 0xff;
+ pos += 2;
+ }
+
+ return pos/2;
+}
+
+static long cff_dict_put_number (double value,
+ card8 *dest, long destlen,
+ int type)
+{
+ long len = 0;
+ double nearint;
+
+ nearint = floor(value+0.5);
+ /* set offset to longint */
+ if (type == CFF_TYPE_OFFSET) {
+ long lvalue;
+
+ lvalue = (long) value;
+ if (destlen < 5)
+ ERROR("%s: Buffer overflow.", CFF_DEBUG_STR);
+ dest[0] = 29;
+ dest[1] = (lvalue >> 24) & 0xff;
+ dest[2] = (lvalue >> 16) & 0xff;
+ dest[3] = (lvalue >> 8) & 0xff;
+ dest[4] = lvalue & 0xff;
+ len = 5;
+ } else if (value > CFF_INT_MAX || value < CFF_INT_MIN ||
+ (fabs(value - nearint) > 1.0e-5)) { /* real */
+ len = pack_real(dest, destlen, value);
+ } else { /* integer */
+ len = pack_integer(dest, destlen, (long) nearint);
+ }
+
+ return len;
+}
+
+static long
+put_dict_entry (cff_dict_entry *de,
+ card8 *dest, long destlen)
+{
+ long len = 0;
+ int i, type, id;
+
+ if (de->count > 0) {
+ id = de->id;
+ if (dict_operator[id].argtype == CFF_TYPE_OFFSET ||
+ dict_operator[id].argtype == CFF_TYPE_SZOFF) {
+ type = CFF_TYPE_OFFSET;
+ } else {
+ type = CFF_TYPE_NUMBER;
+ }
+ for (i = 0; i < de->count; i++) {
+ len += cff_dict_put_number(de->values[i],
+ dest+len,
+ destlen-len, type);
+ }
+ if (id >= 0 && id < CFF_LAST_DICT_OP1) {
+ if (len + 1 > destlen)
+ ERROR("%s: Buffer overflow.", CFF_DEBUG_STR);
+ dest[len++] = id;
+ } else if (id >= 0 && id < CFF_LAST_DICT_OP) {
+ if (len + 2 > destlen)
+ ERROR("in cff_dict_pack(): Buffer overflow");
+ dest[len++] = 12;
+ dest[len++] = id - CFF_LAST_DICT_OP1;
+ } else {
+ ERROR("%s: Invalid CFF DICT operator ID.", CFF_DEBUG_STR);
+ }
+ }
+
+ return len;
+}
+
+long cff_dict_pack (cff_dict *dict, card8 *dest, long destlen)
+{
+ long len = 0;
+ int i;
+
+ for (i = 0; i < dict->count; i++) {
+ if (!strcmp(dict->entries[i].key, "ROS")) {
+ len += put_dict_entry(&dict->entries[i], dest, destlen);
+ break;
+ }
+ }
+ for (i = 0; i < dict->count; i++) {
+ if (strcmp(dict->entries[i].key, "ROS")) {
+ len += put_dict_entry(&dict->entries[i], dest+len, destlen-len);
+ }
+ }
+
+ return len;
+}
+
+void cff_dict_add (cff_dict *dict, const char *key, int count)
+{
+ int id, i;
+
+ for (id=0;id<CFF_LAST_DICT_OP;id++) {
+ if (key && dict_operator[id].opname &&
+ strcmp(dict_operator[id].opname, key) == 0)
+ break;
+ }
+
+ if (id == CFF_LAST_DICT_OP)
+ ERROR("%s: Unknown CFF DICT operator.", CFF_DEBUG_STR);
+
+ for (i=0;i<dict->count;i++) {
+ if ((dict->entries)[i].id == id) {
+ if ((dict->entries)[i].count != count)
+ ERROR("%s: Inconsistent DICT argument number.", CFF_DEBUG_STR);
+ return;
+ }
+ }
+
+ if (dict->count + 1 >= dict->max) {
+ dict->max += 8;
+ dict->entries = RENEW(dict->entries, dict->max, cff_dict_entry);
+ }
+
+ (dict->entries)[dict->count].id = id;
+ (dict->entries)[dict->count].key = dict_operator[id].opname;
+ (dict->entries)[dict->count].count = count;
+ if (count > 0) {
+ (dict->entries)[dict->count].values = NEW(count, double);
+ memset((dict->entries)[dict->count].values,
+ 0, sizeof(double)*count);
+ } else {
+ (dict->entries)[dict->count].values = NULL;
+ }
+ dict->count += 1;
+
+ return;
+}
+
+void cff_dict_remove (cff_dict *dict, const char *key)
+{
+ int i;
+ for (i = 0; i < dict->count; i++) {
+ if (key && strcmp(key, (dict->entries)[i].key) == 0) {
+ (dict->entries)[i].count = 0;
+ if ((dict->entries)[i].values)
+ RELEASE((dict->entries)[i].values);
+ (dict->entries)[i].values = NULL;
+ }
+ }
+}
+
+int cff_dict_known (cff_dict *dict, const char *key)
+{
+ int i;
+
+ for (i = 0; i < dict->count; i++) {
+ if (key && strcmp(key, (dict->entries)[i].key) == 0
+ && (dict->entries)[i].count > 0)
+ return 1;
+ }
+
+ return 0;
+}
+
+double cff_dict_get (cff_dict *dict, const char *key, int idx)
+{
+ double value = 0.0;
+ int i;
+
+ ASSERT(key && dict);
+
+ for (i = 0; i < dict->count; i++) {
+ if (strcmp(key, (dict->entries)[i].key) == 0) {
+ if ((dict->entries)[i].count > idx)
+ value = (dict->entries)[i].values[idx];
+ else
+ ERROR("%s: Invalid index number.", CFF_DEBUG_STR);
+ break;
+ }
+ }
+
+ if (i == dict->count)
+ ERROR("%s: DICT entry \"%s\" not found.", CFF_DEBUG_STR, key);
+
+ return value;
+}
+
+void cff_dict_set (cff_dict *dict, const char *key, int idx, double value)
+{
+ int i;
+
+ ASSERT(dict && key);
+
+ for (i = 0 ; i < dict->count; i++) {
+ if (strcmp(key, (dict->entries)[i].key) == 0) {
+ if ((dict->entries)[i].count > idx)
+ (dict->entries)[i].values[idx] = value;
+ else
+ ERROR("%s: Invalid index number.", CFF_DEBUG_STR);
+ break;
+ }
+ }
+
+ if (i == dict->count)
+ ERROR("%s: DICT entry \"%s\" not found.", CFF_DEBUG_STR, key);
+}
+
+void cff_dict_update (cff_dict *dict, cff_font *cff)
+{
+ int i;
+
+ for (i = 0;i < dict->count; i++) {
+ if ((dict->entries)[i].count > 0) {
+ char *str;
+ int id;
+
+ id = (dict->entries)[i].id;
+ if (dict_operator[id].argtype == CFF_TYPE_SID) {
+ str = cff_get_string(cff, (dict->entries)[i].values[0]);
+ (dict->entries)[i].values[0] = cff_add_string(cff, str, 1);
+ RELEASE(str);
+ } else if (dict_operator[id].argtype == CFF_TYPE_ROS) {
+ str = cff_get_string(cff, (dict->entries)[i].values[0]);
+ (dict->entries)[i].values[0] = cff_add_string(cff, str, 1);
+ RELEASE(str);
+ str = cff_get_string(cff, (dict->entries)[i].values[1]);
+ (dict->entries)[i].values[1] = cff_add_string(cff, str, 1);
+ RELEASE(str);
+ }
+ }
+ }
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/cidtype0.c b/Build/source/texk/dvipdf-x/xsrc/cidtype0.c
new file mode 100644
index 00000000000..316f5c68073
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/cidtype0.c
@@ -0,0 +1,2075 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2007-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+/*
+ * CID-Keyed Font support:
+ *
+ * Only CFF/OpenType CID-Keyed Font with Type 2 charstrings is supported.
+ *
+ */
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "system.h"
+#include "numbers.h"
+#include "mem.h"
+#include "error.h"
+
+#include "dpxfile.h"
+
+#include "pdfobj.h"
+/* pseudo unique tag */
+#include "pdffont.h"
+
+/* Font info. from OpenType tables */
+#include "sfnt.h"
+#include "tt_aux.h"
+/* Metrics */
+#include "tt_table.h"
+
+#include "cff_types.h"
+#include "cff_limits.h"
+#include "cff.h"
+#include "cff_dict.h"
+#include "cs_type2.h"
+
+/* typedef CID in cmap.h */
+#include "cmap.h"
+#include "type0.h"
+#include "cid.h"
+#include "cid_p.h"
+#include "cidtype0.h"
+
+static int verbose = 0;
+static long opt_flags = 0;
+
+void
+CIDFont_type0_set_verbose (void)
+{
+ verbose++;
+}
+
+void
+CIDFont_type0_set_flags (long flags)
+{
+ opt_flags = flags;
+}
+
+/*
+ * PDF Reference 3rd. ed., p.340, "Glyph Metrics in CID Fonts".
+ */
+#ifndef PDFUNIT
+#define PDFUNIT(v) (ROUND((1000.0*(v))/(head->unitsPerEm),1))
+#endif
+
+static void
+add_CIDHMetrics (sfnt *sfont, pdf_obj *fontdict,
+ unsigned char *CIDToGIDMap, unsigned short last_cid,
+ struct tt_maxp_table *maxp,
+ struct tt_head_table *head, struct tt_longMetrics *hmtx)
+{
+ pdf_obj *w_array, *an_array = NULL;
+ long cid, start = 0, prev = 0;
+ double defaultAdvanceWidth;
+ int empty = 1;
+
+ defaultAdvanceWidth = PDFUNIT(hmtx[0].advance);
+ /*
+ * We alway use format:
+ * c [w_1 w_2 ... w_n]
+ */
+ w_array = pdf_new_array();
+ for (cid = 0; cid <= last_cid; cid++) {
+ USHORT gid;
+ double advanceWidth;
+ gid = CIDToGIDMap ? ((CIDToGIDMap[2*cid] << 8)|CIDToGIDMap[2*cid+1]) : cid;
+ if (gid >= maxp->numGlyphs || (cid != 0 && gid == 0))
+ continue;
+ advanceWidth = PDFUNIT(hmtx[gid].advance);
+ if (advanceWidth == defaultAdvanceWidth) {
+ if (an_array) {
+ pdf_add_array(w_array, pdf_new_number(start));
+ pdf_add_array(w_array, an_array);
+ an_array = NULL;
+ empty = 0;
+ }
+ } else {
+ if (cid != prev + 1 && an_array) {
+ pdf_add_array(w_array, pdf_new_number(start));
+ pdf_add_array(w_array, an_array);
+ an_array = NULL;
+ empty = 0;
+ }
+ if (an_array == NULL) {
+ an_array = pdf_new_array();
+ start = cid;
+ }
+ pdf_add_array(an_array, pdf_new_number(advanceWidth));
+ prev = cid;
+ }
+ }
+
+ if (an_array) {
+ pdf_add_array(w_array, pdf_new_number(start));
+ pdf_add_array(w_array, an_array);
+ empty = 0;
+ }
+
+ /*
+ * We always write DW for older MacOS X's preview app.
+ * PDF Reference 2nd. ed, wrongly described default value of DW as 0, and
+ * MacOS X's (up to 10.2.8) preview app. implements this wrong description.
+ */
+ pdf_add_dict(fontdict,
+ pdf_new_name("DW"),
+ pdf_new_number(defaultAdvanceWidth));
+ if (!empty) {
+ pdf_add_dict(fontdict,
+ pdf_new_name("W"),
+ pdf_ref_obj(w_array));
+ }
+ pdf_release_obj(w_array);
+
+ return;
+}
+
+static void
+add_CIDVMetrics (sfnt *sfont, pdf_obj *fontdict,
+ unsigned char *CIDToGIDMap, unsigned short last_cid,
+ struct tt_maxp_table *maxp,
+ struct tt_head_table *head, struct tt_longMetrics *hmtx)
+{
+ pdf_obj *w2_array, *an_array = NULL;
+ long cid;
+#if 0
+ long prev = 0, start = 0;
+#endif
+ struct tt_VORG_table *vorg;
+ struct tt_vhea_table *vhea = NULL;
+ struct tt_longMetrics *vmtx = NULL;
+ double defaultAdvanceHeight, defaultVertOriginY;
+ int empty = 1;
+
+ /*
+ * No accurate vertical metrics can be obtained by simple way if the
+ * font does not have VORG table. Only CJK fonts may have VORG.
+ */
+ if (sfnt_find_table_pos(sfont, "VORG") <= 0)
+ return;
+
+ vorg = tt_read_VORG_table(sfont);
+ defaultVertOriginY = PDFUNIT(vorg->defaultVertOriginY);
+ if (sfnt_find_table_pos(sfont, "vhea") > 0)
+ vhea = tt_read_vhea_table(sfont);
+ if (vhea && sfnt_find_table_pos(sfont, "vmtx") > 0) {
+ sfnt_locate_table(sfont, "vmtx");
+ vmtx = tt_read_longMetrics(sfont, maxp->numGlyphs, vhea->numOfLongVerMetrics, vhea->numOfExSideBearings);
+ }
+
+ if (sfnt_find_table_pos(sfont, "OS/2") <= 0) {
+ struct tt_os2__table *os2;
+ /* OpenType font must have OS/2 table. */
+ os2 = tt_read_os2__table(sfont);
+ defaultVertOriginY = PDFUNIT(os2->sTypoAscender);
+ defaultAdvanceHeight = PDFUNIT(os2->sTypoAscender - os2->sTypoDescender);
+ RELEASE(os2);
+ } else {
+ /* Some TrueType fonts used in Macintosh does not have OS/2 table. */
+ defaultAdvanceHeight = 1000;
+ }
+
+ w2_array = pdf_new_array();
+ for (cid = 0; cid <= last_cid; cid++) {
+ USHORT i, gid;
+ double advanceHeight, vertOriginX, vertOriginY;
+ gid = CIDToGIDMap ? ((CIDToGIDMap[2*cid] << 8)|CIDToGIDMap[2*cid+1]) : cid;
+ if (gid >= maxp->numGlyphs || (cid != 0 && gid == 0))
+ continue;
+ advanceHeight = vmtx ? PDFUNIT(vmtx[gid].advance) : defaultAdvanceHeight;
+ vertOriginX = PDFUNIT(hmtx[gid].advance*0.5);
+ vertOriginY = defaultVertOriginY;
+ for (i = 0;
+ i < vorg->numVertOriginYMetrics && gid > vorg->vertOriginYMetrics[i].glyphIndex;
+ i++) {
+ if (gid == vorg->vertOriginYMetrics[i].glyphIndex)
+ vertOriginY = PDFUNIT(vorg->vertOriginYMetrics[i].vertOriginY);
+ }
+#if 0
+ /*
+ * c [w1_1y v_1x v_1y w1_2y v_2x v_2y ...]
+ * Not working... Why?
+ * Acrobat Reader:
+ * Wrong rendering, interpretation of position vector is wrong.
+ * Xpdf and gs: ignores W2?
+ */
+ if (vertOriginY == defaultVertOriginY &&
+ advanceHeight == defaultAdvanceHeight) {
+ if (an_array) {
+ pdf_add_array(w2_array, pdf_new_number(start));
+ pdf_add_array(w2_array, an_array);
+ an_array = NULL;
+ empty = 0;
+ }
+ } else {
+ if (cid != prev + 1 && an_array) {
+ pdf_add_array(w2_array, pdf_new_number(start));
+ pdf_add_array(w2_array, an_array);
+ an_array = NULL;
+ empty = 0;
+ }
+ if (an_array == NULL) {
+ an_array = pdf_new_array();
+ start = cid;
+ }
+ pdf_add_array(an_array, pdf_new_number(-advanceHeight));
+ pdf_add_array(an_array, pdf_new_number(vertOriginX));
+ pdf_add_array(an_array, pdf_new_number(vertOriginY));
+ prev = cid;
+ }
+#else
+ /*
+ * c_first c_last w1_y v_x v_y
+ * This form may hit Acrobat's implementation limit of array element size, 8192.
+ * AFPL GhostScript 8.11 stops with rangecheck error with this. Maybe GS's bug?
+ */
+ if (vertOriginY != defaultVertOriginY ||
+ advanceHeight != defaultAdvanceHeight) {
+ pdf_add_array(w2_array, pdf_new_number(cid));
+ pdf_add_array(w2_array, pdf_new_number(cid));
+ pdf_add_array(w2_array, pdf_new_number(-advanceHeight));
+ pdf_add_array(w2_array, pdf_new_number(vertOriginX));
+ pdf_add_array(w2_array, pdf_new_number(vertOriginY));
+ empty = 0;
+ }
+#endif
+ }
+
+#if 0
+ if (an_array) {
+ pdf_add_array(w2_array, pdf_new_number(start));
+ pdf_add_array(w2_array, an_array);
+ empty = 0;
+ }
+#endif
+
+ if (defaultVertOriginY != 880 || defaultAdvanceHeight != 1000) {
+ an_array = pdf_new_array();
+ pdf_add_array(an_array, pdf_new_number(defaultVertOriginY));
+ pdf_add_array(an_array, pdf_new_number(-defaultAdvanceHeight));
+ pdf_add_dict(fontdict, pdf_new_name ("DW2"), an_array);
+ }
+ if (!empty) {
+ pdf_add_dict(fontdict,
+ pdf_new_name("W2"), pdf_ref_obj(w2_array));
+ }
+ pdf_release_obj(w2_array);
+
+ if (vorg->vertOriginYMetrics)
+ RELEASE(vorg->vertOriginYMetrics);
+ RELEASE(vorg);
+
+ if (vmtx)
+ RELEASE(vmtx);
+ if (vhea)
+ RELEASE(vhea);
+
+ return;
+}
+
+static void
+add_CIDMetrics (sfnt *sfont, pdf_obj *fontdict,
+ unsigned char *CIDToGIDMap, unsigned short last_cid, int need_vmetrics)
+{
+ struct tt_longMetrics *hmtx;
+ struct tt_head_table *head;
+ struct tt_hhea_table *hhea;
+ struct tt_maxp_table *maxp;
+
+ /*
+ * Read head, hhea, maxp:
+ *
+ * unitsPerEm --> head
+ * numHMetrics --> hhea
+ * numGlyphs --> maxp
+ */
+ head = tt_read_head_table(sfont);
+ maxp = tt_read_maxp_table(sfont);
+ hhea = tt_read_hhea_table(sfont);
+
+ sfnt_locate_table(sfont, "hmtx");
+ hmtx = tt_read_longMetrics(sfont, maxp->numGlyphs, hhea->numOfLongHorMetrics, hhea->numOfExSideBearings);
+
+ add_CIDHMetrics(sfont, fontdict, CIDToGIDMap, last_cid, maxp, head, hmtx);
+ if (need_vmetrics)
+ add_CIDVMetrics(sfont, fontdict, CIDToGIDMap, last_cid, maxp, head, hmtx);
+
+ RELEASE(hmtx);
+ RELEASE(hhea);
+ RELEASE(maxp);
+ RELEASE(head);
+
+ return;
+}
+
+/*
+ * Create an instance of embeddable font.
+ */
+static long
+write_fontfile (CIDFont *font, cff_font *cffont)
+{
+ cff_index *topdict, *fdarray, *private;
+ unsigned char *dest;
+ long destlen = 0, i, size;
+ long offset, topdict_offset, fdarray_offset;
+
+ /* DICT sizes (offset set to long int) */
+ topdict = cff_new_index(1);
+ fdarray = cff_new_index(cffont->num_fds);
+ private = cff_new_index(cffont->num_fds);
+
+ cff_dict_remove(cffont->topdict, "UniqueID");
+ cff_dict_remove(cffont->topdict, "XUID");
+ cff_dict_remove(cffont->topdict, "Private"); /* some bad font may have */
+ cff_dict_remove(cffont->topdict, "Encoding"); /* some bad font may have */
+
+ topdict->offset[1] = cff_dict_pack(cffont->topdict,
+ (card8 *) work_buffer,
+ WORK_BUFFER_SIZE) + 1;
+ for (i = 0;i < cffont->num_fds; i++) {
+ size = 0;
+ if (cffont->private && cffont->private[i]) {
+ size = cff_dict_pack(cffont->private[i],
+ (card8 *) work_buffer, WORK_BUFFER_SIZE);
+ if (size < 1) { /* Private had contained only Subr */
+ cff_dict_remove(cffont->fdarray[i], "Private");
+ }
+ }
+ (private->offset)[i+1] = (private->offset)[i] + size;
+ (fdarray->offset)[i+1] = (fdarray->offset)[i] +
+ cff_dict_pack(cffont->fdarray[i],
+ (card8 *) work_buffer, WORK_BUFFER_SIZE);
+ }
+
+ destlen = 4; /* header size */
+ destlen += cff_set_name(cffont, font->fontname);
+ destlen += cff_index_size(topdict);
+ destlen += cff_index_size(cffont->string);
+ destlen += cff_index_size(cffont->gsubr);
+ destlen += (cffont->charsets->num_entries) * 2 + 1; /* charset format 0 */
+ destlen += (cffont->fdselect->num_entries) * 3 + 5; /* fdselect format 3 */
+ destlen += cff_index_size(cffont->cstrings);
+ destlen += cff_index_size(fdarray);
+ destlen += private->offset[private->count] - 1; /* Private is not INDEX */
+
+ dest = NEW(destlen, card8);
+
+ offset = 0;
+ /* Header */
+ offset += cff_put_header(cffont, dest + offset, destlen - offset);
+ /* Name */
+ offset += cff_pack_index(cffont->name, dest + offset, destlen - offset);
+ /* Top DICT */
+ topdict_offset = offset;
+ offset += cff_index_size(topdict);
+ /* Strings */
+ offset += cff_pack_index(cffont->string, dest + offset, destlen - offset);
+ /* Global Subrs */
+ offset += cff_pack_index(cffont->gsubr, dest + offset, destlen - offset);
+
+ /* charset */
+ cff_dict_set(cffont->topdict, "charset", 0, offset);
+ offset += cff_pack_charsets(cffont, dest + offset, destlen - offset);
+
+ /* FDSelect */
+ cff_dict_set(cffont->topdict, "FDSelect", 0, offset);
+ offset += cff_pack_fdselect(cffont, dest + offset, destlen - offset);
+
+ /* CharStrings */
+ cff_dict_set(cffont->topdict, "CharStrings", 0, offset);
+ offset += cff_pack_index(cffont->cstrings,
+ dest + offset, cff_index_size(cffont->cstrings));
+ cff_release_index(cffont->cstrings);
+ cffont->cstrings = NULL; /* Charstrings cosumes huge memory */
+
+ /* FDArray and Private */
+ cff_dict_set(cffont->topdict, "FDArray", 0, offset);
+ fdarray_offset = offset;
+ offset += cff_index_size(fdarray);
+
+ fdarray->data = NEW(fdarray->offset[fdarray->count] - 1, card8);
+ for (i = 0; i < cffont->num_fds; i++) {
+ size = private->offset[i+1] - private->offset[i];
+ if (cffont->private[i] && size > 0) {
+ cff_dict_pack(cffont->private[i], dest + offset, size);
+ cff_dict_set(cffont->fdarray[i], "Private", 0, size);
+ cff_dict_set(cffont->fdarray[i], "Private", 1, offset);
+ }
+ cff_dict_pack(cffont->fdarray[i],
+ fdarray->data + (fdarray->offset)[i] - 1,
+ fdarray->offset[fdarray->count] - 1);
+ offset += size;
+ }
+
+ cff_pack_index(fdarray, dest + fdarray_offset, cff_index_size(fdarray));
+ cff_release_index(fdarray);
+ cff_release_index(private);
+
+ /* Finally Top DICT */
+ topdict->data = NEW(topdict->offset[topdict->count] - 1, card8);
+ cff_dict_pack(cffont->topdict,
+ topdict->data, topdict->offset[topdict->count] - 1);
+ cff_pack_index(topdict, dest + topdict_offset, cff_index_size(topdict));
+ cff_release_index(topdict);
+
+ /*
+ * FontFile
+ */
+ {
+ pdf_obj *fontfile, *stream_dict;
+
+ fontfile = pdf_new_stream(STREAM_COMPRESS);
+ stream_dict = pdf_stream_dict(fontfile);
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("FontFile3"),
+ pdf_ref_obj (fontfile));
+ pdf_add_dict(stream_dict,
+ pdf_new_name("Subtype"),
+ pdf_new_name("CIDFontType0C"));
+ pdf_add_stream(fontfile, (char *) dest, offset);
+ pdf_release_obj(fontfile);
+ RELEASE(dest);
+ }
+
+ return destlen;
+}
+
+void
+CIDFont_type0_dofont (CIDFont *font)
+{
+ sfnt *sfont;
+ cff_font *cffont;
+ FILE *fp = NULL;
+ cff_index *charstrings, *idx;
+ cff_charsets *charset = NULL;
+ cff_fdselect *fdselect = NULL;
+ long charstring_len, max_len;
+ long destlen = 0;
+ long size, offset = 0;
+ card8 *data;
+ card16 num_glyphs, gid;
+ long cid, cid_count;
+ card16 cs_count, last_cid;
+ int fd, prev_fd, parent_id;
+ char *used_chars;
+ unsigned char *CIDToGIDMap = NULL;
+
+ ASSERT(font);
+
+ if (!font->indirect)
+ return;
+
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("FontDescriptor"),
+ pdf_ref_obj (font->descriptor));
+
+ if (CIDFont_is_BaseFont(font))
+ return;
+ else if (!CIDFont_get_embedding(font) &&
+ (opt_flags & CIDFONT_FORCE_FIXEDPITCH)) {
+ /* No metrics needed. */
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("DW"), pdf_new_number(1000.0));
+ return;
+ }
+
+ if ((parent_id = CIDFont_get_parent_id(font, 0)) < 0 &&
+ (parent_id = CIDFont_get_parent_id(font, 1)) < 0)
+ ERROR("No parent Type 0 font !");
+
+ used_chars = Type0Font_get_usedchars(Type0Font_cache_get(parent_id));
+ if (!used_chars)
+ ERROR("Unexpected error: Font not actually used???");
+
+#ifdef XETEX
+ sfont = sfnt_open(font->ft_face, SFNT_TYPE_POSTSCRIPT);
+#else
+ fp = DPXFOPEN(font->ident, DPX_RES_TYPE_OTFONT);
+ if (!fp)
+ ERROR("Could not open OpenType font file: %s", font->ident);
+ sfont = sfnt_open(fp);
+#endif
+ if (!sfont)
+ ERROR("Could not open OpenType font file: %s", font->ident);
+
+ if (sfnt_read_table_directory(sfont, 0) < 0 ||
+ sfont->type != SFNT_TYPE_POSTSCRIPT)
+ ERROR("Not a CFF/OpenType font ?");
+ offset = sfnt_find_table_pos(sfont, "CFF ");
+ if (offset == 0)
+ ERROR("Not a CFF/OpenType font ?");
+
+ cffont = cff_open(sfont, offset, font->options->index);
+ if (!cffont)
+ ERROR("Could not open CFF font.");
+ if (!(cffont->flag & FONTTYPE_CIDFONT))
+ ERROR("Not a CIDFont.");
+
+ if (cff_dict_known(cffont->topdict, "CIDCount")) {
+ cid_count = (long) cff_dict_get(cffont->topdict, "CIDCount", 0);
+ } else {
+ cid_count = CID_MAX + 1;
+ }
+
+ cff_read_charsets(cffont);
+ CIDToGIDMap = NEW(2*cid_count, unsigned char);
+ memset(CIDToGIDMap, 0, 2*cid_count);
+ add_to_used_chars2(used_chars, 0); /* .notdef */
+ cid = 0; last_cid = 0; num_glyphs = 0;
+ for (cid = 0; cid <= CID_MAX; cid++) {
+ if (is_used_char2(used_chars, cid)) {
+ gid = cff_charsets_lookup(cffont, (card16)cid);
+ if (cid != 0 && gid == 0) {
+ WARN("Glyph for CID %u missing in font \"%s\".", (CID) cid, font->ident);
+ used_chars[cid/8] &= ~(1 << (7 - (cid % 8)));
+ continue;
+ }
+ CIDToGIDMap[2*cid] = (gid >> 8) & 0xff;
+ CIDToGIDMap[2*cid+1] = gid & 0xff;
+ last_cid = cid;
+ num_glyphs++;
+ }
+ }
+
+ /*
+ * DW, W, DW2 and W2:
+ * Those values are obtained from OpenType table (not TFM).
+ */
+ if (opt_flags & CIDFONT_FORCE_FIXEDPITCH) {
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("DW"), pdf_new_number(1000.0));
+ } else {
+ add_CIDMetrics(sfont, font->fontdict, CIDToGIDMap, last_cid,
+ ((CIDFont_get_parent_id(font, 1) < 0) ? 0 : 1));
+ }
+
+ if (!CIDFont_get_embedding(font)) {
+ RELEASE(CIDToGIDMap);
+ cff_close(cffont);
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+
+ return;
+ }
+
+ /*
+ * Embed font subset.
+ */
+ cff_read_fdselect(cffont);
+ cff_read_fdarray(cffont);
+ cff_read_private(cffont);
+
+ cff_read_subrs(cffont);
+
+ offset = (long) cff_dict_get(cffont->topdict, "CharStrings", 0);
+ cff_seek_set(cffont, offset);
+ idx = cff_get_index_header(cffont);
+ /* offset is now absolute offset ... bad */
+ offset = cffont->sfont->loc;
+
+ if ((cs_count = idx->count) < 2) {
+ ERROR("No valid charstring data found.");
+ }
+
+ /* New Charsets data */
+ charset = NEW(1, cff_charsets);
+ charset->format = 0;
+ charset->num_entries = 0;
+ charset->data.glyphs = NEW(num_glyphs, s_SID);
+
+ /* New FDSelect data */
+ fdselect = NEW(1, cff_fdselect);
+ fdselect->format = 3;
+ fdselect->num_entries = 0;
+ fdselect->data.ranges = NEW(num_glyphs, cff_range3);
+
+ /* New CharStrings INDEX */
+ charstrings = cff_new_index((card16)(num_glyphs+1));
+ max_len = 2 * CS_STR_LEN_MAX;
+ charstrings->data = NEW(max_len, card8);
+ charstring_len = 0;
+
+ /*
+ * TODO: Re-assign FD number.
+ */
+ prev_fd = -1; gid = 0;
+ data = NEW(CS_STR_LEN_MAX, card8);
+ for (cid = 0; cid <= last_cid; cid++) {
+ unsigned short gid_org;
+
+ if (!is_used_char2(used_chars, cid))
+ continue;
+
+ gid_org = (CIDToGIDMap[2*cid] << 8)|(CIDToGIDMap[2*cid+1]);
+ if ((size = (idx->offset)[gid_org+1] - (idx->offset)[gid_org])
+ > CS_STR_LEN_MAX)
+ ERROR("Charstring too long: gid=%u", gid_org);
+ if (charstring_len + CS_STR_LEN_MAX >= max_len) {
+ max_len = charstring_len + 2 * CS_STR_LEN_MAX;
+ charstrings->data = RENEW(charstrings->data, max_len, card8);
+ }
+ (charstrings->offset)[gid] = charstring_len + 1;
+ sfnt_seek_set(cffont->sfont, offset + (idx->offset)[gid_org] - 1);
+ sfnt_read(data, size, cffont->sfont);
+ fd = cff_fdselect_lookup(cffont, gid_org);
+ charstring_len += cs_copy_charstring(charstrings->data + charstring_len,
+ max_len - charstring_len,
+ data, size,
+ cffont->gsubr, (cffont->subrs)[fd], 0, 0, NULL);
+ if (cid > 0 && gid_org > 0) {
+ charset->data.glyphs[charset->num_entries] = cid;
+ charset->num_entries += 1;
+ }
+ if (fd != prev_fd) {
+ fdselect->data.ranges[fdselect->num_entries].first = gid;
+ fdselect->data.ranges[fdselect->num_entries].fd = fd;
+ fdselect->num_entries += 1;
+ prev_fd = fd;
+ }
+ gid++;
+ }
+ if (gid != num_glyphs)
+ ERROR("Unexpeced error: ?????");
+ RELEASE(data);
+ cff_release_index(idx);
+
+ RELEASE(CIDToGIDMap);
+
+ (charstrings->offset)[num_glyphs] = charstring_len + 1;
+ charstrings->count = num_glyphs;
+ cffont->num_glyphs = num_glyphs;
+ cffont->cstrings = charstrings;
+
+ /* discard old one, set new data */
+ cff_release_charsets(cffont->charsets);
+ cffont->charsets = charset;
+ cff_release_fdselect(cffont->fdselect);
+ cffont->fdselect = fdselect;
+
+ /* no Global subr */
+ if (cffont->gsubr)
+ cff_release_index(cffont->gsubr);
+ cffont->gsubr = cff_new_index(0);
+
+ for (fd = 0; fd < cffont->num_fds; fd++) {
+ if (cffont->subrs && cffont->subrs[fd]) {
+ cff_release_index(cffont->subrs[fd]);
+ cffont->subrs[fd] = NULL;
+ }
+ if (cffont->private && (cffont->private)[fd]) {
+ cff_dict_remove((cffont->private)[fd], "Subrs"); /* no Subrs */
+ }
+ }
+
+ destlen = write_fontfile(font, cffont);
+
+ cff_close(cffont);
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+
+ if (verbose > 1)
+ MESG("[%u/%u glyphs][%ld bytes]", num_glyphs, cs_count, destlen);
+
+ /*
+ * CIDSet:
+ * Length of CIDSet stream is not clear. Must be 8192 bytes long?
+ */
+ {
+ pdf_obj *cidset;
+
+ cidset = pdf_new_stream(STREAM_COMPRESS);
+ pdf_add_stream(cidset, used_chars, (last_cid/8)+1);
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("CIDSet"), pdf_ref_obj(cidset));
+ pdf_release_obj(cidset);
+ }
+
+ return;
+}
+
+int
+CIDFont_type0_open (CIDFont *font, const char *name,
+ CIDSysInfo *cmap_csi, cid_opt *opt)
+{
+ CIDSysInfo *csi;
+ char *fontname;
+ sfnt *sfont;
+ cff_font *cffont;
+ FILE *fp = NULL;
+ unsigned long offset = 0;
+
+ ASSERT(font);
+
+#ifdef XETEX
+ sfont = sfnt_open(font->ft_face, SFNT_TYPE_POSTSCRIPT);
+ if (!sfont)
+ return -1;
+#else
+ fp = DPXFOPEN(name, DPX_RES_TYPE_OTFONT);
+ if (!fp)
+ return -1;
+
+ sfont = sfnt_open(fp);
+ if (!sfont) {
+ ERROR("Not a CFF/OpenType font?");
+ }
+#endif
+ if (sfont->type != SFNT_TYPE_POSTSCRIPT ||
+ sfnt_read_table_directory(sfont, 0) < 0 ||
+ (offset = sfnt_find_table_pos(sfont, "CFF ")) == 0) {
+ ERROR("Not a CFF/OpenType font?");
+ }
+
+ cffont = cff_open(sfont, offset, opt->index);
+ if (!cffont) {
+ ERROR("Cannot read CFF font data");
+ }
+
+ if (!(cffont->flag & FONTTYPE_CIDFONT)) {
+ cff_close(cffont);
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+ return -1;
+ }
+
+ csi = NEW(1, CIDSysInfo);
+ csi->registry =
+ cff_get_string(cffont, (s_SID)cff_dict_get(cffont->topdict, "ROS", 0));
+ csi->ordering =
+ cff_get_string(cffont, (s_SID)cff_dict_get(cffont->topdict, "ROS", 1));
+ csi->supplement = (int)cff_dict_get(cffont->topdict, "ROS", 2);
+
+ if (cmap_csi) {
+ if (strcmp(csi->registry, cmap_csi->registry) != 0 ||
+ strcmp(csi->ordering, cmap_csi->ordering) != 0) {
+ MESG("\nCharacter collection mismatched:\n");
+ MESG("\tFont: %s-%s-%d\n", csi->registry, csi->ordering, csi->supplement);
+ MESG("\tCMap: %s-%s-%d\n", cmap_csi->registry, cmap_csi->ordering, cmap_csi->supplement);
+ ERROR("Inconsistent CMap specified for this font.");
+ }
+ if (csi->supplement < cmap_csi->supplement) {
+ WARN("CMap have higher supplmement number.");
+ WARN("Some characters may not be displayed or printed.");
+ }
+ }
+
+ {
+ char *shortname;
+
+ shortname = cff_get_name(cffont);
+ if (!shortname)
+ ERROR("No valid FontName found.");
+ /*
+ * Mangled name requires more 7 bytes.
+ * Style requires more 11 bytes.
+ */
+ fontname = NEW(strlen(shortname)+19, char);
+ memset(fontname, 0, strlen(shortname)+19);
+ strcpy(fontname, shortname);
+ RELEASE(shortname);
+ }
+ cff_close(cffont);
+
+ if (opt->embed && opt->style != FONT_STYLE_NONE) {
+ WARN("Embedding disabled due to style option for %s.", name);
+ opt->embed = 0;
+ }
+ switch (opt->style) {
+ case FONT_STYLE_BOLD:
+ strcat(fontname, ",Bold");
+ break;
+ case FONT_STYLE_ITALIC:
+ strcat(fontname, ",Italic");
+ break;
+ case FONT_STYLE_BOLDITALIC:
+ strcat(fontname, ",BoldItalic");
+ break;
+ }
+
+ font->fontname = fontname;
+ font->subtype = CIDFONT_TYPE0;
+ font->csi = csi;
+
+ font->fontdict = pdf_new_dict();
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("Type"),
+ pdf_new_name("Font"));
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("Subtype"),
+ pdf_new_name("CIDFontType0"));
+
+ /* getting font info. from TrueType tables */
+ if ((font->descriptor
+ = tt_get_fontdesc(sfont, &(opt->embed), opt->stemv, 0, name)) == NULL)
+ ERROR("Could not obtain necessary font info.");
+
+ if (opt->embed) {
+ memmove(fontname + 7, fontname, strlen(fontname) + 1);
+ pdf_font_make_uniqueTag(fontname);
+ fontname[6] = '+';
+ }
+
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("FontName"),
+ pdf_new_name(fontname));
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("BaseFont"),
+ pdf_new_name(fontname));
+ {
+ pdf_obj *csi_dict = pdf_new_dict();
+ pdf_add_dict(csi_dict,
+ pdf_new_name("Registry"),
+ pdf_new_string(csi->registry, strlen(csi->registry)));
+ pdf_add_dict(csi_dict,
+ pdf_new_name("Ordering"),
+ pdf_new_string(csi->ordering, strlen(csi->ordering)));
+ pdf_add_dict(csi_dict,
+ pdf_new_name("Supplement"),
+ pdf_new_number(csi->supplement));
+ pdf_add_dict(font->fontdict, pdf_new_name("CIDSystemInfo"), csi_dict);
+ }
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("DW"),
+ pdf_new_number(1000)); /* not sure */
+
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+
+ return 0;
+}
+
+void
+CIDFont_type0_t1cdofont (CIDFont *font)
+{
+ sfnt *sfont;
+ cff_font *cffont;
+ cff_index *charstrings, *idx;
+ long charstring_len, max_len;
+ long destlen = 0;
+ long size, offset = 0;
+ card8 *data;
+ card16 num_glyphs, gid, last_cid;
+ long i, cid;
+ int parent_id;
+ char *used_chars;
+ double default_width, nominal_width;
+ FILE *fp = NULL;
+
+ ASSERT(font);
+
+ if (!font->indirect)
+ return;
+
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("FontDescriptor"),
+ pdf_ref_obj (font->descriptor));
+
+ if ((parent_id = CIDFont_get_parent_id(font, 0)) < 0 &&
+ (parent_id = CIDFont_get_parent_id(font, 1)) < 0)
+ ERROR("No parent Type 0 font !");
+
+ used_chars = Type0Font_get_usedchars(Type0Font_cache_get(parent_id));
+ if (!used_chars)
+ ERROR("Unexpected error: Font not actually used???");
+
+#ifdef XETEX
+ sfont = sfnt_open(font->ft_face, SFNT_TYPE_POSTSCRIPT);
+#else
+ fp = DPXFOPEN(font->ident, DPX_RES_TYPE_OTFONT);
+ if (!fp)
+ ERROR("Could not open OpenType font file: %s", font->ident);
+
+ sfont = sfnt_open(fp);
+#endif
+ if (!sfont)
+ ERROR("Could not open OpenType font file: %s", font->ident);
+
+ if (sfnt_read_table_directory(sfont, 0) < 0 ||
+ sfont->type != SFNT_TYPE_POSTSCRIPT)
+ ERROR("Not a CFF/OpenType font ?");
+ offset = sfnt_find_table_pos(sfont, "CFF ");
+ if (offset == 0)
+ ERROR("Not a CFF/OpenType font ?");
+
+ cffont = cff_open(sfont, offset, font->options->index);
+ if (!cffont)
+ ERROR("Could not open CFF font.");
+ if (cffont->flag & FONTTYPE_CIDFONT)
+ ERROR("This is CIDFont...");
+
+ cff_read_private(cffont);
+ cff_read_subrs (cffont);
+
+ if (cffont->private[0] && cff_dict_known(cffont->private[0], "StdVW")) {
+ double stemv;
+ stemv = cff_dict_get(cffont->private[0], "StdVW", 0);
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("StemV"), pdf_new_number(stemv));
+ }
+ if (cffont->private[0] && cff_dict_known(cffont->private[0], "defaultWidthX")) {
+ default_width = (double) cff_dict_get(cffont->private[0], "defaultWidthX", 0);
+ } else {
+ default_width = CFF_DEFAULTWIDTHX_DEFAULT;
+ }
+ if (cffont->private[0] && cff_dict_known(cffont->private[0], "nominalWidthX")) {
+ nominal_width = (double) cff_dict_get(cffont->private[0], "nominalWidthX", 0);
+ } else {
+ nominal_width = CFF_NOMINALWIDTHX_DEFAULT;
+ }
+
+ num_glyphs = 0; last_cid = 0;
+ add_to_used_chars2(used_chars, 0); /* .notdef */
+ for (i = 0; i < (cffont->num_glyphs + 7)/8; i++) {
+ int c, j;
+
+ c = used_chars[i];
+ for (j = 7; j >= 0; j--) {
+ if (c & (1 << j)) {
+ num_glyphs++;
+ last_cid = (i + 1) * 8 - j - 1;
+ }
+ }
+ }
+
+ {
+ cff_fdselect *fdselect;
+
+ fdselect = NEW(1, cff_fdselect);
+ fdselect->format = 3;
+ fdselect->num_entries = 1;
+ fdselect->data.ranges = NEW(1, cff_range3);
+ fdselect->data.ranges[0].first = 0;
+ fdselect->data.ranges[0].fd = 0;
+ cffont->fdselect = fdselect;
+ }
+
+ {
+ cff_charsets *charset;
+
+ charset = NEW(1, cff_charsets);
+ charset->format = 0;
+ charset->num_entries = num_glyphs-1;
+ charset->data.glyphs = NEW(num_glyphs-1, s_SID);
+
+ for (gid = 0, cid = 0; cid <= last_cid; cid++) {
+ if (is_used_char2(used_chars, cid)) {
+ if (gid > 0)
+ charset->data.glyphs[gid-1] = cid;
+ gid++;
+ }
+ }
+ /* cff_release_charsets(cffont->charsets); */
+ cffont->charsets = charset;
+ }
+
+ cff_dict_add(cffont->topdict, "CIDCount", 1);
+ cff_dict_set(cffont->topdict, "CIDCount", 0, last_cid + 1);
+
+ cffont->fdarray = NEW(1, cff_dict *);
+ cffont->fdarray[0] = cff_new_dict();
+ cff_dict_add(cffont->fdarray[0], "FontName", 1);
+ cff_dict_set(cffont->fdarray[0], "FontName", 0,
+ (double) cff_add_string(cffont, font->fontname + 7, 1)); /* FIXME: Skip XXXXXX+ */
+ cff_dict_add(cffont->fdarray[0], "Private", 2);
+ cff_dict_set(cffont->fdarray[0], "Private", 0, 0.0);
+ cff_dict_set(cffont->fdarray[0], "Private", 0, 0.0);
+ /* FDArray - index offset, not known yet */
+ cff_dict_add(cffont->topdict, "FDArray", 1);
+ cff_dict_set(cffont->topdict, "FDArray", 0, 0.0);
+ /* FDSelect - offset, not known yet */
+ cff_dict_add(cffont->topdict, "FDSelect", 1);
+ cff_dict_set(cffont->topdict, "FDSelect", 0, 0.0);
+
+ cff_dict_remove(cffont->topdict, "UniqueID");
+ cff_dict_remove(cffont->topdict, "XUID");
+ cff_dict_remove(cffont->topdict, "Private");
+ cff_dict_remove(cffont->topdict, "Encoding");
+
+
+ /* */
+ offset = (long) cff_dict_get(cffont->topdict, "CharStrings", 0);
+ cff_seek_set(cffont, offset);
+ idx = cff_get_index_header(cffont);
+ /* offset is now absolute offset ... bad */
+ offset = cffont->sfont->loc;
+
+ if (idx->count < 2)
+ ERROR("No valid charstring data found.");
+
+ /* New CharStrings INDEX */
+ charstrings = cff_new_index((card16)(num_glyphs+1));
+ max_len = 2 * CS_STR_LEN_MAX;
+ charstrings->data = NEW(max_len, card8);
+ charstring_len = 0;
+
+ gid = 0;
+ data = NEW(CS_STR_LEN_MAX, card8);
+ for (cid = 0; cid <= last_cid; cid++) {
+ if (!is_used_char2(used_chars, cid))
+ continue;
+
+ if ((size = (idx->offset)[cid+1] - (idx->offset)[cid])
+ > CS_STR_LEN_MAX)
+ ERROR("Charstring too long: gid=%u", cid);
+ if (charstring_len + CS_STR_LEN_MAX >= max_len) {
+ max_len = charstring_len + 2 * CS_STR_LEN_MAX;
+ charstrings->data = RENEW(charstrings->data, max_len, card8);
+ }
+ (charstrings->offset)[gid] = charstring_len + 1;
+ sfnt_seek_set(cffont->sfont, offset + (idx->offset)[cid] - 1);
+ sfnt_read(data, size, cffont->sfont);
+ charstring_len += cs_copy_charstring(charstrings->data + charstring_len,
+ max_len - charstring_len,
+ data, size,
+ cffont->gsubr, (cffont->subrs)[0],
+ default_width, nominal_width, NULL);
+ gid++;
+ }
+ if (gid != num_glyphs)
+ ERROR("Unexpeced error: ?????");
+ RELEASE(data);
+ cff_release_index(idx);
+
+ (charstrings->offset)[num_glyphs] = charstring_len + 1;
+ charstrings->count = num_glyphs;
+ cffont->num_glyphs = num_glyphs;
+ cffont->cstrings = charstrings;
+
+ /* no Global subr */
+ if (cffont->gsubr)
+ cff_release_index(cffont->gsubr);
+ cffont->gsubr = cff_new_index(0);
+
+ if (cffont->subrs && cffont->subrs[0]) {
+ cff_release_index(cffont->subrs[0]);
+ cffont->subrs[0] = NULL;
+ }
+ if (cffont->private && (cffont->private)[0]) {
+ cff_dict_remove((cffont->private)[0], "Subrs"); /* no Subrs */
+ }
+
+ cff_add_string(cffont, "Adobe", 1);
+ cff_add_string(cffont, "Identity", 1);
+
+ cff_dict_update(cffont->topdict, cffont);
+ cff_dict_update(cffont->private[0], cffont);
+ cff_update_string(cffont);
+
+ /* CFF code need to be rewrote... */
+ cff_dict_add(cffont->topdict, "ROS", 3);
+ cff_dict_set(cffont->topdict, "ROS", 0,
+ (double) cff_get_sid(cffont, "Adobe"));
+ cff_dict_set(cffont->topdict, "ROS", 1,
+ (double) cff_get_sid(cffont, "Identity"));
+ cff_dict_set(cffont->topdict, "ROS", 2, 0.0);
+
+ destlen = write_fontfile(font, cffont);
+
+ cff_close(cffont);
+
+ /*
+ * DW, W, DW2 and W2:
+ * Those values are obtained from OpenType table (not TFM).
+ */
+ {
+ unsigned char *CIDToGIDMap;
+
+ CIDToGIDMap = NEW(2 * (last_cid+1), unsigned char);
+ memset(CIDToGIDMap, 0, 2 * (last_cid + 1));
+ for (cid = 0; cid <= last_cid; cid++) {
+ if (is_used_char2(used_chars, cid)) {
+ CIDToGIDMap[2*cid ] = (cid >> 8) & 0xff;
+ CIDToGIDMap[2*cid+1] = cid & 0xff;
+ }
+ }
+ add_CIDMetrics(sfont, font->fontdict, CIDToGIDMap, last_cid,
+ ((CIDFont_get_parent_id(font, 1) < 0) ? 0 : 1));
+ RELEASE(CIDToGIDMap);
+ }
+
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+
+ if (verbose > 1)
+ MESG("[%u glyphs][%ld bytes]", num_glyphs, destlen);
+
+ /*
+ * CIDSet:
+ * Length of CIDSet stream is not clear. Must be 8192 bytes long?
+ */
+ {
+ pdf_obj *cidset;
+
+ cidset = pdf_new_stream(STREAM_COMPRESS);
+ pdf_add_stream(cidset, used_chars, (last_cid/8)+1);
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("CIDSet"), pdf_ref_obj(cidset));
+ pdf_release_obj(cidset);
+ }
+
+ return;
+}
+
+int
+CIDFont_type0_t1copen (CIDFont *font, const char *name,
+ CIDSysInfo *cmap_csi, cid_opt *opt)
+{
+ CIDSysInfo *csi;
+ char *fontname;
+ sfnt *sfont;
+ cff_font *cffont;
+ unsigned long offset = 0;
+ FILE *fp = NULL;
+
+ ASSERT(font);
+
+#ifdef XETEX
+ sfont = sfnt_open(font->ft_face, SFNT_TYPE_POSTSCRIPT);
+ if (!sfont)
+ return -1;
+#else
+ fp = DPXFOPEN(name, DPX_RES_TYPE_OTFONT);
+ if (!fp)
+ return -1;
+
+ sfont = sfnt_open(fp);
+#endif
+ if (!sfont) {
+ ERROR("Not a CFF/OpenType font?");
+ }
+ if (sfont->type != SFNT_TYPE_POSTSCRIPT ||
+ sfnt_read_table_directory(sfont, 0) < 0 ||
+ (offset = sfnt_find_table_pos(sfont, "CFF ")) == 0) {
+ ERROR("Not a CFF/OpenType font?");
+ }
+
+ cffont = cff_open(sfont, offset, opt->index);
+ if (!cffont) {
+ ERROR("Cannot read CFF font data");
+ }
+
+ if (cffont->flag & FONTTYPE_CIDFONT) {
+ cff_close(cffont);
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+
+ return -1;
+ }
+
+ csi = NEW(1, CIDSysInfo);
+ csi->registry = NEW(strlen("Adobe")+1, char);
+ strcpy(csi->registry, "Adobe");
+ csi->ordering = NEW(strlen("Identity")+1, char);
+ strcpy(csi->ordering, "Identity");
+ csi->supplement = 0;
+
+ if (cmap_csi) {
+ if (strcmp(csi->registry, cmap_csi->registry) != 0 ||
+ strcmp(csi->ordering, cmap_csi->ordering) != 0) {
+ MESG("\nCharacter collection mismatched:\n");
+ MESG("\tFont: %s-%s-%d\n", csi->registry, csi->ordering, csi->supplement);
+ MESG("\tCMap: %s-%s-%d\n", cmap_csi->registry, cmap_csi->ordering, cmap_csi->supplement);
+ ERROR("Inconsistent CMap specified for this font.");
+ }
+ if (csi->supplement < cmap_csi->supplement) {
+ WARN("CMap have higher supplmement number.");
+ WARN("Some characters may not be displayed or printed.");
+ }
+ }
+
+ {
+ char *shortname;
+
+ shortname = cff_get_name(cffont);
+ if (!shortname)
+ ERROR("No valid FontName found.");
+ /* Mangled name requires more 7 bytes. */
+
+ fontname = NEW(strlen(shortname) + 8, char);
+ memset(fontname, 0, strlen(shortname) + 8);
+ strcpy(fontname, shortname);
+ RELEASE(shortname);
+ }
+ cff_close(cffont);
+
+ opt->embed = 1;
+
+ font->fontname = fontname;
+ font->subtype = CIDFONT_TYPE0;
+ font->csi = csi;
+ font->flags |= CIDFONT_FLAG_TYPE1C;
+
+ font->fontdict = pdf_new_dict();
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("Type"),
+ pdf_new_name("Font"));
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("Subtype"),
+ pdf_new_name("CIDFontType0"));
+
+ /* getting font info. from TrueType tables */
+ if ((font->descriptor
+ = tt_get_fontdesc(sfont, &(opt->embed), opt->stemv, 0, name)) == NULL)
+ ERROR("Could not obtain necessary font info.");
+
+ if (opt->embed) {
+ memmove(fontname + 7, fontname, strlen(fontname) + 1);
+ pdf_font_make_uniqueTag(fontname);
+ fontname[6] = '+';
+ }
+
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("FontName"),
+ pdf_new_name(fontname));
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("BaseFont"),
+ pdf_new_name(fontname));
+ {
+ pdf_obj *csi_dict = pdf_new_dict();
+ pdf_add_dict(csi_dict,
+ pdf_new_name("Registry"),
+ pdf_new_string(csi->registry, strlen(csi->registry)));
+ pdf_add_dict(csi_dict,
+ pdf_new_name("Ordering"),
+ pdf_new_string(csi->ordering, strlen(csi->ordering)));
+ pdf_add_dict(csi_dict,
+ pdf_new_name("Supplement"),
+ pdf_new_number(csi->supplement));
+ pdf_add_dict(font->fontdict, pdf_new_name("CIDSystemInfo"), csi_dict);
+ }
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+
+ return 0;
+}
+
+
+/* Type1 --> CFF CIDFont */
+#include "unicode.h"
+#include "t1_load.h"
+#include "t1_char.h"
+
+#include "agl.h"
+
+#include "cmap.h"
+#include "cmap_write.h"
+#include "fontmap.h"
+
+static int
+load_base_CMap (const char *font_name, int wmode, cff_font *cffont)
+{
+ int cmap_id = -1;
+ CMap *cmap;
+ char *cmap_name;
+ card16 gid;
+ unsigned char range_min[4] = {0x00, 0x00, 0x00, 0x00};
+ unsigned char range_max[4] = {0x7f, 0xff, 0xff, 0xff};
+
+ cmap_name = NEW(strlen(font_name)+strlen("-UCS4-H")+1, char);
+ if (wmode) {
+ sprintf(cmap_name, "%s-UCS4-V", font_name);
+ } else {
+ sprintf(cmap_name, "%s-UCS4-H", font_name);
+ }
+
+ cmap_id = CMap_cache_find(cmap_name);
+ if (cmap_id >= 0) {
+ RELEASE(cmap_name);
+ return cmap_id;
+ }
+
+ cmap = CMap_new();
+ CMap_set_name (cmap, cmap_name);
+ CMap_set_type (cmap, CMAP_TYPE_CODE_TO_CID);
+ CMap_set_wmode(cmap, wmode);
+ CMap_add_codespacerange(cmap, range_min, range_max, 4);
+ CMap_set_CIDSysInfo(cmap, &CSI_IDENTITY);
+ RELEASE(cmap_name);
+
+ for (gid = 1; gid < cffont->num_glyphs; gid++) {
+ long ucv;
+ s_SID sid;
+ char *glyph, *name, *suffix;
+ unsigned char srcCode[4];
+
+ sid = cff_charsets_lookup_inverse(cffont, gid);
+ glyph = cff_get_string (cffont, sid);
+
+ name = agl_chop_suffix(glyph, &suffix);
+ if (!name) {
+ if (suffix)
+ RELEASE(suffix);
+ RELEASE(glyph);
+ continue;
+ }
+
+ if (suffix) {
+ RELEASE(name);
+ RELEASE(suffix);
+ RELEASE(glyph);
+ continue;
+ }
+
+ if (agl_name_is_unicode(name)) {
+ ucv = agl_name_convert_unicode(name);
+ srcCode[0] = (ucv >> 24) & 0xff;
+ srcCode[1] = (ucv >> 16) & 0xff;
+ srcCode[2] = (ucv >> 8) & 0xff;
+ srcCode[3] = ucv & 0xff;
+ CMap_add_cidchar(cmap, srcCode, 4, gid);
+ } else {
+ agl_name *agln;
+
+ agln = agl_lookup_list(name);
+ if (!agln)
+ WARN("Glyph \"%s\" inaccessible (no Unicode mapping)", glyph);
+ while (agln) {
+ if (agln->n_components > 1) {
+ WARN("Glyph \"%s\" inaccessible (composite character)", glyph);
+ } else if (agln->n_components == 1) {
+ ucv = agln->unicodes[0];
+ srcCode[0] = (ucv >> 24) & 0xff;
+ srcCode[1] = (ucv >> 16) & 0xff;
+ srcCode[2] = (ucv >> 8) & 0xff;
+ srcCode[3] = ucv & 0xff;
+ CMap_add_cidchar(cmap, srcCode, 4, gid);
+ }
+ agln = agln->alternate;
+ }
+ }
+ RELEASE(name);
+ if (suffix)
+ RELEASE(suffix);
+ RELEASE(glyph);
+ }
+ cmap_id = CMap_cache_add(cmap);
+
+ return cmap_id;
+}
+
+int
+t1_load_UnicodeCMap (const char *font_name,
+ const char *otl_tags, /* not supported yet */
+ int wmode)
+{
+ int cmap_id = -1;
+ cff_font *cffont;
+ FILE *fp;
+
+ if (!font_name)
+ return -1;
+
+ fp = DPXFOPEN(font_name, DPX_RES_TYPE_T1FONT);
+ if (!fp)
+ return -1;
+
+ cffont = t1_load_font(NULL, 1, fp);
+ DPXFCLOSE(fp);
+ if (!cffont)
+ return -1;
+
+ cmap_id = load_base_CMap(font_name, wmode, cffont);
+
+ cff_close(cffont);
+
+ if (cmap_id < 0) {
+ ERROR("Failed to create Unicode charmap for font \"%s\".", font_name);
+ return -1;
+ }
+
+ if (otl_tags) {
+ WARN("Glyph substitution not supported for Type1 font yet...");
+ }
+
+ return cmap_id;
+}
+
+
+/*
+ * ToUnicode CMap
+ */
+
+static pdf_obj *
+create_ToUnicode_stream (cff_font *cffont,
+ const char *font_name, const char *used_glyphs)
+{
+ pdf_obj *stream = NULL;
+ CMap *cmap;
+ CID cid;
+ card16 gid;
+ long glyph_count, total_fail_count;
+ char *cmap_name;
+#define WBUF_SIZE 1024
+ unsigned char wbuf[WBUF_SIZE];
+ unsigned char *p, *endptr;
+ static unsigned char range_min[2] = {0x00, 0x00};
+ static unsigned char range_max[2] = {0xff, 0xff};
+
+ if (!font_name || !used_glyphs)
+ return NULL;
+
+ cmap = CMap_new();
+
+ cmap_name = NEW(strlen(font_name)+strlen("-UTF16")+1, char);
+ strcpy(cmap_name, font_name);
+ strcat(cmap_name, "-UTF16");
+ CMap_set_name (cmap, cmap_name);
+ RELEASE(cmap_name);
+
+ CMap_set_wmode(cmap, 0);
+ CMap_set_type (cmap, CMAP_TYPE_TO_UNICODE);
+ CMap_set_CIDSysInfo(cmap, &CSI_UNICODE);
+
+ CMap_add_codespacerange(cmap, range_min, range_max, 2);
+
+ glyph_count = total_fail_count = 0;
+ p = wbuf;
+ endptr = wbuf + WBUF_SIZE;
+ for (cid = 1; cid < cffont->num_glyphs; cid++) { /* Skip .notdef */
+ if (is_used_char2(used_glyphs, cid)) {
+ char *glyph;
+ long len;
+ int fail_count;
+
+ wbuf[0] = (cid >> 8) & 0xff;
+ wbuf[1] = (cid & 0xff);
+
+ p = wbuf + 2;
+ gid = cff_charsets_lookup_inverse(cffont, cid);
+ if (gid == 0)
+ continue;
+ glyph = cff_get_string(cffont, gid);
+ if (glyph) {
+ len = agl_sput_UTF16BE(glyph, &p, endptr, &fail_count);
+ if (len < 1 || fail_count) {
+ total_fail_count += fail_count;
+ } else {
+ CMap_add_bfchar(cmap, wbuf, 2, wbuf+2, len);
+ }
+ RELEASE(glyph);
+ }
+ glyph_count++;
+ }
+ }
+
+ if (total_fail_count != 0 &&
+ total_fail_count >= glyph_count/10) {
+ WARN("%d glyph names (out of %d) missing Unicode mapping.",
+ total_fail_count, glyph_count);
+ WARN("ToUnicode CMap \"%s-UTF16\" removed.", font_name);
+ } else {
+ stream = CMap_create_stream(cmap, 0);
+ }
+ CMap_release(cmap);
+
+ return stream;
+}
+
+
+int
+CIDFont_type0_t1open (CIDFont *font, const char *name,
+ CIDSysInfo *cmap_csi, cid_opt *opt)
+{
+ FILE *fp;
+ char *fontname, *shortname;
+ cff_font *cffont;
+
+ ASSERT(font);
+
+ if (cmap_csi &&
+ (strcmp(cmap_csi->registry, "Adobe") != 0 ||
+ strcmp(cmap_csi->ordering, "Identity") != 0)) {
+ return -1;
+ }
+ fp = DPXFOPEN(name, DPX_RES_TYPE_T1FONT);
+ if (!fp)
+ return -1;
+
+ cffont = t1_load_font(NULL, 1, fp);
+ if (!cffont) {
+ DPXFCLOSE(fp);
+ return -1;
+ }
+ DPXFCLOSE(fp);
+
+ shortname = cff_get_name(cffont);
+ if (!shortname)
+ ERROR("No valid FontName found.");
+ fontname = NEW(strlen(shortname) + 8, char);
+ memset(fontname, 0, strlen(shortname) + 8);
+ strcpy(fontname, shortname);
+ RELEASE(shortname);
+
+#ifdef XETEX
+ font->ft_to_gid = cff_get_ft_to_gid(cffont);
+ cffont->ft_to_gid = NULL;
+#endif
+
+ cff_close(cffont);
+
+ if (opt->style != FONT_STYLE_NONE) {
+ WARN(",Bold, ,Italic, ... not supported for this type of font...");
+ opt->style = FONT_STYLE_NONE;
+ }
+
+ font->fontname = fontname;
+ font->subtype = CIDFONT_TYPE0;
+ font->csi = NEW(1, CIDSysInfo);
+ font->csi->registry = NEW(strlen("Adobe")+1, char);
+ strcpy(font->csi->registry, "Adobe");
+ font->csi->ordering = NEW(strlen("Identity")+1, char);
+ strcpy(font->csi->ordering, "Identity");
+ font->csi->supplement = 0;
+ font->flags |= CIDFONT_FLAG_TYPE1;
+
+ font->fontdict = pdf_new_dict();
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("Type"),
+ pdf_new_name("Font"));
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("Subtype"),
+ pdf_new_name("CIDFontType0"));
+
+ memmove(fontname + 7, fontname, strlen(fontname) + 1);
+ pdf_font_make_uniqueTag(fontname);
+ fontname[6] = '+';
+
+ font->descriptor = pdf_new_dict();
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("FontName"),
+ pdf_new_name(fontname));
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("BaseFont"),
+ pdf_new_name(fontname));
+ {
+ pdf_obj *csi_dict;
+
+ csi_dict = pdf_new_dict();
+ pdf_add_dict(csi_dict,
+ pdf_new_name("Registry"),
+ pdf_new_string("Adobe", strlen("Adobe")));
+ pdf_add_dict(csi_dict,
+ pdf_new_name("Ordering"),
+ pdf_new_string("Identity", strlen("Identity")));
+ pdf_add_dict(csi_dict,
+ pdf_new_name("Supplement"),
+ pdf_new_number(0.0));
+ pdf_add_dict(font->fontdict, pdf_new_name("CIDSystemInfo"), csi_dict);
+ }
+
+
+ return 0;
+}
+
+/* Duplicate from type1.c */
+#define TYPE1_NAME_LEN_MAX 127
+
+#define FONT_FLAG_FIXEDPITCH (1 << 0) /* Fixed-width font */
+#define FONT_FLAG_SERIF (1 << 1) /* Serif font */
+#define FONT_FLAG_SYMBOLIC (1 << 2) /* Symbolic font */
+#define FONT_FLAG_SCRIPT (1 << 3) /* Script font */
+#define FONT_FLAG_STANDARD (1 << 5) /* Adobe Standard Character Set */
+#define FONT_FLAG_ITALIC (1 << 6) /* Italic */
+#define FONT_FLAG_ALLCAP (1 << 16) /* All-cap font */
+#define FONT_FLAG_SMALLCAP (1 << 17) /* Small-cap font */
+#define FONT_FLAG_FORCEBOLD (1 << 18) /* Force bold at small text sizes */
+
+/* pdf_font --> CIDFont */
+static void
+get_font_attr (CIDFont *font, cff_font *cffont)
+{
+ double capheight, ascent, descent;
+ double italicangle, stemv;
+ double defaultwidth, nominalwidth;
+ long flags = 0;
+ long gid;
+ int i;
+ static const char *L_c[] = {
+ "H", "P", "Pi", "Rho", NULL
+ };
+ static const char *L_d[] = {
+ "p", "q", "mu", "eta", NULL
+ };
+ static const char *L_a[] = {
+ "b", "h", "lambda", NULL
+ };
+ t1_ginfo gm;
+
+ defaultwidth = 500.0;
+ nominalwidth = 0.0;
+
+ /*
+ * CapHeight, Ascent, and Descent is meaningfull only for Latin/Greek/Cyrillic.
+ * The BlueValues and OtherBlues also have those information.
+ */
+ if (cff_dict_known(cffont->topdict, "FontBBox")) {
+ /* Default values */
+ capheight = ascent = cff_dict_get(cffont->topdict, "FontBBox", 3);
+ descent = cff_dict_get(cffont->topdict, "FontBBox", 1);
+ } else {
+ capheight = 680.0;
+ ascent = 690.0;
+ descent = -190.0;
+ }
+ if (cff_dict_known(cffont->private[0], "StdVW")) {
+ stemv = cff_dict_get(cffont->private[0], "StdVW", 0);
+ } else {
+ /*
+ * We may use the following values for StemV:
+ * Thin - ExtraLight: <= 50
+ * Light: 71
+ * Regular(Normal): 88
+ * Medium: 109
+ * SemiBold(DemiBold): 135
+ * Bold - Heavy: >= 166
+ */
+ stemv = 88.0;
+ }
+ if (cff_dict_known(cffont->topdict, "ItalicAngle")) {
+ italicangle = cff_dict_get(cffont->topdict, "ItalicAngle", 0);
+ if (italicangle != 0.0)
+ flags |= FONT_FLAG_ITALIC;
+ } else {
+ italicangle = 0.0;
+ }
+
+ /*
+ * Use "space", "H", "p", and "b" for various values.
+ * Those characters should not "seac". (no accent)
+ */
+ gid = cff_glyph_lookup(cffont, "space");
+ if (gid >= 0 && gid < cffont->cstrings->count) {
+ t1char_get_metrics(cffont->cstrings->data + cffont->cstrings->offset[gid] - 1,
+ cffont->cstrings->offset[gid+1] - cffont->cstrings->offset[gid],
+ cffont->subrs[0], &gm);
+ defaultwidth = gm.wx;
+ }
+
+ for (i = 0; L_c[i] != NULL; i++) {
+ gid = cff_glyph_lookup(cffont, L_c[i]);
+ if (gid >= 0 && gid < cffont->cstrings->count) {
+ t1char_get_metrics(cffont->cstrings->data + cffont->cstrings->offset[gid] - 1,
+ cffont->cstrings->offset[gid+1] - cffont->cstrings->offset[gid],
+ cffont->subrs[0], &gm);
+ capheight = gm.bbox.ury;
+ break;
+ }
+ }
+
+ for (i = 0; L_d[i] != NULL; i++) {
+ gid = cff_glyph_lookup(cffont, L_d[i]);
+ if (gid >= 0 && gid < cffont->cstrings->count) {
+ t1char_get_metrics(cffont->cstrings->data + cffont->cstrings->offset[gid] - 1,
+ cffont->cstrings->offset[gid+1] - cffont->cstrings->offset[gid],
+ cffont->subrs[0], &gm);
+ descent = gm.bbox.lly;
+ break;
+ }
+ }
+
+ for (i = 0; L_a[i] != NULL; i++) {
+ gid = cff_glyph_lookup(cffont, L_a[i]);
+ if (gid >= 0 && gid < cffont->cstrings->count) {
+ t1char_get_metrics(cffont->cstrings->data + cffont->cstrings->offset[gid] - 1,
+ cffont->cstrings->offset[gid+1] - cffont->cstrings->offset[gid],
+ cffont->subrs[0], &gm);
+ ascent = gm.bbox.ury;
+ break;
+ }
+ }
+
+ if (defaultwidth != 0.0) {
+ cff_dict_add(cffont->private[0], "defaultWidthX", 1);
+ cff_dict_set(cffont->private[0], "defaultWidthX", 0, defaultwidth);
+ }
+ if (nominalwidth != 0.0) {
+ cff_dict_add(cffont->private[0], "nominalWidthX", 1);
+ cff_dict_set(cffont->private[0], "nominalWidthX", 0, nominalwidth);
+ }
+ if (cff_dict_known(cffont->private[0], "ForceBold") &&
+ cff_dict_get(cffont->private[0], "ForceBold", 0)) {
+ flags |= FONT_FLAG_FORCEBOLD;
+ }
+ if (cff_dict_known(cffont->private[0], "IsFixedPitch") &&
+ cff_dict_get(cffont->private[0], "IsFixedPitch", 0)) {
+ flags |= FONT_FLAG_FIXEDPITCH;
+ }
+ if (font->fontname &&
+ !strstr(font->fontname, "Sans")) {
+ flags |= FONT_FLAG_SERIF;
+ }
+ flags |= FONT_FLAG_SYMBOLIC;
+
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("CapHeight"), pdf_new_number(capheight));
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("Ascent"), pdf_new_number(ascent));
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("Descent"), pdf_new_number(descent));
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("ItalicAngle"), pdf_new_number(italicangle));
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("StemV"), pdf_new_number(stemv));
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("Flags"), pdf_new_number(flags));
+}
+
+static void
+add_metrics (CIDFont *font, cff_font *cffont,
+ unsigned char *CIDToGIDMap,
+ double *widths, double default_width, CID last_cid)
+{
+ pdf_obj *tmp;
+ double val;
+ card16 cid, gid;
+ char *used_chars;
+ int i, parent_id;
+
+ /*
+ * The original FontBBox of the font is preserved, instead
+ * of replacing it with tight bounding box calculated from
+ * charstrings, to prevent Acrobat 4 from greeking text as
+ * much as possible.
+ */
+ if (!cff_dict_known(cffont->topdict, "FontBBox")) {
+ ERROR("No FontBBox?");
+ }
+ tmp = pdf_new_array();
+ for (i = 0; i < 4; i++) {
+ val = cff_dict_get(cffont->topdict, "FontBBox", i);
+ pdf_add_array(tmp, pdf_new_number(ROUND(val, 1.0)));
+ }
+ pdf_add_dict(font->descriptor, pdf_new_name("FontBBox"), tmp);
+
+ if ((parent_id = CIDFont_get_parent_id(font, 0)) < 0 &&
+ (parent_id = CIDFont_get_parent_id(font, 1)) < 0)
+ ERROR("No parent Type 0 font !");
+
+ used_chars = Type0Font_get_usedchars(Type0Font_cache_get(parent_id));
+ if (!used_chars) {
+ ERROR("Unexpected error: Font not actually used???");
+ }
+
+ /* FIXME:
+ * This writes "CID CID width".
+ * I think it's better to handle each 8 char block
+ * and to use "CID_start [ w0 w1 ...]".
+ */
+ tmp = pdf_new_array();
+ for (cid = 0; cid <= last_cid; cid++) {
+ if (is_used_char2(used_chars, cid)) {
+ gid = (CIDToGIDMap[2*cid] << 8)|CIDToGIDMap[2*cid+1];
+ if (widths[gid] != default_width) {
+ pdf_add_array(tmp, pdf_new_number(cid));
+ pdf_add_array(tmp, pdf_new_number(cid));
+ pdf_add_array(tmp, pdf_new_number(ROUND(widths[gid], 1.0)));
+ }
+ }
+ }
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("DW"), pdf_new_number(default_width));
+ if (pdf_array_length(tmp) > 0) {
+ pdf_add_dict(font->fontdict, pdf_new_name("W"), pdf_ref_obj(tmp));
+ }
+ pdf_release_obj(tmp);
+}
+
+void
+CIDFont_type0_t1dofont (CIDFont *font)
+{
+ cff_font *cffont;
+ double defaultwidth, nominalwidth;
+ long num_glyphs = 0;
+ FILE *fp;
+ long i, offset;
+ char *used_chars = NULL;
+ card16 last_cid, gid, cid;
+ unsigned char *CIDToGIDMap;
+
+ ASSERT(font);
+
+ if (!font->indirect) {
+ return;
+ }
+
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("FontDescriptor"),
+ pdf_ref_obj (font->descriptor));
+
+ fp = DPXFOPEN(font->ident, DPX_RES_TYPE_T1FONT);
+ if (!fp) {
+ ERROR("Type1: Could not open Type1 font.");
+ }
+
+ cffont = t1_load_font(NULL, 0, fp);
+ if (!cffont)
+ ERROR("Could not read Type 1 font...");
+ DPXFCLOSE(fp);
+
+ if (!font->fontname)
+ ERROR("Fontname undefined...");
+
+ {
+ Type0Font *hparent, *vparent;
+ pdf_obj *tounicode;
+ int vparent_id, hparent_id;
+
+ hparent_id = CIDFont_get_parent_id(font, 0);
+ vparent_id = CIDFont_get_parent_id(font, 1);
+ if (hparent_id < 0 && vparent_id < 0)
+ ERROR("No parent Type 0 font !");
+
+ /* usedchars is same for h and v */
+ if (hparent_id < 0)
+ hparent = NULL;
+ else {
+ hparent = Type0Font_cache_get(hparent_id);
+ used_chars = Type0Font_get_usedchars(hparent);
+ }
+ if (vparent_id < 0)
+ vparent = NULL;
+ else {
+ vparent = Type0Font_cache_get(vparent_id);
+ used_chars = Type0Font_get_usedchars(vparent);
+ }
+ if (!used_chars)
+ ERROR("Unexpected error: Font not actually used???");
+
+ tounicode = create_ToUnicode_stream(cffont, font->fontname, used_chars);
+
+ if (hparent)
+ Type0Font_set_ToUnicode(hparent, pdf_ref_obj(tounicode));
+ if (vparent)
+ Type0Font_set_ToUnicode(vparent, pdf_ref_obj(tounicode));
+ pdf_release_obj(tounicode);
+ }
+
+ cff_set_name(cffont, font->fontname);
+
+ /* defaultWidthX, CapHeight, etc. */
+ get_font_attr(font, cffont);
+ if (cff_dict_known(cffont->private[0], "defaultWidthX")) {
+ defaultwidth = cff_dict_get(cffont->private[0], "defaultWidthX", 0);
+ } else {
+ defaultwidth = 0.0;
+ }
+ if (cff_dict_known(cffont->private[0], "nominalWidthX")) {
+ nominalwidth = cff_dict_get(cffont->private[0], "nominalWidthX", 0);
+ } else {
+ nominalwidth = 0.0;
+ }
+
+ num_glyphs = 0; last_cid = 0;
+ add_to_used_chars2(used_chars, 0); /* .notdef */
+ for (i = 0; i < (cffont->num_glyphs + 7)/8; i++) {
+ int c, j;
+
+ c = used_chars[i];
+ for (j = 7; j >= 0; j--) {
+ if (c & (1 << j)) {
+ num_glyphs++;
+ last_cid = (i + 1) * 8 - j - 1;
+ }
+ }
+ }
+
+ {
+ cff_fdselect *fdselect;
+
+ fdselect = NEW(1, cff_fdselect);
+ fdselect->format = 3;
+ fdselect->num_entries = 1;
+ fdselect->data.ranges = NEW(1, cff_range3);
+ fdselect->data.ranges[0].first = 0;
+ fdselect->data.ranges[0].fd = 0;
+ cffont->fdselect = fdselect;
+ }
+
+ CIDToGIDMap = NEW(2*(last_cid+1), unsigned char);
+ memset(CIDToGIDMap, 0, 2*(last_cid+1));
+ {
+ cff_charsets *charset;
+
+ charset = NEW(1, cff_charsets);
+ charset->format = 0;
+ charset->num_entries = num_glyphs-1;
+ charset->data.glyphs = NEW(num_glyphs-1, s_SID);
+
+ for (gid = 0, cid = 0; cid <= last_cid; cid++) {
+ if (is_used_char2(used_chars, cid)) {
+ if (gid > 0)
+ charset->data.glyphs[gid-1] = cid;
+ CIDToGIDMap[2*cid ] = (gid >> 8) & 0xff;
+ CIDToGIDMap[2*cid+1] = gid & 0xff;
+ gid++;
+ }
+ }
+
+ cff_release_charsets(cffont->charsets);
+ cffont->charsets = charset;
+ }
+
+ cff_dict_add(cffont->topdict, "CIDCount", 1);
+ cff_dict_set(cffont->topdict, "CIDCount", 0, last_cid + 1);
+
+ cffont->fdarray = NEW(1, cff_dict *);
+ cffont->fdarray[0] = cff_new_dict();
+ cff_dict_add(cffont->fdarray[0], "FontName", 1);
+ cff_dict_set(cffont->fdarray[0], "FontName", 0,
+ (double) cff_add_string(cffont, font->fontname + 7, 1)); /* FIXME: Skip XXXXXX+ */
+ cff_dict_add(cffont->fdarray[0], "Private", 2);
+ cff_dict_set(cffont->fdarray[0], "Private", 0, 0.0);
+ cff_dict_set(cffont->fdarray[0], "Private", 0, 0.0);
+
+ /* FDArray - index offset, not known yet */
+ cff_dict_add(cffont->topdict, "FDArray", 1);
+ cff_dict_set(cffont->topdict, "FDArray", 0, 0.0);
+ /* FDSelect - offset, not known yet */
+ cff_dict_add(cffont->topdict, "FDSelect", 1);
+ cff_dict_set(cffont->topdict, "FDSelect", 0, 0.0);
+
+ cff_dict_add(cffont->topdict, "charset", 1);
+ cff_dict_set(cffont->topdict, "charset", 0, 0.0);
+
+ cff_dict_add(cffont->topdict, "CharStrings", 1);
+ cff_dict_set(cffont->topdict, "CharStrings", 0, 0.0);
+
+ {
+ cff_index *cstring;
+ t1_ginfo gm;
+ long max = 0;
+ double *widths;
+ int w_stat[1001], max_count, dw;
+
+ widths = NEW(num_glyphs, double);
+ memset(w_stat, 0, sizeof(int)*1001);
+ offset = 0L;
+ cstring = cff_new_index((card16)num_glyphs);
+ cstring->data = NULL;
+ cstring->offset[0] = 1;
+ gid = 0;
+ for (cid = 0; cid <= last_cid; cid++) {
+ if (!is_used_char2(used_chars, cid))
+ continue;
+
+ if (offset + CS_STR_LEN_MAX >= max) {
+ max += CS_STR_LEN_MAX*2;
+ cstring->data = RENEW(cstring->data, max, card8);
+ }
+ offset += t1char_convert_charstring(cstring->data + cstring->offset[gid] - 1, CS_STR_LEN_MAX,
+ cffont->cstrings->data + cffont->cstrings->offset[cid] - 1,
+ cffont->cstrings->offset[cid+1] - cffont->cstrings->offset[cid],
+ cffont->subrs[0], defaultwidth, nominalwidth, &gm);
+ cstring->offset[gid+1] = offset + 1;
+ if (gm.use_seac) {
+ ERROR("This font using the \"seac\" command for accented characters...");
+ }
+ widths[gid] = gm.wx;
+ if (gm.wx >= 0.0 && gm.wx <= 1000.0) {
+ w_stat[((int) gm.wx)] += 1;
+ }
+ gid++;
+ }
+
+ cff_release_index(cffont->cstrings);
+ cffont->cstrings = cstring;
+
+ max_count = 0; dw = -1;
+ for (i = 0; i <= 1000; i++) {
+ if (w_stat[i] > max_count) {
+ dw = i;
+ max_count = w_stat[i];
+ }
+ }
+ if (dw >= 0) {
+ add_metrics(font, cffont, CIDToGIDMap, widths, dw, last_cid);
+ } else {
+ add_metrics(font, cffont, CIDToGIDMap, widths, defaultwidth, last_cid);
+ }
+ RELEASE(widths);
+ }
+ cff_release_index(cffont->subrs[0]);
+ cffont->subrs[0] = NULL;
+
+ RELEASE(CIDToGIDMap);
+
+ cff_add_string(cffont, "Adobe", 1);
+ cff_add_string(cffont, "Identity", 1);
+
+ cff_dict_update(cffont->topdict, cffont);
+ cff_dict_update(cffont->private[0], cffont);
+
+ cff_update_string(cffont);
+
+ /* CFF code need to be rewrote... */
+ cff_dict_add(cffont->topdict, "ROS", 3);
+ cff_dict_set(cffont->topdict, "ROS", 0,
+ (double) cff_get_sid(cffont, "Adobe"));
+ cff_dict_set(cffont->topdict, "ROS", 1,
+ (double) cff_get_sid(cffont, "Identity"));
+ cff_dict_set(cffont->topdict, "ROS", 2, 0.0);
+
+ cffont->num_glyphs = num_glyphs;
+ offset = write_fontfile(font, cffont);
+
+ cff_close(cffont);
+
+ {
+ pdf_obj *cidset;
+
+ cidset = pdf_new_stream(STREAM_COMPRESS);
+ pdf_add_stream(cidset, used_chars, (last_cid/8)+1);
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("CIDSet"), pdf_ref_obj(cidset));
+ pdf_release_obj(cidset);
+ }
+
+
+ return;
+}
+
+void
+CIDFont_type0_release(CIDFont *font)
+{
+#ifdef XETEX
+ if (font->ft_to_gid) RELEASE(font->ft_to_gid);
+#endif
+ return;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/cidtype2.c b/Build/source/texk/dvipdf-x/xsrc/cidtype2.c
new file mode 100644
index 00000000000..0059a1c89ea
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/cidtype2.c
@@ -0,0 +1,1126 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+/*
+ * TrueType glyf table is sorted by CID and no CIDToGIDMap is used here.
+ * GhostScript can't handle CIDToGIDMap correctly.
+ */
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "system.h"
+#include "numbers.h"
+#include "mem.h"
+#include "error.h"
+#include "dpxfile.h"
+
+#include "pdfobj.h"
+/* pseudo unique tag */
+#include "pdffont.h"
+
+#ifndef PDF_NAME_LEN_MAX
+# define PDF_NAME_LEN_MAX 255
+#endif
+
+/* TrueType */
+#include "sfnt.h"
+#include "tt_aux.h"
+#include "tt_glyf.h"
+#include "tt_cmap.h"
+#include "tt_table.h"
+
+#include "tt_gsub.h"
+
+/* CID font */
+#include "cmap.h"
+#include "type0.h"
+#include "cid.h"
+#include "cid_p.h"
+#include "cidtype2.h"
+
+static int verbose = 0;
+static int opt_flags = 0;
+
+void
+CIDFont_type2_set_verbose (void)
+{
+ verbose++;
+}
+
+void
+CIDFont_type2_set_flags (long flags)
+{
+ opt_flags = flags;
+}
+
+/*
+ * PDF viewer applications use following tables (CIDFontType 2)
+ *
+ * head, hhea, loca, maxp, glyf, hmtx, fpgm, cvt_, prep
+ *
+ * - from PDF Ref. v.1.3, 2nd ed.
+ *
+ * The fpgm, cvt_, and prep tables appears only when TrueType instructions
+ * requires them. Those tables must be preserved if they exist.
+ * We use must_exist flag to indicate `preserve it if present'
+ * and to make sure not to cause an error when it does not exist.
+ *
+ * post and name table must exist in ordinary TrueType font file,
+ * but when a TrueType font is converted to CIDFontType 2 font, those tables
+ * are no longer required.
+ *
+ * The OS/2 table (required for TrueType font for Windows and OS/2) contains
+ * liscencing information, but PDF viewers seems not using them.
+ *
+ * The 'name' table added. See comments in ttf.c.
+ */
+
+static struct
+{
+ const char *name;
+ int must_exist;
+} required_table[] = {
+ {"OS/2", 0}, {"head", 1}, {"hhea", 1}, {"loca", 1}, {"maxp", 1},
+ {"name", 1}, {"glyf", 1}, {"hmtx", 1}, {"fpgm", 0}, {"cvt ", 0},
+ {"prep", 0}, {NULL, 0}
+};
+
+static void
+validate_name (char *fontname, int len)
+{
+ int i, count;
+ char *p;
+ static const char *badstrlist[] = {
+ "-WIN-RKSJ-H",
+ "-WINP-RKSJ-H",
+ "-WING-RKSJ-H",
+ "-90pv-RKSJ-H",
+ NULL
+ };
+
+ for (count = 0, i = 0; i < len; i++) {
+ if (fontname[i] == 0) {
+ memmove(fontname + i, fontname + i + 1, len - i);
+ count++;
+ len--;
+ }
+ }
+ if (count > 0) {
+ WARN("Removed %d null character(s) from fontname --> %s",
+ count, fontname);
+ }
+ fontname[len] = '\0';
+
+ /* For some fonts that have bad PS name. ad hoc. remove me. */
+ for (i = 0; badstrlist[i] != NULL; i++) {
+ p = strstr(fontname, badstrlist[i]);
+ if (p && p > fontname) {
+ WARN("Removed string \"%s\" from fontname \"%s\".",
+ badstrlist[i], fontname);
+ p[0] = '\0';
+ len = (int) (p - fontname);
+ break;
+ }
+ }
+
+ if (len < 1) {
+ ERROR("No valid character found in fontname string.");
+ }
+}
+
+/*
+ * We will follow the convension for finding ToUnicode CMap described in PDF
+ * Reference 4th ed., page 432. The name of "ToCode" (not limited to Unicode
+ * here) CMap is obtained by concatenating the registry, ordering, and the
+ * name of encoding.
+ *
+ * UCSms-UCS4, UCSms-UCS2, UCS4 added...
+ */
+
+#define WIN_UCS_INDEX_MAX 1
+#define KNOWN_ENCODINGS_MAX 9
+static struct
+{
+ unsigned short platform;
+ unsigned short encoding;
+ const char *pdfnames[5];
+} known_encodings[] = {
+ {TT_WIN, TT_WIN_UCS4, {"UCSms-UCS4", "UCSms-UCS2", "UCS4", "UCS2", NULL}},
+ {TT_WIN, TT_WIN_UNICODE, {"UCSms-UCS4", "UCSms-UCS2", "UCS4", "UCS2", NULL}},
+ {TT_WIN, TT_WIN_SJIS, {"90ms-RKSJ", NULL}},
+ {TT_WIN, TT_WIN_RPC, {"GBK-EUC", NULL}},
+ {TT_WIN, TT_WIN_BIG5, {"ETen-B5", NULL}},
+ {TT_WIN, TT_WIN_WANSUNG, {"KSCms-UHC", NULL}},
+ {TT_MAC, TT_MAC_JAPANESE, {"90pv-RKSJ", NULL}},
+ {TT_MAC, TT_MAC_TRADITIONAL_CHINESE, {"B5pc", NULL}},
+ {TT_MAC, TT_MAC_SIMPLIFIED_CHINESE, {"GBpc-EUC", NULL}},
+ {TT_MAC, TT_MAC_KOREAN, {"KSCpc-EUC", NULL}},
+ {0, 0, {NULL}}
+};
+
+static CMap *
+find_tocode_cmap (const char *reg, const char *ord, int select)
+{
+ int cmap_id = -1, i;
+ char *cmap_name;
+ const char *append;
+
+ if (!reg || !ord ||
+ select < 0 || select > KNOWN_ENCODINGS_MAX)
+ ERROR("Character set unknown.");
+
+ if (!strcmp(ord, "UCS") &&
+ select <= WIN_UCS_INDEX_MAX)
+ return NULL;
+
+ for (i = 0; cmap_id < 0 && i < 5; i++) {
+ append = known_encodings[select].pdfnames[i];
+ if (!append)
+ break;
+ cmap_name = NEW(strlen(reg) + strlen(ord) + strlen(append) + 3, char);
+ sprintf(cmap_name, "%s-%s-%s", reg, ord, append);
+ cmap_id = CMap_cache_find(cmap_name);
+ RELEASE(cmap_name);
+ }
+ if (cmap_id < 0) {
+ WARN("Could not find CID-to-Code mapping for \"%s-%s\".", reg, ord);
+ WARN("I tried to load (one of) the following file(s):");
+ for (i = 0; i < 5; i++) {
+ append = known_encodings[select].pdfnames[i];
+ if (!append)
+ break;
+ MESG(" %s-%s-%s", reg, ord, append);
+ }
+ WARN("Please check if this file exists.");
+ ERROR("Cannot continue...");
+ }
+
+ return CMap_cache_get(cmap_id);
+}
+
+
+/*
+ * CIDFont glyph metrics:
+ * Mostly same as add_CID[HV]Metrics in cidtype0.c.
+ */
+#define PDFUNIT(v) ((double) (ROUND(1000.0*(v)/(g->emsize), 1)))
+
+static void
+add_TTCIDHMetrics (pdf_obj *fontdict, struct tt_glyphs *g,
+ char *used_chars, unsigned char *cidtogidmap, unsigned short last_cid)
+{
+ long cid, start = 0, prev = 0;
+ pdf_obj *w_array, *an_array = NULL;
+ double dw;
+ int empty = 1;
+
+ w_array = pdf_new_array();
+ if (g->dw != 0 && g->dw <= g->emsize) {
+ dw = PDFUNIT(g->dw);
+ } else {
+ dw = PDFUNIT(g->gd[0].advw);
+ }
+ for (cid = 0; cid <= last_cid; cid++) {
+ USHORT idx, gid;
+ double width;
+
+ if (!is_used_char2(used_chars, cid))
+ continue;
+ gid = (cidtogidmap) ? ((cidtogidmap[2*cid] << 8)|cidtogidmap[2*cid+1]) : cid;
+ idx = tt_get_index(g, gid);
+ if (cid != 0 && idx == 0)
+ continue;
+ width = PDFUNIT((g->gd)[idx].advw);
+ if (width == dw) {
+ if (an_array) {
+ pdf_add_array(w_array, pdf_new_number(start));
+ pdf_add_array(w_array, an_array);
+ an_array = NULL;
+ empty = 0;
+ }
+ } else {
+ if (cid != prev + 1) {
+ if (an_array) {
+ pdf_add_array(w_array, pdf_new_number(start));
+ pdf_add_array(w_array, an_array);
+ an_array = NULL;
+ empty = 0;
+ }
+ }
+ if (an_array == NULL) {
+ an_array = pdf_new_array();
+ start = cid;
+ }
+ pdf_add_array(an_array, pdf_new_number(width));
+ prev = cid;
+ }
+ }
+
+ if (an_array) {
+ pdf_add_array(w_array, pdf_new_number(start));
+ pdf_add_array(w_array, an_array);
+ empty = 0;
+ }
+
+ pdf_add_dict(fontdict,
+ pdf_new_name("DW"),
+ pdf_new_number(dw));
+ if (!empty) {
+ pdf_add_dict(fontdict,
+ pdf_new_name("W"),
+ pdf_ref_obj(w_array));
+ }
+ pdf_release_obj(w_array);
+
+ return;
+}
+
+static void
+add_TTCIDVMetrics (pdf_obj *fontdict, struct tt_glyphs *g,
+ char *used_chars, unsigned char *cidtogidmap, unsigned short last_cid)
+{
+ pdf_obj *w2_array, *an_array = NULL;
+ long cid;
+#if 0
+ long prev = 0, start = 0;
+#endif
+ double defaultVertOriginY, defaultAdvanceHeight;
+ int empty = 1;
+
+ defaultVertOriginY = PDFUNIT(g->default_advh - g->default_tsb);
+ defaultAdvanceHeight = PDFUNIT(g->default_advh);
+
+ w2_array = pdf_new_array();
+ for (cid = 0; cid <= last_cid; cid++) {
+ USHORT idx;
+#if 0
+ USHORT gid;
+#endif
+ double vertOriginX, vertOriginY, advanceHeight;
+
+ if (!is_used_char2(used_chars, cid))
+ continue;
+#if 0
+ gid = (cidtogidmap) ? ((cidtogidmap[2*cid] << 8)|cidtogidmap[2*cid+1]) : cid;
+#endif
+ idx = tt_get_index(g, (USHORT)cid);
+ if (cid != 0 && idx == 0)
+ continue;
+ advanceHeight = PDFUNIT(g->gd[idx].advh);
+ vertOriginX = PDFUNIT(0.5*(g->gd[idx].advw));
+ vertOriginY = PDFUNIT(g->gd[idx].tsb + g->gd[idx].ury);
+#if 0
+ /*
+ * c [w1_1y v_1x v_1y w1_2y v_2x v_2y ...]
+ * Not working... Why?
+ * Acrobat Reader:
+ * Wrong rendering, interpretation of position vector is wrong.
+ * Xpdf and gs: ignores W2?
+ */
+ if (vertOriginY == defaultVertOriginY &&
+ advanceHeight == defaultAdvanceHeight) {
+ if (an_array) {
+ pdf_add_array(w2_array, pdf_new_number(start));
+ pdf_add_array(w2_array, an_array);
+ an_array = NULL;
+ empty = 0;
+ }
+ } else {
+ if (cid != prev + 1 && an_array) {
+ pdf_add_array(w2_array, pdf_new_number(start));
+ pdf_add_array(w2_array, an_array);
+ an_array = NULL;
+ empty = 0;
+ }
+ if (an_array == NULL) {
+ an_array = pdf_new_array();
+ start = cid;
+ }
+ pdf_add_array(an_array, pdf_new_number(-advanceHeight));
+ pdf_add_array(an_array, pdf_new_number(vertOriginX));
+ pdf_add_array(an_array, pdf_new_number(vertOriginY));
+ prev = cid;
+ }
+#else
+ /*
+ * c_first c_last w1_y v_x v_y
+ * This form may hit Acrobat's implementation limit of array element size,
+ * 8192. AFPL GhostScript 8.11 stops with rangecheck error with this.
+ * Maybe GS's bug?
+ */
+ if (vertOriginY != defaultVertOriginY ||
+ advanceHeight != defaultAdvanceHeight) {
+ pdf_add_array(w2_array, pdf_new_number(cid));
+ pdf_add_array(w2_array, pdf_new_number(cid));
+ pdf_add_array(w2_array, pdf_new_number(-advanceHeight));
+ pdf_add_array(w2_array, pdf_new_number(vertOriginX));
+ pdf_add_array(w2_array, pdf_new_number(vertOriginY));
+ empty = 0;
+ }
+#endif
+ }
+
+#if 0
+ if (an_array) {
+ pdf_add_array(w2_array, pdf_new_number(start));
+ pdf_add_array(w2_array, an_array);
+ empty = 0;
+ }
+#endif
+
+ if (defaultVertOriginY != 880 || defaultAdvanceHeight != 1000) {
+ an_array = pdf_new_array();
+ pdf_add_array(an_array, pdf_new_number(defaultVertOriginY));
+ pdf_add_array(an_array, pdf_new_number(-defaultAdvanceHeight));
+ pdf_add_dict(fontdict, pdf_new_name ("DW2"), an_array);
+ }
+ if (!empty) {
+ pdf_add_dict(fontdict,
+ pdf_new_name("W2"),
+ pdf_ref_obj(w2_array));
+ }
+ pdf_release_obj(w2_array);
+
+ return;
+}
+
+/*
+ * The following routine fixes few problems caused by vendor specific
+ * Unicode mappings.
+ */
+
+#define FIX_CJK_UNIOCDE_SYMBOLS 1
+
+static unsigned short
+fix_CJK_symbols (unsigned short code)
+{
+ unsigned short alt_code;
+ static struct
+ {
+ unsigned short alt1;
+ unsigned short alt2;
+ } CJK_Uni_symbols[] = {
+ /*
+ * Microsoft/Apple Unicode mapping difference:
+ * They are taken from SJIS-Unicode mapping difference but nearly
+ * same thing might be applied to Chinese (e.g., Big5) too.
+ */
+ {0x2014, 0x2015}, /* EM DASH <-> HORIZONTAL BAR */
+ {0x2016, 0x2225}, /* DOUBLE VERTICAL LINE <-> PARALLEL TO */
+ {0x203E, 0xFFE3}, /* OVERLINE <-> FULLWIDTH MACRON */
+ {0x2026, 0x22EF}, /* HORIZONTAL ELLIPSIS <-> MIDLINE HORIZONTAL ELLIPSIS */
+ {0x2212, 0xFF0D}, /* MINUS SIGN <-> FULLWIDTH HYPHEN-MINUS */
+ {0x301C, 0xFF5E}, /* WAVE DASH <-> FULLWIDTH TILDE */
+ {0xFFE0, 0x00A2}, /* FULLWIDTH CENT SIGN <-> CENT SIGN */
+ {0xFFE1, 0x00A3}, /* FULLWIDTH POUND SIGN <-> POUND SIGN */
+ {0xFFE2, 0x00AC}, /* FULLWIDTH NOT SIGN <-> NOT SIGN */
+ {0xFFFF, 0xFFFF}, /* EOD */
+ };
+#define NUM_CJK_SYMBOLS (sizeof(CJK_Uni_symbols)/sizeof(CJK_Uni_symbols[0]))
+ int i;
+
+ alt_code = code;
+ for (i = 0; i < NUM_CJK_SYMBOLS; i++) {
+ if (CJK_Uni_symbols[i].alt1 == code) {
+ alt_code = CJK_Uni_symbols[i].alt2;
+ break;
+ } else if (CJK_Uni_symbols[i].alt2 == code) {
+ alt_code = CJK_Uni_symbols[i].alt1;
+ break;
+ }
+ }
+
+ return alt_code;
+}
+
+static long
+cid_to_code (CMap *cmap, CID cid)
+{
+ unsigned char inbuf[2], outbuf[32];
+ long inbytesleft = 2, outbytesleft = 32;
+ const unsigned char *p;
+ unsigned char *q;
+
+ if (!cmap)
+ return cid;
+
+ inbuf[0] = (cid >> 8) & 0xff;
+ inbuf[1] = cid & 0xff;
+ p = inbuf; q = outbuf;
+
+ CMap_decode_char(cmap, &p, &inbytesleft, &q, &outbytesleft);
+
+ if (inbytesleft != 0)
+ return 0;
+ else if (outbytesleft == 31)
+ return (long) outbuf[0];
+ else if (outbytesleft == 30)
+ return (long) (outbuf[0] << 8|outbuf[1]);
+ else if (outbytesleft == 28) { /* We assume the output encoding is UTF-16. */
+ CID hi, lo;
+ hi = outbuf[0] << 8|outbuf[1];
+ lo = outbuf[2] << 8|outbuf[3];
+ if (hi >= 0xd800 && hi <= 0xdbff && lo >= 0xdc00 && lo <= 0xdfff)
+ return (long) ((hi - 0xd800) * 0x400 + 0x10000 + lo - 0xdc00);
+ else
+ return (long) (hi << 16|lo);
+ }
+
+ return 0;
+}
+
+/* #define NO_GHOSTSCRIPT_BUG 1 */
+
+void
+CIDFont_type2_dofont (CIDFont *font)
+{
+ pdf_obj *fontfile;
+ sfnt *sfont;
+ char *h_used_chars, *v_used_chars, *used_chars;
+ struct tt_glyphs *glyphs;
+ CMap *cmap = NULL;
+ tt_cmap *ttcmap = NULL;
+ unsigned long offset = 0;
+ CID cid, last_cid;
+ unsigned char *cidtogidmap;
+ USHORT num_glyphs;
+ int i, glyph_ordering = 0, unicode_cmap = 0;
+ FILE *fp = NULL;
+
+ if (!font->indirect)
+ return;
+
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("FontDescriptor"), pdf_ref_obj(font->descriptor));
+
+ if (CIDFont_is_BaseFont(font))
+ return;
+
+ /*
+ * CIDSystemInfo comes here since Supplement can be increased.
+ */
+ {
+ pdf_obj *tmp;
+
+ tmp = pdf_new_dict ();
+ pdf_add_dict(tmp,
+ pdf_new_name("Registry"),
+ pdf_new_string(font->csi->registry, strlen(font->csi->registry)));
+ pdf_add_dict(tmp,
+ pdf_new_name("Ordering"),
+ pdf_new_string(font->csi->ordering, strlen(font->csi->ordering)));
+ pdf_add_dict(tmp,
+ pdf_new_name("Supplement"),
+ pdf_new_number(font->csi->supplement));
+ pdf_add_dict(font->fontdict, pdf_new_name("CIDSystemInfo"), tmp);
+ }
+
+ /* Quick exit for non-embedded & fixed-pitch font. */
+ if (!CIDFont_get_embedding(font) &&
+ (opt_flags & CIDFONT_FORCE_FIXEDPITCH)) {
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("DW"), pdf_new_number(1000.0));
+ return;
+ }
+
+#ifdef XETEX
+ sfont = sfnt_open(font->ft_face, SFNT_TYPE_TTC | SFNT_TYPE_TRUETYPE);
+#else
+ fp = DPXFOPEN(font->ident, DPX_RES_TYPE_TTFONT);
+ if (!fp) {
+ fp = DPXFOPEN(font->ident, DPX_RES_TYPE_DFONT);
+ if (!fp) ERROR("Could not open TTF/dfont file: %s", font->ident);
+ sfont = dfont_open(fp, font->options->index);
+ } else {
+ sfont = sfnt_open(fp);
+ }
+#endif
+
+ if (!sfont) {
+ ERROR("Could not open TTF file: %s", font->ident);
+ }
+
+ switch (sfont->type) {
+ case SFNT_TYPE_TTC:
+ offset = ttc_read_offset(sfont, font->options->index);
+ if (offset == 0)
+ ERROR("Invalid TTC index in %s.", font->ident);
+ break;
+ case SFNT_TYPE_TRUETYPE:
+#ifndef XETEX
+ /* disable the check here becuase sfnt_open() does not distinguish dfont
+ * from regular trutype */
+ if (font->options->index > 0)
+ ERROR("Found TrueType font file while expecting TTC file (%s).", font->ident);
+#endif
+ offset = 0;
+ break;
+ case SFNT_TYPE_DFONT:
+ offset = sfont->offset;
+ break;
+ default:
+ ERROR("Not a TrueType/TTC font (%s)?", font->ident);
+ break;
+ }
+
+ if (sfnt_read_table_directory(sfont, offset) < 0)
+ ERROR("Could not read TrueType table directory (%s).", font->ident);
+
+ /*
+ * Adobe-Identity means font's internal glyph ordering here.
+ */
+ if (!strcmp(font->csi->registry, "Adobe") &&
+ !strcmp(font->csi->ordering, "Identity")) {
+ glyph_ordering = 1;
+ } else {
+ glyph_ordering = 0;
+ }
+
+ /*
+ * Select TrueType cmap table, find ToCode CMap for each TrueType encodings.
+ */
+ if (glyph_ordering) {
+ ttcmap = NULL;
+ cmap = NULL;
+ } else {
+ /*
+ * This part contains a bug. It may choose SJIS encoding TrueType cmap
+ * table for Adobe-GB1.
+ */
+ for (i = 0; i <= KNOWN_ENCODINGS_MAX; i++) {
+ ttcmap = tt_cmap_read(sfont,
+ known_encodings[i].platform,
+ known_encodings[i].encoding);
+ if (ttcmap)
+ break;
+ }
+ if (!ttcmap) {
+ WARN("No usable TrueType cmap table found for font \"%s\".", font->ident);
+ WARN("CID character collection for this font is set to \"%s-%s\"",
+ font->csi->registry, font->csi->ordering);
+ ERROR("Cannot continue without this...");
+ } else if (i <= WIN_UCS_INDEX_MAX) {
+ unicode_cmap = 1;
+ } else {
+ unicode_cmap = 0;
+ }
+
+ /*
+ * NULL is returned if CMap is Identity CMap.
+ */
+ cmap = find_tocode_cmap(font->csi->registry,
+ font->csi->ordering, i);
+ }
+
+ glyphs = tt_build_init();
+
+ last_cid = 0;
+ num_glyphs = 1; /* .notdef */
+ used_chars = h_used_chars = v_used_chars = NULL;
+ {
+ Type0Font *parent;
+ int parent_id, c;
+
+ if ((parent_id = CIDFont_get_parent_id(font, 0)) >= 0) {
+ parent = Type0Font_cache_get(parent_id);
+ h_used_chars = Type0Font_get_usedchars(parent);
+ }
+ if ((parent_id = CIDFont_get_parent_id(font, 1)) >= 0) {
+ parent = Type0Font_cache_get(parent_id);
+ v_used_chars = Type0Font_get_usedchars(parent);
+ }
+ if (!h_used_chars && !v_used_chars)
+ ERROR("Unexpected error.");
+
+ /*
+ * Quick check of max CID.
+ */
+ c = 0;
+ for (i = 8191; i >= 0; i--) {
+ if (h_used_chars && h_used_chars[i] != 0) {
+ last_cid = i * 8 + 7;
+ c = h_used_chars[i];
+ break;
+ }
+ if (v_used_chars && v_used_chars[i] != 0) {
+ last_cid = i * 8 + 7;
+ c = v_used_chars[i];
+ break;
+ }
+ }
+ if (last_cid > 0) {
+ for (i = 0; i < 8; i++) {
+ if ((c >> i) & 1)
+ break;
+ last_cid--;
+ }
+ }
+ if (last_cid >= 0xFFFFu) {
+ ERROR("CID count > 65535");
+ }
+ }
+
+#ifndef NO_GHOSTSCRIPT_BUG
+ cidtogidmap = NULL;
+#else
+ cidtogidmap = NEW((last_cid + 1) * 2, unsigned char);
+ memset(cidtogidmap, 0, (last_cid + 1) * 2);
+#endif /* !NO_GHOSTSCRIPT_BUG */
+
+ /*
+ * Map CIDs to GIDs.
+ * Horizontal and vertical used_chars are merged.
+ */
+
+ /*
+ * Horizontal
+ */
+ if (h_used_chars) {
+ used_chars = h_used_chars;
+ for (cid = 1; cid <= last_cid; cid++) {
+ long code;
+ unsigned short gid;
+
+ if (!is_used_char2(h_used_chars, cid))
+ continue;
+
+ if (glyph_ordering) {
+ gid = cid;
+ code = cid;
+ } else {
+ code = cid_to_code(cmap, cid);
+ gid = tt_cmap_lookup(ttcmap, code);
+#ifdef FIX_CJK_UNIOCDE_SYMBOLS
+ if (gid == 0 && unicode_cmap) {
+ long alt_code;
+
+ alt_code = fix_CJK_symbols((unsigned short)code);
+ if (alt_code != code) {
+ gid = tt_cmap_lookup(ttcmap, alt_code);
+ if (gid != 0) {
+ WARN("Unicode char U+%04x replaced with U+%04x.",
+ code, alt_code);
+ }
+ }
+ }
+#endif /* FIX_CJK_UNIOCDE_SYMBOLS */
+ }
+
+ if (gid == 0) {
+ WARN("Glyph missing in font. (CID=%u, code=0x%04x)", cid, code);
+ }
+
+ /* TODO: duplicated glyph */
+#ifndef NO_GHOSTSCRIPT_BUG
+ gid = tt_add_glyph(glyphs, gid, cid);
+#else
+ gid = tt_add_glyph(glyphs, gid, num_glyphs);
+ cidtogidmap[2*cid ] = gid >> 8;
+ cidtogidmap[2*cid+1] = gid & 0xff;
+#endif /* !NO_GHOSTSCRIPT_BUG */
+
+ num_glyphs++;
+ }
+ }
+
+ /*
+ * Vertical
+ */
+ if (v_used_chars) {
+ otl_gsub *gsub_list = NULL;
+
+ /*
+ * Require `vrt2' or `vert'.
+ */
+ if (glyph_ordering) {
+ gsub_list = NULL;
+ } else {
+ gsub_list = otl_gsub_new();
+ if (otl_gsub_add_feat(gsub_list,
+ "*", "*", "vrt2", sfont) < 0) {
+ if (otl_gsub_add_feat(gsub_list,
+ "*", "*", "vert", sfont) < 0) {
+ WARN("GSUB feature vrt2/vert not found.");
+ otl_gsub_release(gsub_list);
+ gsub_list = NULL;
+ } else {
+ otl_gsub_select(gsub_list, "*", "*", "vert");
+ }
+ } else {
+ otl_gsub_select(gsub_list, "*", "*", "vrt2");
+ }
+ }
+
+ for (cid = 1; cid <= last_cid; cid++) {
+ long code;
+ unsigned short gid;
+
+ if (!is_used_char2(v_used_chars, cid))
+ continue;
+
+ /* There may be conflict of horizontal and vertical glyphs
+ * when font is used with /UCS. However, we simply ignore
+ * that...
+ */
+ if (h_used_chars && is_used_char2(h_used_chars, cid)) {
+ continue;
+ }
+
+ if (glyph_ordering) {
+ gid = cid;
+ code = cid;
+ } else {
+ code = cid_to_code(cmap, cid);
+ gid = tt_cmap_lookup(ttcmap, code);
+#ifdef FIX_CJK_UNIOCDE_SYMBOLS
+ if (gid == 0 && unicode_cmap) {
+ long alt_code;
+
+ alt_code = fix_CJK_symbols((unsigned short)code);
+ if (alt_code != code) {
+ gid = tt_cmap_lookup(ttcmap, alt_code);
+ if (gid != 0) {
+ WARN("Unicode char U+%04x replaced with U+%04x.",
+ code, alt_code);
+ }
+ }
+ }
+#endif /* FIX_CJK_UNIOCDE_SYMBOLS */
+ }
+ if (gid == 0) {
+ WARN("Glyph missing in font. (CID=%u, code=0x%04x)", cid, code);
+ } else if (gsub_list) {
+ otl_gsub_apply(gsub_list, &gid);
+ }
+
+#ifndef NO_GHOSTSCRIPT_BUG
+ gid = tt_add_glyph(glyphs, gid, cid);
+#else
+ gid = tt_add_glyph(glyphs, gid, num_glyphs);
+ cidtogidmap[2*cid ] = gid >> 8;
+ cidtogidmap[2*cid+1] = gid & 0xff;
+#endif /* !NO_GHOSTSCRIPT_BUG */
+
+ if (used_chars) /* merge vertical used_chars to horizontal */
+ add_to_used_chars2(used_chars, cid);
+
+ num_glyphs++;
+ }
+
+ if (gsub_list)
+ otl_gsub_release(gsub_list);
+
+ if (!used_chars) /* We have no horizontal. */
+ used_chars = v_used_chars;
+ }
+
+ if (!used_chars)
+ ERROR("Unexpected error.");
+
+ tt_cmap_release(ttcmap);
+
+ if (CIDFont_get_embedding(font)) {
+ if (tt_build_tables(sfont, glyphs) < 0)
+ ERROR("Could not created FontFile stream.");
+ if (verbose > 1)
+ MESG("[%u glyphs (Max CID: %u)]", glyphs->num_glyphs, last_cid);
+ } else {
+ if (tt_get_metrics(sfont, glyphs) < 0)
+ ERROR("Reading glyph metrics failed...");
+ }
+
+ /*
+ * DW, W, DW2, and W2
+ */
+ if (opt_flags & CIDFONT_FORCE_FIXEDPITCH) {
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("DW"), pdf_new_number(1000.0));
+ } else {
+ add_TTCIDHMetrics(font->fontdict, glyphs, used_chars, cidtogidmap, last_cid);
+ if (v_used_chars)
+ add_TTCIDVMetrics(font->fontdict, glyphs, used_chars, cidtogidmap, last_cid);
+ }
+
+ tt_build_finish(glyphs);
+
+ /* Finish here if not embedded. */
+ if (!CIDFont_get_embedding(font)) {
+ if (cidtogidmap)
+ RELEASE(cidtogidmap);
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+
+ return;
+ }
+
+ /* Create font file */
+ for (i = 0; required_table[i].name; i++) {
+ if (sfnt_require_table(sfont,
+ required_table[i].name,
+ required_table[i].must_exist) < 0) {
+ ERROR("Some required TrueType table (%s) does not exist.", required_table[i].name);
+ }
+ }
+
+ /*
+ * FontFile2
+ */
+ fontfile = sfnt_create_FontFile_stream(sfont);
+
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+
+ if (!fontfile)
+ ERROR("Could not created FontFile stream for \"%s\".", font->ident);
+
+ if (verbose > 1) {
+ MESG("[%ld bytes]", pdf_stream_length(fontfile));
+ }
+
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("FontFile2"),
+ pdf_ref_obj (fontfile));
+ pdf_release_obj(fontfile);
+
+ /*
+ * CIDSet
+ */
+ {
+ pdf_obj *cidset;
+
+ cidset = pdf_new_stream(STREAM_COMPRESS);
+ pdf_add_stream(cidset, used_chars, last_cid/8 + 1);
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("CIDSet"),
+ pdf_ref_obj(cidset));
+ pdf_release_obj(cidset);
+ }
+
+ /*
+ * CIDToGIDMap
+ */
+ if (cidtogidmap) {
+ pdf_obj *c2gmstream;
+
+ c2gmstream = pdf_new_stream(STREAM_COMPRESS);
+ pdf_add_stream(c2gmstream, cidtogidmap, (last_cid + 1) * 2);
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("CIDToGIDMap"),
+ pdf_ref_obj (c2gmstream));
+ pdf_release_obj(c2gmstream);
+ RELEASE(cidtogidmap);
+ }
+
+ return;
+}
+
+int
+CIDFont_type2_open (CIDFont *font, const char *name,
+ CIDSysInfo *cmap_csi, cid_opt *opt)
+{
+ char *fontname;
+ sfnt *sfont;
+ unsigned long offset = 0;
+ FILE *fp = NULL;
+
+ ASSERT(font && opt);
+
+#ifdef XETEX
+ sfont = sfnt_open(font->ft_face, SFNT_TYPE_TTC | SFNT_TYPE_TRUETYPE);
+ if (!sfont)
+ return -1;
+#else
+ fp = DPXFOPEN(name, DPX_RES_TYPE_TTFONT);
+ if (!fp) {
+ fp = DPXFOPEN(name, DPX_RES_TYPE_DFONT);
+ if (!fp) return -1;
+ sfont = dfont_open(fp, opt->index);
+ } else {
+ sfont = sfnt_open(fp);
+ }
+
+ if (!sfont) {
+ DPXFCLOSE(fp);
+ return -1;
+ }
+#endif
+
+ switch (sfont->type) {
+ case SFNT_TYPE_TTC:
+ offset = ttc_read_offset(sfont, opt->index);
+ break;
+ case SFNT_TYPE_TRUETYPE:
+#ifdef XETEX
+ /* disable the check here becuase sfnt_open() does not distinguish dfont
+ * from regular trutype */
+ offset = 0;
+#else
+ assert (opt->index == 0);
+ if (opt->index > 0) {
+ ERROR("Invalid TTC index (not TTC font): %s", name);
+ } else {
+ offset = 0;
+ }
+#endif
+ break;
+ case SFNT_TYPE_DFONT:
+ offset = sfont->offset;
+ break;
+ default:
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+ return -1;
+ break;
+ }
+
+ if (sfnt_read_table_directory(sfont, offset) < 0) {
+ ERROR("Reading TrueType table directory failed.");
+ }
+
+ {
+ char *shortname;
+ long namelen;
+
+ /* MAC-ROMAN-EN-POSTSCRIPT or WIN-UNICODE-EN(US)-POSTSCRIPT */
+ shortname = NEW(PDF_NAME_LEN_MAX, char);
+ namelen = tt_get_ps_fontname(sfont, shortname, PDF_NAME_LEN_MAX);
+ if (namelen == 0) {
+ memset(shortname, 0, PDF_NAME_LEN_MAX);
+ strncpy(shortname, name, PDF_NAME_LEN_MAX);
+ namelen = strlen(shortname);
+ }
+ validate_name(shortname, namelen); /* for SJIS, UTF-16, ... string */
+ /*
+ * Strlen works, after validate_named string.
+ * Mangled name requires more 7 bytes.
+ * Style requires more 11 bytes.
+ */
+ fontname = NEW(strlen(shortname)+19, char);
+ strcpy(fontname, shortname);
+ RELEASE(shortname);
+ }
+
+ if (opt->embed && opt->style != FONT_STYLE_NONE) {
+ WARN("Embedding disabled due to style option for %s.", name);
+ opt->embed = 0;
+ }
+ switch (opt->style) {
+ case FONT_STYLE_BOLD:
+ strcat(fontname, ",Bold");
+ break;
+ case FONT_STYLE_ITALIC:
+ strcat(fontname, ",Italic");
+ break;
+ case FONT_STYLE_BOLDITALIC:
+ strcat(fontname, ",BoldItalic");
+ break;
+ }
+ /*
+ * CIDSystemInfo is determined from CMap or from map record option.
+ */
+ font->fontname = fontname;
+ font->subtype = CIDFONT_TYPE2;
+ font->csi = NEW(1, CIDSysInfo);
+ if (opt->csi) {
+ if (cmap_csi) {
+ if (strcmp(opt->csi->registry, cmap_csi->registry) ||
+ strcmp(opt->csi->ordering, cmap_csi->ordering)) {
+ WARN("CID character collection mismatched:\n");
+ MESG("\tFont: %s-%s-%d\n",
+ opt->csi->registry, opt->csi->ordering, opt->csi->supplement);
+ MESG("\tCMap: %s-%s-%d\n",
+ cmap_csi->registry, cmap_csi->ordering, cmap_csi->supplement);
+ ERROR("Incompatible CMap specified for this font.");
+ }
+ if (opt->csi->supplement < cmap_csi->supplement) {
+ WARN("Supplmement value in CIDSystemInfo increased.");
+ WARN("Some characters may not shown.");
+ opt->csi->supplement = cmap_csi->supplement;
+ }
+ }
+ font->csi->registry = NEW(strlen(opt->csi->registry)+1, char);
+ strcpy(font->csi->registry, opt->csi->registry);
+ font->csi->ordering = NEW(strlen(opt->csi->ordering)+1, char);
+ strcpy(font->csi->ordering, opt->csi->ordering);
+ font->csi->supplement = opt->csi->supplement;
+ } else if (cmap_csi) {
+ font->csi->registry = NEW(strlen(cmap_csi->registry)+1, char);
+ strcpy(font->csi->registry, cmap_csi->registry);
+ font->csi->ordering = NEW(strlen(cmap_csi->ordering)+1, char);
+ strcpy(font->csi->ordering, cmap_csi->ordering);
+ font->csi->supplement = cmap_csi->supplement;
+ } else { /* This means font's internal glyph ordering. */
+ font->csi->registry = NEW(strlen("Adobe")+1, char);
+ strcpy(font->csi->registry, "Adobe");
+ font->csi->ordering = NEW(strlen("Identity")+1, char);
+ strcpy(font->csi->ordering, "Identity");
+ font->csi->supplement = 0;
+ }
+
+ font->fontdict = pdf_new_dict();
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("Type"),
+ pdf_new_name("Font"));
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("Subtype"),
+ pdf_new_name("CIDFontType2"));
+
+ font->descriptor = tt_get_fontdesc(sfont, &(opt->embed), opt->stemv, 0, name);
+ if (!font->descriptor) {
+ ERROR("Could not obtain necessary font info.");
+ }
+
+ if (opt->embed) {
+ memmove(fontname + 7, fontname, strlen(fontname) + 1);
+ pdf_font_make_uniqueTag(fontname);
+ fontname[6] = '+';
+ }
+
+ pdf_add_dict(font->descriptor,
+ pdf_new_name("FontName"),
+ pdf_new_name(fontname));
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("BaseFont"),
+ pdf_new_name(fontname));
+
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+
+ /*
+ * Don't write fontdict here.
+ * /Supplement in /CIDSystemInfo may change.
+ */
+
+ return 0;
+}
+
+void
+CIDFont_type2_release (CIDFont *font)
+{
+ return;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/dpxfile.c b/Build/source/texk/dvipdf-x/xsrc/dpxfile.c
new file mode 100644
index 00000000000..a0b124c722e
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/dpxfile.c
@@ -0,0 +1,1175 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2007-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#ifdef _MSC_VER
+#include <kpathsea/dirent.h>
+#endif
+
+#include <time.h>
+
+#include "system.h"
+#include "error.h"
+#include "mem.h"
+
+#include "dpxutil.h"
+#include "mfileio.h"
+
+#include "dpxfile.h"
+#include "dpxcrypt.h"
+#define MAX_KEY_LEN 16
+
+#include <kpathsea/lib.h>
+#include <string.h>
+#ifdef WIN32
+#include <io.h>
+#include <process.h>
+#else
+#if HAVE_SYS_WAIT_H
+#include <sys/wait.h>
+#endif
+#ifndef WEXITSTATUS
+#define WEXITSTATUS(val) ((unsigned)(val) >> 8)
+#endif
+#ifndef WIFEXITED
+#define WIFEXITED(val) (((val) & 255) == 0)
+#endif
+#endif
+
+static int verbose = 0;
+int keep_cache = 0;
+
+void
+dpx_file_set_verbose (void)
+{
+ verbose++;
+}
+
+
+/* Kpathsea library does not check file type. */
+static int qcheck_filetype (const char *fqpn, int type);
+
+/* For testing MIKTEX enabled compilation */
+#if defined(TESTCOMPILE) && !defined(MIKTEX)
+# define MIKTEX 1
+# define PATH_SEP_CHR '/'
+# define _MAX_PATH 256
+
+static int
+miktex_get_acrobat_font_dir (char *buf)
+{
+ strcpy(buf, "/usr/share/ghostscript/Resource/Font/");
+ return 1;
+}
+
+static int
+miktex_find_file (const char *filename, const char *dirlist, char *buf)
+{
+ int r = 0;
+ char *fqpn;
+
+ fqpn = kpse_path_search(dirlist, filename, 0);
+ if (!fqpn)
+ return 0;
+ if (strlen(fqpn) > _MAX_PATH)
+ r = 0;
+ else {
+ strcpy(buf, fqpn);
+ r = 1;
+ }
+ RELEASE(fqpn);
+
+ return r;
+}
+
+static int
+miktex_find_app_input_file (const char *progname, const char *filename, char *buf)
+{
+ int r = 0;
+ char *fqpn;
+
+ kpse_reset_program_name(progname);
+ fqpn = kpse_find_file (filename, kpse_program_text_format, false);
+ kpse_reset_program_name(PACKAGE);
+
+ if (!fqpn)
+ return 0;
+ if (strlen(fqpn) > _MAX_PATH)
+ r = 0;
+ else {
+ strcpy(buf, fqpn);
+ r = 1;
+ }
+ RELEASE(fqpn);
+
+ return r;
+}
+
+static int
+miktex_find_psheader_file (const char *filename, char *buf)
+{
+ int r;
+ char *fqpn;
+
+ fqpn = kpse_find_file(filename, kpse_tex_ps_header_format, 0);
+
+ if (!fqpn)
+ return 0;
+ if (strlen(fqpn) > _MAX_PATH)
+ r = 0;
+ else {
+ strcpy(buf, fqpn);
+ r = 1;
+ }
+ RELEASE(fqpn);
+
+ return r;
+}
+
+#endif /* TESTCOMPILE */
+
+#ifdef MIKTEX
+#ifndef PATH_SEP_CHR
+# define PATH_SEP_CHR '\\'
+#endif
+static char _tmpbuf[_MAX_PATH+1];
+#endif /* MIKTEX */
+
+static int exec_spawn (char *cmd)
+{
+ char **cmdv, **qv;
+ char *p, *pp;
+ char buf[1024];
+ int i, ret = -1;
+
+ if (!cmd)
+ return -1;
+ while (*cmd == ' ' || *cmd == '\t')
+ cmd++;
+ if (*cmd == '\0')
+ return -1;
+ i = 0;
+ p = cmd;
+ while (*p) {
+ if (*p == ' ' || *p == '\t')
+ i++;
+ p++;
+ }
+ cmdv = xcalloc (i + 2, sizeof (char *));
+ p = cmd;
+ qv = cmdv;
+ while (*p) {
+ pp = buf;
+ if (*p == '"') {
+ p++;
+ while (*p != '"') {
+ if (*p == '\0') {
+ goto done;
+ }
+ *pp++ = *p++;
+ }
+ p++;
+ } else if (*p == '\'') {
+ p++;
+ while (*p != '\'') {
+ if (*p == '\0') {
+ goto done;
+ }
+ *pp++ = *p++;
+ }
+ p++;
+ } else {
+ while (*p != ' ' && *p != '\t' && *p) {
+ if (*p == '\'') {
+ p++;
+ while (*p != '\'') {
+ if (*p == '\0') {
+ goto done;
+ }
+ *pp++ = *p++;
+ }
+ p++;
+ } else {
+ *pp++ = *p++;
+ }
+ }
+ }
+ *pp = '\0';
+#ifdef WIN32
+ if (strchr (buf, ' ') || strchr (buf, '\t'))
+ *qv = concat3 ("\"", buf, "\"");
+ else
+#endif
+ *qv = xstrdup (buf);
+/*
+ fprintf(stderr,"\n%s", *qv);
+*/
+ while (*p == ' ' || *p == '\t')
+ p++;
+ qv++;
+ }
+#ifdef WIN32
+ ret = spawnvp (_P_WAIT, *cmdv, (const char* const*) cmdv);
+#else
+ i = fork ();
+ if (i < 0)
+ ret = -1;
+ else if (i == 0) {
+ if (execvp (*cmdv, cmdv))
+ _exit (-1);
+ } else {
+ if (wait (&ret) == i) {
+ ret = (WIFEXITED (ret) ? WEXITSTATUS (ret) : -1);
+ } else {
+ ret = -1;
+ }
+ }
+#endif
+done:
+ qv = cmdv;
+ while (*qv) {
+ free (*qv);
+ qv++;
+ }
+ free (cmdv);
+ return ret;
+}
+
+/* ensuresuffix() returns a copy of basename if sfx is "". */
+static char *
+ensuresuffix (const char *basename, const char *sfx)
+{
+ char *q, *p;
+
+ p = NEW(strlen(basename) + strlen(sfx) + 1, char);
+ strcpy(p, basename);
+ q = strrchr(p, '.');
+ if (!q && sfx[0])
+ strcat(p, sfx);
+
+ return p;
+}
+
+#ifdef MIKTEX
+static char *
+dpx_find__app__xyz (const char *filename,
+ const char *suffix, int is_text)
+{
+ char *fqpn = NULL;
+ int r;
+ char *q;
+
+ q = ensuresuffix(filename, suffix);
+ r = miktex_find_app_input_file(PACKAGE, q, _tmpbuf);
+ if (!r && strcmp(q, filename))
+ r = miktex_find_app_input_file(PACKAGE, filename, _tmpbuf);
+ if (r) {
+ fqpn = NEW(strlen(_tmpbuf) + 1, char);
+ strcpy(fqpn, _tmpbuf);
+ }
+ RELEASE(q);
+
+ return fqpn;
+}
+
+static char *
+dpx_foolsearch (const char *foolname,
+ const char *filename,
+ int is_text)
+{
+ char *fqpn = NULL;
+ int r;
+
+ r = miktex_find_app_input_file(foolname, filename, _tmpbuf);
+ if (r) {
+ fqpn = NEW(strlen(_tmpbuf) + 1, char);
+ strcpy(fqpn, _tmpbuf);
+ }
+
+ return fqpn;
+}
+#else /* !MIKTEX */
+# define TDS11DOC "http://www.tug.org/ftp/tex/tds-1.1/tds.html#Fonts"
+static void
+insistupdate (const char *filename,
+ const char *fqpn,
+ const char *foolname,
+ kpse_file_format_type foolformat,
+ kpse_file_format_type realformat)
+{
+ kpse_format_info_type *fif;
+ kpse_format_info_type *fir;
+ if (verbose < 1)
+ return;
+ fif = &kpse_format_info[foolformat];
+ fir = &kpse_format_info[realformat];
+ WARN("File name=\"%s\" format=\"%s\" might be found in different location than I expected:",
+ filename, fir->type);
+ WARN(">> %s", fqpn);
+ WARN(">> Please adjust your TEXMF as conformant with:");
+ WARN(">> " TDS11DOC);
+ WARN(">> I searched it with fooling kpathsea as progname=\"%s\" format=\"%s\".",
+ foolname, fif->type);
+ WARN(">> Default search path for this format file is:");
+ WARN(">> %s", fir->default_path);
+ WARN(">> Please read \"README\" file.");
+}
+
+static char *
+dpx_find__app__xyz (const char *filename,
+ const char *suffix, int is_text)
+{
+ char *fqpn = NULL;
+ char *q;
+
+ q = ensuresuffix(filename, suffix);
+ fqpn = kpse_find_file(q,
+ (is_text ?
+ kpse_program_text_format : kpse_program_binary_format), 0);
+ if (!fqpn && strcmp(q, filename))
+ fqpn = kpse_find_file(filename,
+ (is_text ?
+ kpse_program_text_format : kpse_program_binary_format), 0);
+ RELEASE(q);
+
+ return fqpn;
+}
+
+static char *
+dpx_foolsearch (const char *foolname,
+ const char *filename,
+ int is_text)
+{
+ char *fqpn = NULL;
+
+ kpse_reset_program_name(foolname);
+ fqpn = kpse_find_file (filename,
+ (is_text ?
+ kpse_program_text_format :
+ kpse_program_binary_format),
+ false);
+ kpse_reset_program_name(PACKAGE);
+
+ return fqpn;
+}
+#endif /* MIKTEX */
+
+static char *dpx_find_fontmap_file (const char *filename);
+static char *dpx_find_agl_file (const char *filename);
+static char *dpx_find_sfd_file (const char *filename);
+static char *dpx_find_cmap_file (const char *filename);
+static char *dpx_find_enc_file (const char *filename);
+static char *dpx_find_iccp_file (const char *filename);
+
+FILE *
+dpx_open_file (const char *filename, int type)
+{
+ FILE *fp = NULL;
+ char *fqpn = NULL;
+
+ switch (type) {
+ case DPX_RES_TYPE_FONTMAP:
+ fqpn = dpx_find_fontmap_file(filename);
+ break;
+ case DPX_RES_TYPE_T1FONT:
+ fqpn = dpx_find_type1_file(filename);
+ break;
+ case DPX_RES_TYPE_TTFONT:
+ fqpn = dpx_find_truetype_file(filename);
+ break;
+ case DPX_RES_TYPE_OTFONT:
+ fqpn = dpx_find_opentype_file(filename);
+ break;
+ case DPX_RES_TYPE_PKFONT:
+ break;
+ case DPX_RES_TYPE_CMAP:
+ fqpn = dpx_find_cmap_file(filename);
+ break;
+ case DPX_RES_TYPE_ENC:
+ fqpn = dpx_find_enc_file(filename);
+ break;
+ case DPX_RES_TYPE_SFD:
+ fqpn = dpx_find_sfd_file(filename);
+ break;
+ case DPX_RES_TYPE_AGL:
+ fqpn = dpx_find_agl_file(filename);
+ break;
+ case DPX_RES_TYPE_ICCPROFILE:
+ fqpn = dpx_find_iccp_file(filename);
+ break;
+ case DPX_RES_TYPE_DFONT:
+ fqpn = dpx_find_dfont_file(filename);
+ break;
+ case DPX_RES_TYPE_BINARY:
+ fqpn = dpx_find__app__xyz(filename, "", 0);
+ break;
+ case DPX_RES_TYPE_TEXT:
+ fqpn = dpx_find__app__xyz(filename, "", 1);
+ break;
+ default:
+ ERROR("Unknown resource type: %d", type);
+ break;
+ }
+ if (fqpn) {
+ fp = MFOPEN(fqpn, FOPEN_RBIN_MODE);
+ RELEASE(fqpn);
+ }
+
+ return fp;
+}
+
+
+static char *
+dpx_find_iccp_file (const char *filename)
+{
+ char *fqpn = NULL;
+
+ fqpn = dpx_find__app__xyz(filename, "", 0);
+ if (fqpn || strrchr(filename, '.'))
+ return fqpn;
+
+ fqpn = dpx_find__app__xyz(filename, ".icc", 0);
+ if (fqpn)
+ return fqpn;
+
+ fqpn = dpx_find__app__xyz(filename, ".icm", 0);
+
+ return fqpn;
+}
+
+
+static char *
+dpx_find_fontmap_file (const char *filename)
+{
+ char *fqpn = NULL;
+ char *q;
+
+ q = ensuresuffix(filename, ".map");
+#ifdef MIKTEX
+ fqpn = dpx_find__app__xyz(q, ".map", 1);
+#else /* !MIKTEX */
+ fqpn = kpse_find_file(q, kpse_fontmap_format, 0);
+ if (!fqpn) {
+ fqpn = dpx_find__app__xyz(q, ".map", 1);
+ if (fqpn)
+ insistupdate(q, fqpn, PACKAGE,
+ kpse_program_text_format, kpse_fontmap_format);
+ }
+#endif /* MIKETEX */
+ RELEASE(q);
+
+ return fqpn;
+}
+
+
+static char *
+dpx_find_agl_file (const char *filename)
+{
+ char *fqpn = NULL;
+ char *q;
+
+ q = ensuresuffix(filename, ".txt");
+#ifdef MIKTEX
+ fqpn = dpx_find__app__xyz(q, ".txt", 1);
+#else /* !MIKTEX */
+ fqpn = kpse_find_file(q, kpse_fontmap_format, 0);
+ if (!fqpn) {
+ fqpn = dpx_find__app__xyz(q, ".txt", 1);
+ if (fqpn)
+ insistupdate(q, fqpn, PACKAGE,
+ kpse_program_text_format, kpse_fontmap_format);
+ }
+#endif /* MIKETEX */
+ RELEASE(q);
+
+ return fqpn;
+}
+
+
+/* cmap.sty put files into tex/latex/cmap */
+static char *
+dpx_find_cmap_file (const char *filename)
+{
+ char *fqpn = NULL;
+ static const char *fools[] = {
+ "cmap", "tex", NULL
+ };
+ int i;
+
+#if defined(MIKTEX)
+ /* Find in Acrobat's Resource/CMap dir */
+ {
+ char _acrodir[_MAX_PATH+1];
+ char *q;
+ int r;
+
+ memset(_acrodir, 0, _MAX_PATH+1);
+ r = miktex_get_acrobat_font_dir(_acrodir);
+ if (r &&
+ strlen(_acrodir) > strlen("Font")) {
+ /* ....\Font\ */
+ q = strrchr(_acrodir, PATH_SEP_CHR);
+ if (q && q[1] == '\0')
+ q[0] = '\0';
+ q = strrchr(_acrodir, PATH_SEP_CHR);
+ if (q && !strcmp(q + 1, "Font")) {
+ sprintf(q, "%cCMap%c", PATH_SEP_CHR, PATH_SEP_CHR);
+ r = miktex_find_file(filename, _acrodir, _tmpbuf);
+ if (r) {
+ fqpn = NEW(strlen(_tmpbuf) + 1, char);
+ strcpy(fqpn, _tmpbuf);
+ }
+ }
+ }
+ memset(_tmpbuf, 0, _MAX_PATH+1);
+ }
+#else
+ fqpn = kpse_find_file(filename, kpse_cmap_format, 0);
+#endif
+
+ /* Files found above are assumed to be CMap,
+ * if it's not really CMap it will cause an error.
+ */
+ for (i = 0; !fqpn && fools[i]; i++) {
+ fqpn = dpx_foolsearch(fools[i], filename, 1);
+ if (fqpn) {
+#ifndef MIKTEX
+ insistupdate(filename, fqpn, fools[i],
+ kpse_program_text_format, kpse_cmap_format);
+#endif
+ if (!qcheck_filetype(fqpn, DPX_RES_TYPE_CMAP)) {
+ WARN("Found file \"%s\" for PostScript CMap but it doesn't look like a CMap...", fqpn);
+ RELEASE(fqpn);
+ fqpn = NULL;
+ }
+ }
+ }
+
+ return fqpn;
+}
+
+
+/* Search order:
+ * SFDFONTS (TDS 1.1)
+ * ttf2pk (text file)
+ * ttf2tfm (text file)
+ * dvipdfm (text file)
+ */
+static char *
+dpx_find_sfd_file (const char *filename)
+{
+ char *fqpn = NULL;
+ char *q;
+ static const char *fools[] = {
+ "ttf2pk", "ttf2tfm", NULL
+ };
+ int i;
+
+ q = ensuresuffix(filename, ".sfd");
+#ifndef MIKTEX
+ fqpn = kpse_find_file(q, kpse_sfd_format, 0);
+#endif /* !MIKTEX */
+
+ for (i = 0; !fqpn && fools[i]; i++) {
+ fqpn = dpx_foolsearch(fools[i], q, 1);
+#ifndef MIKTEX
+ if (fqpn)
+ insistupdate(filename, fqpn, fools[i],
+ kpse_program_text_format, kpse_sfd_format);
+#endif
+ }
+ RELEASE(q);
+
+ return fqpn;
+}
+
+
+static char *
+dpx_find_enc_file (const char *filename)
+{
+ char *fqpn = NULL;
+ char *q;
+ static const char *fools[] = {
+ "dvips", NULL
+ };
+ int i;
+
+ q = ensuresuffix(filename, ".enc");
+#ifdef MIKTEX
+ if (miktex_find_psheader_file(q, _tmpbuf)) {
+ fqpn = NEW(strlen(_tmpbuf) + 1, char);
+ strcpy(fqpn, _tmpbuf);
+ }
+#else
+ fqpn = kpse_find_file(q, kpse_enc_format, 0);
+#endif /* MIKTEX */
+
+ for (i = 0; !fqpn && fools[i]; i++) {
+ fqpn = dpx_foolsearch(fools[i], q, 1);
+#ifndef MIKTEX
+ if (fqpn)
+ insistupdate(filename, fqpn, fools[i],
+ kpse_program_text_format, kpse_enc_format);
+#endif
+ }
+ RELEASE(q);
+
+ return fqpn;
+}
+
+static int
+is_absolute_path(const char *filename)
+{
+#ifdef WIN32
+ if (isalpha(filename[0]) && filename[1] == ':')
+ return 1;
+ if (filename[0] == '\\' && filename[1] == '\\')
+ return 1;
+ if (filename[0] == '/' && filename[1] == '/')
+ return 1;
+#else
+ if (filename[0] == '/')
+ return 1;
+#endif
+ return 0;
+}
+
+char *
+dpx_find_type1_file (const char *filename)
+{
+ char *fqpn = NULL;
+
+ if (is_absolute_path(filename))
+ fqpn = xstrdup(filename);
+ else
+ fqpn = kpse_find_file(filename, kpse_type1_format, 0);
+ if (fqpn && !qcheck_filetype(fqpn, DPX_RES_TYPE_T1FONT)) {
+ RELEASE(fqpn);
+ fqpn = NULL;
+ }
+
+ return fqpn;
+}
+
+
+char *
+dpx_find_truetype_file (const char *filename)
+{
+ char *fqpn = NULL;
+
+ if (is_absolute_path(filename))
+ fqpn = xstrdup(filename);
+ else
+ fqpn = kpse_find_file(filename, kpse_truetype_format, 0);
+ if (fqpn && !qcheck_filetype(fqpn, DPX_RES_TYPE_TTFONT)) {
+ RELEASE(fqpn);
+ fqpn = NULL;
+ }
+
+ return fqpn;
+}
+
+
+char *
+dpx_find_opentype_file (const char *filename)
+{
+ char *fqpn = NULL;
+ char *q;
+
+ q = ensuresuffix(filename, ".otf");
+#ifndef MIKTEX
+ if (is_absolute_path(q))
+ fqpn = xstrdup(q);
+ else
+ fqpn = kpse_find_file(q, kpse_opentype_format, 0);
+ if (!fqpn) {
+#endif
+ fqpn = dpx_foolsearch(PACKAGE, q, 0);
+#ifndef MIKTEX
+ if (fqpn)
+ insistupdate(filename, fqpn, PACKAGE,
+ kpse_program_binary_format, kpse_opentype_format);
+ }
+#endif
+ RELEASE(q);
+
+ /* *We* use "opentype" for ".otf" (CFF). */
+ if (fqpn && !qcheck_filetype(fqpn, DPX_RES_TYPE_OTFONT)) {
+ RELEASE(fqpn);
+ fqpn = NULL;
+ }
+
+ return fqpn;
+}
+
+
+
+char *
+dpx_find_dfont_file (const char *filename)
+{
+ char *fqpn = NULL;
+
+ fqpn = kpse_find_file(filename, kpse_truetype_format, 0);
+ if (fqpn) {
+ int len = strlen(fqpn);
+ if (len > 6 && strncmp(fqpn+len-6, ".dfont", 6)) {
+ fqpn = RENEW(fqpn, len+6, char);
+ strcat(fqpn, "/rsrc");
+ }
+ }
+ if (!qcheck_filetype(fqpn, DPX_RES_TYPE_DFONT)) {
+ RELEASE(fqpn);
+ fqpn = NULL;
+ }
+ return fqpn;
+}
+
+static const char *
+dpx_get_tmpdir (void)
+{
+# ifdef WIN32
+# define __TMPDIR "."
+# else /* WIN32 */
+# define __TMPDIR "/tmp"
+#endif /* WIN32 */
+ const char *_tmpd;
+
+# ifdef HAVE_GETENV
+ _tmpd = getenv("TMPDIR");
+# ifdef WIN32
+ if (!_tmpd)
+ _tmpd = getenv("TMP");
+ if (!_tmpd)
+ _tmpd = getenv("TEMP");
+# endif /* WIN32 */
+ if (!_tmpd)
+ _tmpd = __TMPDIR;
+# else /* HAVE_GETENV */
+ _tmpd = __TMPDIR;
+# endif /* HAVE_GETENV */
+ return _tmpd;
+}
+
+#ifdef HAVE_MKSTEMP
+# include <stdlib.h>
+#endif
+
+#ifdef XETEX
+char *
+dpx_create_temp_file (void)
+{
+ char *tmp = NULL;
+
+#if defined(MIKTEX)
+ {
+ tmp = NEW(_MAX_PATH + 1, char);
+ miktex_create_temp_file_name(tmp); /* FIXME_FIXME */
+ }
+#elif defined(HAVE_MKSTEMP)
+# define TEMPLATE "/dvipdfmx.XXXXXXXX"
+ {
+ const char *_tmpd;
+ int _fd = -1;
+ _tmpd = dpx_get_tmpdir();
+ tmp = NEW(strlen(_tmpd) + strlen(TEMPLATE) + 1, char);
+ strcpy(tmp, _tmpd);
+ strcat(tmp, TEMPLATE);
+ _fd = mkstemp(tmp);
+ if (_fd != -1)
+#ifdef WIN32
+ _close(_fd);
+#else
+ close(_fd);
+#endif /* WIN32 */
+ else {
+ RELEASE(tmp);
+ tmp = NULL;
+ }
+ }
+#else /* use _tempnam or tmpnam */
+ {
+# ifdef WIN32
+ const char *_tmpd;
+ char *p;
+ _tmpd = dpx_get_tmpdir();
+ tmp = _tempnam (_tmpd, "dvipdfmx.");
+ for (p = tmp; *p; p++) {
+ if (IS_KANJI (p))
+ p++;
+ else if (*p == '\\')
+ *p = '/';
+ }
+# else /* WIN32 */
+ char *_tmpa = NEW(L_tmpnam + 1, char);
+ tmp = tmpnam(_tmpa);
+ if (!tmp)
+ RELEASE(_tmpa);
+# endif /* WIN32 */
+ }
+#endif /* MIKTEX */
+
+ return tmp;
+}
+#endif /* XETEX */
+
+char *
+dpx_create_fix_temp_file (const char *filename)
+{
+#define PREFIX "xdvipdfmx."
+ static const char *dir = NULL;
+ static char *cwd = NULL;
+ char *ret, *s;
+ int i;
+ MD5_CONTEXT state;
+ unsigned char digest[MAX_KEY_LEN];
+#ifdef WIN32
+ char *p;
+#endif
+
+ if (!dir) {
+ dir = dpx_get_tmpdir();
+ cwd = xgetcwd();
+ }
+
+ MD5_init(&state);
+ MD5_write(&state, (unsigned char *)cwd, strlen(cwd));
+ MD5_write(&state, (unsigned const char *)filename, strlen(filename));
+ MD5_final(digest, &state);
+
+ ret = NEW(strlen(dir)+1+strlen(PREFIX)+MAX_KEY_LEN*2 + 1, char);
+ sprintf(ret, "%s/%s", dir, PREFIX);
+ s = ret + strlen(ret);
+ for (i=0; i<MAX_KEY_LEN; i++) {
+ sprintf(s, "%02x", digest[i]);
+ s += 2;
+ }
+#ifdef WIN32
+ for (p = ret; *p; p++) {
+ if (IS_KANJI (p))
+ p++;
+ else if (*p == '\\')
+ *p = '/';
+ }
+#endif
+ /* printf("dpx_create_fix_temp_file: %s\n", ret); */
+ return ret;
+}
+
+static int
+dpx_clear_cache_filter (const struct dirent *ent) {
+ int plen = strlen(PREFIX);
+ if (strlen(ent->d_name) != plen + MAX_KEY_LEN * 2) return 0;
+#ifdef WIN32
+ return strncasecmp(ent->d_name, PREFIX, plen) == 0;
+#else
+ return strncmp(ent->d_name, PREFIX, plen) == 0;
+#endif
+}
+
+void
+dpx_delete_old_cache (int life)
+{
+ const char *dir;
+ char *pathname;
+ DIR *dp;
+ struct dirent *de;
+ time_t limit;
+
+ if (life == -2) {
+ keep_cache = -1;
+ return;
+ }
+
+ dir = dpx_get_tmpdir();
+ pathname = NEW(strlen(dir)+1+strlen(PREFIX)+MAX_KEY_LEN*2 + 1, char);
+ limit = time(NULL) - life * 60 * 60;
+
+ if (life >= 0) keep_cache = 1;
+ if ((dp = opendir(dir)) != NULL) {
+ while((de = readdir(dp)) != NULL) {
+ if (dpx_clear_cache_filter(de)) {
+ struct stat sb;
+ sprintf(pathname, "%s/%s", dir, de->d_name);
+ stat(pathname, &sb);
+ if (sb.st_mtime < limit) {
+ remove(pathname);
+ /* printf("remove: %s\n", pathname); */
+ }
+ }
+ }
+ closedir(dp);
+ }
+ RELEASE(pathname);
+}
+
+void
+dpx_delete_temp_file (char *tmp, int force)
+{
+ if (!tmp)
+ return;
+ if (force || keep_cache != 1) remove (tmp);
+ RELEASE(tmp);
+
+ return;
+}
+
+/* dpx_file_apply_filter() is used for converting unsupported graphics
+ * format to one of the formats that dvipdfmx can natively handle.
+ * 'input' is the filename of the original file and 'output' is actually
+ * temporal files 'generated' by the above routine.
+ * This should be system dependent. (MiKTeX may want something different)
+ * Please modify as appropriate (see also pdfximage.c and dvipdfmx.c).
+ */
+int
+dpx_file_apply_filter (const char *cmdtmpl,
+ const char *input, const char *output,
+ unsigned char version)
+{
+ char *cmd = NULL;
+ const char *p, *q;
+ size_t n, size;
+ int error = 0;
+
+ if (!cmdtmpl)
+ return -1;
+ else if (!input || !output)
+ return -1;
+
+ size = strlen(cmdtmpl) + strlen(input) + strlen(output) + 3;
+ cmd = NEW(size, char);
+ memset(cmd, 0, size);
+ for (n = 0, p = cmdtmpl; *p != 0; p++) {
+#define need(s,l,m,n) \
+if ((l) + (n) >= (m)) { \
+ (m) += (n) + 128; \
+ (s) = RENEW((s), (m), char); \
+}
+ if (p[0] == '%') {
+ p++;
+ switch (p[0]) {
+ case 'o': /* Output file name */
+ need(cmd, n, size, strlen(output));
+ strcpy(cmd + n, output); n += strlen(output);
+ break;
+ case 'i': /* Input filename */
+ need(cmd, n, size, strlen(input));
+ strcpy(cmd + n, input); n += strlen(input);
+ break;
+ case 'b':
+ need(cmd, n, size, strlen(input));
+ q = strrchr(input, '.'); /* wrong */
+ if (q) {
+ memcpy(cmd + n, input, (int) (q - input));
+ n += (int) (q - input);
+ } else {
+ strcpy(cmd + n, input); n += strlen(input);
+ }
+ case 'v': /* Version number, e.g. 1.4 */ {
+ char buf[6];
+ sprintf(buf, "1.%hu", (unsigned short) version);
+ need(cmd, n, size, strlen(buf));
+ strcpy(cmd + n, buf); n += strlen(buf);
+ break;
+ }
+ case 0:
+ break;
+ case '%':
+ need(cmd, n, size, 1);
+ cmd[n] = '%'; n++;
+ break;
+ }
+ } else {
+ need(cmd, n, size, 1);
+ cmd[n] = p[0]; n++;
+ }
+ }
+ need(cmd, n, size, 1);
+ cmd[n] = '\0';
+ if (strlen(cmd) == 0) {
+ RELEASE(cmd);
+ return -1;
+ }
+
+ error = exec_spawn(cmd);
+ if (error)
+ WARN("Filtering file via command -->%s<-- failed.", cmd);
+ RELEASE(cmd);
+
+ return error;
+}
+
+static char _sbuf[128];
+/*
+ * SFNT type sigs:
+ * `true' (0x74727565): TrueType (Mac)
+ * `typ1' (0x74797031) (Mac): PostScript font housed in a sfnt wrapper
+ * 0x00010000: TrueType (Win)/OpenType
+ * `OTTO': PostScript CFF font with OpenType wrapper
+ * `ttcf': TrueType Collection
+ */
+static int
+istruetype (FILE *fp)
+{
+ int n;
+
+ rewind(fp);
+ n = fread(_sbuf, 1, 4, fp);
+ rewind(fp);
+
+ if (n != 4)
+ return 0;
+ else if (!memcmp(_sbuf, "true", 4) ||
+ !memcmp(_sbuf, "\0\1\0\0", 4)) /* This doesn't help... */
+ return 1;
+ else if (!memcmp(_sbuf, "ttcf", 4))
+ return 1;
+
+ return 0;
+}
+
+/* "OpenType" is only for ".otf" here */
+static int
+isopentype (FILE *fp)
+{
+ int n;
+
+ rewind(fp);
+ n = fread(_sbuf, 1, 4, fp);
+ rewind(fp);
+
+ if (n != 4)
+ return 0;
+ else if (!memcmp(_sbuf, "OTTO", 4))
+ return 1;
+ else
+ return 0;
+}
+
+static int
+ist1binary (FILE *fp)
+{
+ char *p;
+ int n;
+
+ rewind(fp);
+ n = fread(_sbuf, 1, 21, fp);
+ rewind(fp);
+
+ p = _sbuf;
+ if (n != 21)
+ return 0;
+ else if (p[0] != (char) 0x80 || p[1] < 0 || p[1] > 3)
+ return 0;
+ else if (!memcmp(p + 6, "%!PS-AdobeFont", 14) ||
+ !memcmp(p + 6, "%!FontType1", 11))
+ return 1;
+ else if (!memcmp(p + 6, "%!PS", 4)) {
+#if 0
+ p[20] = '\0'; p += 6;
+ WARN("Ambiguous PostScript resource type: %s", (char *) p);
+#endif
+ return 1;
+ }
+ /* Otherwise ambiguious */
+ return 0;
+}
+
+/* %!PS-Adobe-x.y Resource-CMap */
+static int
+ispscmap (FILE *fp)
+{
+ char *p;
+ p = mfgets(_sbuf, 128, fp); p[127] = '\0';
+ if (!p || strlen(p) < 4 || memcmp(p, "%!PS", 4))
+ return 0;
+ for (p += 4; *p && !isspace(*p); p++);
+ for ( ; *p && (*p == ' ' || *p == '\t'); p++);
+ if (*p == '\0' || strlen(p) < strlen("Resource-CMap"))
+ return 0;
+ else if (!memcmp(p, "Resource-CMap", strlen("Resource-CMap")))
+ return 1;
+ /* Otherwise ambiguious */
+ return 0;
+}
+
+static int
+isdfont (FILE *fp)
+{
+ int i, n;
+ unsigned long pos;
+
+ rewind(fp);
+
+ get_unsigned_quad(fp);
+ seek_absolute(fp, (pos = get_unsigned_quad(fp)) + 0x18);
+ seek_absolute(fp, pos + get_unsigned_pair(fp));
+ n = get_unsigned_pair(fp);
+ for (i = 0; i <= n; i++) {
+ if (get_unsigned_quad(fp) == 0x73666e74UL) /* "sfnt" */
+ return 1;
+ get_unsigned_quad(fp);
+ }
+ return 0;
+}
+
+/* This actually opens files. */
+static int
+qcheck_filetype (const char *fqpn, int type)
+{
+ int r = 1;
+ FILE *fp;
+
+ if (!fqpn)
+ return 0;
+
+ fp = MFOPEN(fqpn, FOPEN_RBIN_MODE);
+ if (!fp) {
+ WARN("File \"%s\" found but I could not open that...", fqpn);
+ return 0;
+ }
+ switch (type) {
+ case DPX_RES_TYPE_T1FONT:
+ r = ist1binary(fp);
+ break;
+ case DPX_RES_TYPE_TTFONT:
+ r = istruetype(fp);
+ break;
+ case DPX_RES_TYPE_OTFONT:
+ r = isopentype(fp);
+ break;
+ case DPX_RES_TYPE_CMAP:
+ r = ispscmap(fp);
+ break;
+ case DPX_RES_TYPE_DFONT:
+ r = isdfont(fp);
+ break;
+ }
+ MFCLOSE(fp);
+
+ return r;
+}
+
diff --git a/Build/source/texk/dvipdf-x/xsrc/dpxfile.h b/Build/source/texk/dvipdf-x/xsrc/dpxfile.h
new file mode 100644
index 00000000000..e4ae4c0a679
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/dpxfile.h
@@ -0,0 +1,70 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _DPXFILE_H_
+#define _DPXFILE_H_
+
+#define DPX_CONFIG_FILE "dvipdfmx.cfg"
+
+#define DPX_RES_TYPE_FONTMAP 0x00
+
+#define DPX_RES_TYPE_T1FONT 0x10
+#define DPX_RES_TYPE_TTFONT 0x11
+#define DPX_RES_TYPE_OTFONT 0x12
+#define DPX_RES_TYPE_PKFONT 0x13
+#define DPX_RES_TYPE_DFONT 0x14
+
+#define DPX_RES_TYPE_ENC 0x20
+#define DPX_RES_TYPE_CMAP 0x21
+#define DPX_RES_TYPE_SFD 0x22
+#define DPX_RES_TYPE_AGL 0x23
+
+#define DPX_RES_TYPE_ICCPROFILE 0x30
+
+#define DPX_RES_TYPE_BINARY 0x40
+#define DPX_RES_TYPE_TEXT 0x41
+
+#include "mfileio.h"
+extern FILE *dpx_open_file (const char *filename, int type);
+
+extern char * dpx_find_type1_file (const char *filename);
+extern char * dpx_find_truetype_file (const char *filename);
+extern char * dpx_find_opentype_file (const char *filename);
+extern char * dpx_find_dfont_file (const char *filename);
+
+#define DPXFOPEN(n,t) dpx_open_file((const char *)(n),(t))
+#define DPXFCLOSE(f) MFCLOSE((f))
+
+extern void dpx_file_set_verbose (void);
+
+extern int dpx_file_apply_filter (const char *cmdtmpl,
+ const char *input, const char *output,
+ unsigned char version);
+extern char *dpx_create_temp_file (void);
+extern char *dpx_create_fix_temp_file (const char *filename);
+extern void dpx_delete_old_cache (int life);
+extern void dpx_delete_temp_file (char *tmp, int force); /* tmp freed here */
+
+extern int keep_cache;
+#endif /* _DPXFILE_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/dpxutil.c b/Build/source/texk/dvipdf-x/xsrc/dpxutil.c
new file mode 100644
index 00000000000..98ba7cde9d4
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/dpxutil.c
@@ -0,0 +1,651 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+
+#include "dpxutil.h"
+
+int
+xtoi (char c)
+{
+ if (c >= '0' && c <= '9')
+ return (c - '0');
+ else if (c >= 'a' && c <= 'f')
+ return (c - 'W');
+ else if (c >= 'A' && c <= 'F')
+ return (c - '7');
+ else
+ return -1;
+}
+
+int
+sputx (unsigned char c, char **s, char *end)
+{
+ char hi = (c >> 4), lo = c & 0x0f;
+
+ if (*s + 2 > end)
+ ERROR("Buffer overflow.");
+ **s = (hi < 10) ? hi + '0' : hi + '7';
+ *(*s+1) = (lo < 10) ? lo + '0' : lo + '7';
+ *s += 2;
+
+ return 2;
+}
+
+int
+getxpair (unsigned char **s)
+{
+ int hi, lo;
+ hi = xtoi(**s);
+ if (hi < 0)
+ return hi;
+ (*s)++;
+ lo = xtoi(**s);
+ if (lo < 0)
+ return lo;
+ (*s)++;
+ return ((hi << 4)| lo);
+}
+
+int
+putxpair (unsigned char c, char **s)
+{
+ char hi = (c >> 4), lo = c & 0x0f;
+
+ **s = (hi < 10) ? hi + '0' : hi + '7';
+ *(*s+1) = (lo < 10) ? lo + '0' : lo + '7';
+ *s += 2;
+
+ return 2;
+}
+
+/* Overflowed value is set to invalid char. */
+unsigned char
+ostrtouc (unsigned char **inbuf, unsigned char *inbufend, unsigned char *valid)
+{
+ unsigned char *cur = *inbuf;
+ unsigned int val = 0;
+
+ while (cur < inbufend && cur < *inbuf + 3 &&
+ (*cur >= '0' && *cur <= '7')) {
+ val = (val << 3) | (*cur - '0');
+ cur++;
+ }
+ if (val > 255 || cur == *inbuf)
+ *valid = 0;
+ else
+ *valid = 1;
+
+ *inbuf = cur;
+ return (unsigned char) val;
+}
+
+unsigned char
+esctouc (unsigned char **inbuf, unsigned char *inbufend, unsigned char *valid)
+{
+ unsigned char unescaped, escaped;
+
+ escaped = **inbuf;
+ *valid = 1;
+ switch (escaped) {
+ /* Backslash, unbalanced paranthes */
+ case '\\': case ')': case '(':
+ unescaped = escaped;
+ (*inbuf)++;
+ break;
+ /* Other escaped char */
+ case 'n': unescaped = '\n'; (*inbuf)++; break;
+ case 'r': unescaped = '\r'; (*inbuf)++; break;
+ case 't': unescaped = '\t'; (*inbuf)++; break;
+ case 'b': unescaped = '\b'; (*inbuf)++; break;
+ case 'f': unescaped = '\f'; (*inbuf)++; break;
+ /*
+ * An end-of-line marker preceeded by backslash is not part of a
+ * literal string
+ */
+ case '\r':
+ unescaped = 0;
+ *valid = 0;
+ *inbuf += (*inbuf < inbufend - 1 && *(*inbuf+1) == '\n') ? 2 : 1;
+ break;
+ case '\n':
+ unescaped = 0;
+ *valid = 0;
+ (*inbuf)++;
+ break;
+ /* Possibly octal notion */
+ default:
+ unescaped = ostrtouc(inbuf, inbufend, valid);
+ }
+
+ return unescaped;
+}
+
+void
+skip_white_spaces (unsigned char **s, unsigned char *endptr)
+{
+ while (*s < endptr)
+ if (!is_space(**s))
+ break;
+ else
+ (*s)++;
+}
+
+void
+ht_init_table (struct ht_table *ht, hval_free_func hval_free_fn)
+{
+ int i;
+
+ ASSERT(ht);
+
+ for (i = 0; i < HASH_TABLE_SIZE; i++) {
+ ht->table[i] = NULL;
+ }
+ ht->count = 0;
+ ht->hval_free_fn = hval_free_fn;
+}
+
+void
+ht_clear_table (struct ht_table *ht)
+{
+ int i;
+
+ ASSERT(ht);
+
+ for (i = 0; i < HASH_TABLE_SIZE; i++) {
+ struct ht_entry *hent, *next;
+
+ hent = ht->table[i];
+ while (hent) {
+ if (hent->value && ht->hval_free_fn) {
+ ht->hval_free_fn(hent->value);
+ }
+ hent->value = NULL;
+ if (hent->key) {
+ RELEASE(hent->key);
+ }
+ hent->key = NULL;
+ next = hent->next;
+ RELEASE(hent);
+ hent = next;
+ }
+ ht->table[i] = NULL;
+ }
+ ht->count = 0;
+ ht->hval_free_fn = NULL;
+}
+
+static unsigned int
+get_hash (const void *key, int keylen)
+{
+ unsigned int hkey = 0;
+ int i;
+
+ for (i = 0; i < keylen; i++) {
+ hkey = (hkey << 5) + hkey + ((const char *)key)[i];
+ }
+
+ return (hkey % HASH_TABLE_SIZE);
+}
+
+void *
+ht_lookup_table (struct ht_table *ht, const void *key, int keylen)
+{
+ struct ht_entry *hent;
+ unsigned int hkey;
+
+ ASSERT(ht && key);
+
+ hkey = get_hash(key, keylen);
+ hent = ht->table[hkey];
+ while (hent) {
+ if (hent->keylen == keylen &&
+ !memcmp(hent->key, key, keylen)) {
+ return hent->value;
+ }
+ hent = hent->next;
+ }
+
+ return NULL;
+}
+
+int
+ht_remove_table (struct ht_table *ht,
+ const void *key, int keylen)
+/* returns 1 if the element was found and removed and 0 otherwise */
+{
+ struct ht_entry *hent, *prev;
+ unsigned int hkey;
+
+ ASSERT(ht && key);
+
+ hkey = get_hash(key, keylen);
+ hent = ht->table[hkey];
+ prev = NULL;
+ while (hent) {
+ if (hent->keylen == keylen &&
+ !memcmp(hent->key, key, keylen)) {
+ break;
+ }
+ prev = hent;
+ hent = hent->next;
+ }
+ if (hent) {
+ if (hent->key)
+ RELEASE(hent->key);
+ hent->key = NULL;
+ hent->keylen = 0;
+ if (hent->value && ht->hval_free_fn) {
+ ht->hval_free_fn(hent->value);
+ }
+ hent->value = NULL;
+ if (prev) {
+ prev->next = hent->next;
+ } else {
+ ht->table[hkey] = hent->next;
+ }
+ RELEASE(hent);
+ ht->count--;
+ return 1;
+ } else
+ return 0;
+}
+
+/* replace... */
+void
+ht_insert_table (struct ht_table *ht,
+ const void *key, int keylen, void *value)
+{
+ struct ht_entry *hent, *prev;
+ unsigned int hkey;
+
+ ASSERT(ht && key);
+
+ hkey = get_hash(key, keylen);
+ hent = ht->table[hkey];
+ prev = NULL;
+ while (hent) {
+ if (hent->keylen == keylen &&
+ !memcmp(hent->key, key, keylen)) {
+ break;
+ }
+ prev = hent;
+ hent = hent->next;
+ }
+ if (hent) {
+ if (hent->value && ht->hval_free_fn)
+ ht->hval_free_fn(hent->value);
+ hent->value = value;
+ } else {
+ hent = NEW(1, struct ht_entry);
+ hent->key = NEW(keylen, char);
+ memcpy(hent->key, key, keylen);
+ hent->keylen = keylen;
+ hent->value = value;
+ hent->next = NULL;
+ if (prev) {
+ prev->next = hent;
+ } else {
+ ht->table[hkey] = hent;
+ }
+ ht->count++;
+ }
+}
+
+void
+ht_append_table (struct ht_table *ht,
+ const void *key, int keylen, void *value)
+{
+ struct ht_entry *hent, *last;
+ unsigned int hkey;
+
+ hkey = get_hash(key, keylen);
+ hent = ht->table[hkey];
+ if (!hent) {
+ hent = NEW(1, struct ht_entry);
+ ht->table[hkey] = hent;
+ } else {
+ while (hent) {
+ last = hent;
+ hent = hent->next;
+ }
+ hent = NEW(1, struct ht_entry);
+ last->next = hent;
+ }
+ hent->key = NEW(keylen, char);
+ memcpy(hent->key, key, keylen);
+ hent->keylen = keylen;
+ hent->value = value;
+ hent->next = NULL;
+
+ ht->count++;
+}
+
+int
+ht_set_iter (struct ht_table *ht, struct ht_iter *iter)
+{
+ int i;
+
+ ASSERT(ht && ht->table && iter);
+
+ for (i = 0; i < HASH_TABLE_SIZE; i++) {
+ if (ht->table[i]) {
+ iter->index = i;
+ iter->curr = ht->table[i];
+ iter->hash = ht;
+ return 0;
+ }
+ }
+
+ return -1;
+}
+
+void
+ht_clear_iter (struct ht_iter *iter)
+{
+ if (iter) {
+ iter->index = HASH_TABLE_SIZE;
+ iter->curr = NULL;
+ iter->hash = NULL;
+ }
+}
+
+char *
+ht_iter_getkey (struct ht_iter *iter, int *keylen)
+{
+ struct ht_entry *hent;
+
+ hent = (struct ht_entry *) iter->curr;
+ if (iter && hent) {
+ *keylen = hent->keylen;
+ return hent->key;
+ } else {
+ *keylen = 0;
+ return NULL;
+ }
+}
+
+void *
+ht_iter_getval (struct ht_iter *iter)
+{
+ struct ht_entry *hent;
+
+ hent = (struct ht_entry *) iter->curr;
+ if (iter && hent) {
+ return hent->value;
+ } else {
+ return NULL;
+ }
+}
+
+int
+ht_iter_next (struct ht_iter *iter)
+{
+ struct ht_entry *hent;
+ struct ht_table *ht;
+
+ ASSERT(iter);
+
+ ht = iter->hash;
+ hent = (struct ht_entry *) iter->curr;
+ hent = hent->next;
+ while (!hent &&
+ ++iter->index < HASH_TABLE_SIZE) {
+ hent = ht->table[iter->index];
+ }
+ iter->curr = hent;
+
+ return (hent ? 0 : -1);
+}
+
+
+static int
+read_c_escchar (char *r, const char **pp, const char *endptr)
+{
+ int c = 0, l = 1;
+ const char *p = *pp;
+
+ switch (p[0]) {
+ case 'a' : c = '\a'; p++; break;
+ case 'b' : c = '\b'; p++; break;
+ case 'f' : c = '\f'; p++; break;
+ case 'n' : c = '\n'; p++; break;
+ case 'r' : c = '\r'; p++; break;
+ case 't' : c = '\t'; p++; break;
+ case 'v' : c = '\v'; p++; break;
+ case '\\': case '?': case '\'': case '\"':
+ c = p[0]; p++;
+ break;
+ case '\n': l = 0; p++; break;
+ case '\r':
+ {
+ p++;
+ if (p < endptr && p[0] == '\n')
+ p++;
+ l = 0;
+ }
+ break;
+ case '0': case '1': case '2': case '3':
+ case '4': case '5': case '6': case '7':
+ {
+ int i;
+ for (c = 0, i = 0;
+ i < 3 && p < endptr &&
+ p[0] >= '0' && p[0] <= '7'; i++, p++)
+ c = (c << 3) + (p[0] - '0');
+ }
+ break;
+ case 'x':
+ {
+ int i;
+ for (c = 0, i = 0, p++;
+ i < 2 && p < endptr && isxdigit(p[0]);
+ i++, p++)
+ c = (c << 4) +
+ (isdigit(p[0]) ?
+ p[0] - '0' :
+ (islower(p[0]) ? p[0] - 'a' + 10: p[0] - 'A' + 10));
+ }
+ break;
+ default:
+ WARN("Unknown escape char sequence: \\%c", p[0]);
+ l = 0; p++;
+ break;
+ }
+
+ if (r)
+ *r = (char) c;
+ *pp = p;
+ return l;
+}
+
+#define C_QUOTE '"'
+#define C_ESCAPE '\\'
+static int
+read_c_litstrc (char *q, int len, const char **pp, const char *endptr)
+{
+ const char *p;
+ int l = 0;
+#define Q_TERM 0
+#define Q_CONT -1
+#define Q_ERROR_UNTERM -1
+#define Q_ERROR_INVAL -2
+#define Q_ERROR_BUFF -3
+ int s = Q_CONT;
+
+ for (l = 0, p = *pp;
+ s == Q_CONT && p < endptr; ) {
+ switch (p[0]) {
+ case C_QUOTE:
+ s = Q_TERM; p++;
+ break;
+ case C_ESCAPE:
+ if (q && l == len)
+ s = Q_ERROR_BUFF;
+ else {
+ p++;
+ l += read_c_escchar(q ? &q[l] : NULL, &p, endptr);
+ }
+ break;
+ case '\n': case '\r':
+ s = Q_ERROR_INVAL;
+ break;
+ default:
+ if (q && l == len)
+ s = Q_ERROR_BUFF;
+ else {
+ if (!q)
+ l++;
+ else
+ q[l++] = p[0];
+ p++;
+ }
+ break;
+ }
+ }
+ if (s == Q_TERM) {
+ if (q && l == len)
+ s = Q_ERROR_BUFF;
+ else if (q)
+ q[l++] = '\0';
+ }
+
+ *pp = p;
+ return ((s == Q_TERM) ? l : s);
+}
+
+char *
+parse_c_string (const char **pp, const char *endptr)
+{
+ char *q = NULL;
+ const char *p = *pp;
+ int l = 0;
+
+ if (p >= endptr || p[0] != C_QUOTE)
+ return NULL;
+
+ p++;
+ l = read_c_litstrc(NULL, 0, &p, endptr);
+ if (l >= 0) {
+ q = NEW(l + 1, char);
+ p = *pp + 1;
+ l = read_c_litstrc(q, l + 1, &p, endptr);
+ }
+
+ *pp = p;
+ return q;
+}
+
+#define ISCNONDIGITS(c) ( \
+ (c) == '_' || \
+ ((c) >= 'a' && (c) <= 'z') || \
+ ((c) >= 'A' && (c) <= 'Z') \
+)
+#define ISCIDENTCHAR(c) ( \
+ ISCNONDIGITS((c)) || \
+ ((c) >= '0' && (c) <= '9') \
+)
+
+char *
+parse_c_ident (const char **pp, const char *endptr)
+{
+ char *q = NULL;
+ const char *p = *pp;
+ int n;
+
+ if (p >= endptr || !ISCNONDIGITS(*p))
+ return NULL;
+
+ for (n = 0; p < endptr && ISCIDENTCHAR(*p); p++, n++);
+ q = NEW(n + 1, char);
+ memcpy(q, *pp, n); q[n] = '\0';
+
+ *pp = p;
+ return q;
+}
+
+char *
+parse_float_decimal (const char **pp, const char *endptr)
+{
+ char *q = NULL;
+ const char *p = *pp;
+ int s = 0, n = 0;
+
+ if (p >= endptr)
+ return NULL;
+
+ if (p[0] == '+' || p[0] == '-')
+ p++;
+
+ /* 1. .01 001 001E-001 */
+ for (s = 0, n = 0; p < endptr && s >= 0; ) {
+ switch (p[0]) {
+ case '+': case '-':
+ if (s != 2)
+ s = -1;
+ else {
+ s = 3; p++;
+ }
+ break;
+ case '.':
+ if (s > 0)
+ s = -1;
+ else {
+ s = 1; p++;
+ }
+ break;
+ case '0': case '1': case '2': case '3': case '4':
+ case '5': case '6': case '7': case '8': case '9':
+ n++; p++;
+ break;
+ case 'E': case 'e':
+ if (n == 0 || s == 2)
+ s = -1;
+ else {
+ s = 2; p++;
+ }
+ break;
+ default:
+ s = -1;
+ break;
+ }
+ }
+
+ if (n != 0) {
+ n = (int) (p - *pp);
+ q = NEW(n + 1, char);
+ memcpy(q, *pp, n); q[n] = '\0';
+ }
+
+ *pp = p;
+ return q;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/dpxutil.h b/Build/source/texk/dvipdf-x/xsrc/dpxutil.h
new file mode 100644
index 00000000000..f902bb1f2aa
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/dpxutil.h
@@ -0,0 +1,105 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _DPXUTIL_H_
+#define _DPXUTIL_H_
+
+#undef MIN
+#define MIN(a, b) (((a) < (b)) ? (a) : (b))
+#undef MAX
+#define MAX(a, b) (((a) > (b)) ? (a) : (b))
+#undef ABS
+#define ABS(a) (((a) < 0) ? -(a) : (a))
+
+#ifndef is_space
+#define is_space(c) ((c) == ' ' || (c) == '\t' || (c) == '\f' || \
+ (c) == '\r' || (c) == '\n' || (c) == '\0')
+#endif
+#ifndef is_delim
+#define is_delim(c) ((c) == '(' || (c) == '/' || \
+ (c) == '<' || (c) == '>' || \
+ (c) == '[' || (c) == ']' || \
+ (c) == '{' || (c) == '}' || \
+ (c) == '%')
+#endif
+
+extern void skip_white_spaces (unsigned char **s, unsigned char *endptr);
+extern int xtoi (char c);
+extern int getxpair (unsigned char **str);
+extern int putxpair (unsigned char c, char **str);
+extern int sputx (unsigned char c, char **buf, char *endptr);
+
+extern unsigned char ostrtouc (unsigned char **inbuf,
+ unsigned char *inbufend, unsigned char *valid);
+extern unsigned char esctouc (unsigned char **inbuf,
+ unsigned char *inbufend, unsigned char *valid);
+
+#define HASH_TABLE_SIZE 503
+
+struct ht_entry {
+ char *key;
+ int keylen;
+
+ void *value;
+
+ struct ht_entry *next;
+};
+
+typedef void (*hval_free_func) (void *);
+
+struct ht_table {
+ long count;
+ hval_free_func hval_free_fn;
+ struct ht_entry *table[HASH_TABLE_SIZE];
+};
+
+extern void ht_init_table (struct ht_table *ht,
+ hval_free_func hval_free_fn);
+extern void ht_clear_table (struct ht_table *ht);
+extern void *ht_lookup_table (struct ht_table *ht,
+ const void *key, int keylen);
+extern void ht_append_table (struct ht_table *ht,
+ const void *key, int keylen, void *value) ;
+extern int ht_remove_table (struct ht_table *ht,
+ const void *key, int keylen);
+extern void ht_insert_table (struct ht_table *ht,
+ const void *key, int keylen, void *value);
+
+struct ht_iter {
+ int index;
+ void *curr;
+ struct ht_table *hash;
+};
+
+extern int ht_set_iter (struct ht_table *ht, struct ht_iter *iter);
+extern void ht_clear_iter (struct ht_iter *iter);
+extern char *ht_iter_getkey (struct ht_iter *iter, int *keylen);
+extern void *ht_iter_getval (struct ht_iter *iter);
+extern int ht_iter_next (struct ht_iter *iter);
+
+extern char *parse_float_decimal (const char **pp, const char *endptr);
+extern char *parse_c_string (const char **pp, const char *endptr);
+extern char *parse_c_ident (const char **pp, const char *endptr);
+
+#endif /* _DPXUTIL_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/dvi.c b/Build/source/texk/dvipdf-x/xsrc/dvi.c
new file mode 100644
index 00000000000..5bb8d9aad5e
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/dvi.c
@@ -0,0 +1,2737 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <sys/types.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <ctype.h>
+
+#ifdef WIN32
+#include <fcntl.h>
+#include <io.h>
+#endif
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+#include "mfileio.h"
+#include "numbers.h"
+
+#include "pdfdev.h"
+#include "pdfdoc.h"
+#include "pdfparse.h"
+#include "pdfencrypt.h"
+
+#include "fontmap.h"
+
+#include "dvicodes.h"
+#include "tfm.h"
+#include "vf.h"
+#include "subfont.h"
+
+#include "spc_util.h"
+#include "specials.h"
+
+#include "dvi.h"
+
+#ifdef XETEX
+#include "pdfximage.h"
+#include FT_ADVANCES_H
+#endif
+
+#define DVI_STACK_DEPTH_MAX 256u
+#define TEX_FONTS_ALLOC_SIZE 16u
+#define VF_NESTING_MAX 16u
+
+/* Interal Variables */
+static FILE *dvi_file = NULL;
+static char linear = 0; /* set to 1 for strict linear processing of the input */
+
+static unsigned long *page_loc = NULL;
+static unsigned long num_pages = 0;
+
+static unsigned long dvi_file_size = 0;
+
+static struct dvi_header
+{
+ UNSIGNED_QUAD unit_num;
+ UNSIGNED_QUAD unit_den;
+ UNSIGNED_QUAD mag;
+ UNSIGNED_QUAD media_width, media_height;
+ UNSIGNED_PAIR stackdepth;
+ char comment[257];
+} dvi_info = {
+ 25400000 , /* num */
+ 473628672, /* den */
+ 1000, /* mag */
+ 0, 0, /* media width and height */
+ 0, /* stackdepth */
+ {'\0'} /* comment */
+};
+
+static double dev_origin_x = 72.0, dev_origin_y = 770.0;
+
+double get_origin (int x)
+{
+ return x ? dev_origin_x : dev_origin_y;
+}
+
+#define PHYSICAL 1
+#define VIRTUAL 2
+#define SUBFONT 3
+#ifdef XETEX
+#define NATIVE 4
+#endif
+#define DVI 1
+#define VF 2
+
+static struct loaded_font
+{
+ int type; /* Type is physical or virtual */
+ int font_id; /* id returned by dev (for PHYSICAL fonts)
+ * or by vf module for (VIRTUAL fonts)
+ */
+ int subfont_id; /* id returned by subfont_locate_font() */
+ int tfm_id;
+ spt_t size;
+ int source; /* Source is either DVI or VF */
+#ifdef XETEX
+ unsigned long rgba_color;
+ FT_Face ft_face;
+ int layout_dir;
+ float extend;
+ float slant;
+ float embolden;
+#endif
+} *loaded_fonts = NULL;
+static int num_loaded_fonts = 0, max_loaded_fonts = 0;
+
+static void
+need_more_fonts (unsigned n)
+{
+ if (num_loaded_fonts + n > max_loaded_fonts) {
+ max_loaded_fonts += TEX_FONTS_ALLOC_SIZE;
+ loaded_fonts = RENEW (loaded_fonts, max_loaded_fonts, struct loaded_font);
+ }
+}
+
+static struct font_def
+{
+ long tex_id;
+ spt_t point_size;
+ spt_t design_size;
+ char *font_name;
+ int font_id; /* index of _loaded_ font in loaded_fonts array */
+ int used;
+#ifdef XETEX
+ int native; /* boolean */
+ unsigned long rgba_color; /* only used for native fonts in XeTeX */
+ int layout_dir; /* 1 = vertical, 0 = horizontal */
+ int extend;
+ int slant;
+ int embolden;
+#endif
+} *def_fonts = NULL;
+
+#ifdef XETEX
+#define XDV_FLAG_VERTICAL 0x0100
+#define XDV_FLAG_COLORED 0x0200
+#define XDV_FLAG_FEATURES 0x0400
+#define XDV_FLAG_VARIATIONS 0x0800
+#define XDV_FLAG_EXTEND 0x1000
+#define XDV_FLAG_SLANT 0x2000
+#define XDV_FLAG_EMBOLDEN 0x4000
+#endif
+
+static int num_def_fonts = 0, max_def_fonts = 0;
+static int compute_boxes = 0, link_annot = 1;
+static int verbose = 0;
+
+#define DVI_PAGE_BUF_CHUNK 0x10000UL /* 64K should be plenty for most pages */
+
+static unsigned char* dvi_page_buffer;
+static unsigned long dvi_page_buf_size;
+static unsigned long dvi_page_buf_index;
+
+/* functions to read numbers from the dvi file and store them in dvi_page_buffer */
+static UNSIGNED_BYTE get_and_buffer_unsigned_byte (FILE *file)
+{
+ int ch;
+ if ((ch = fgetc (file)) < 0)
+ ERROR ("File ended prematurely\n");
+ if (dvi_page_buf_index >= dvi_page_buf_size) {
+ dvi_page_buf_size += DVI_PAGE_BUF_CHUNK;
+ dvi_page_buffer = RENEW(dvi_page_buffer, dvi_page_buf_size, unsigned char);
+ }
+ dvi_page_buffer[dvi_page_buf_index++] = ch;
+ return (UNSIGNED_BYTE) ch;
+}
+
+#if 0
+/* Not used */
+static SIGNED_BYTE get_and_buffer_signed_byte (FILE *file)
+{
+ int byte;
+ byte = get_and_buffer_unsigned_byte(file);
+ if (byte >= 0x80)
+ byte -= 0x100;
+ return (SIGNED_BYTE) byte;
+}
+#endif
+
+static UNSIGNED_PAIR get_and_buffer_unsigned_pair (FILE *file)
+{
+ int i;
+ UNSIGNED_BYTE byte;
+ UNSIGNED_PAIR pair = 0;
+ for (i=0; i<2; i++) {
+ byte = get_and_buffer_unsigned_byte(file);
+ pair = pair*0x100u + byte;
+ }
+ return pair;
+}
+
+static SIGNED_PAIR get_and_buffer_signed_pair (FILE *file)
+{
+ int i;
+ long pair = 0;
+ for (i=0; i<2; i++) {
+ pair = pair*0x100 + get_and_buffer_unsigned_byte(file);
+ }
+ if (pair >= 0x8000) {
+ pair -= 0x10000l;
+ }
+ return (SIGNED_PAIR) pair;
+}
+
+static UNSIGNED_TRIPLE get_and_buffer_unsigned_triple(FILE *file)
+{
+ int i;
+ long triple = 0;
+ for (i=0; i<3; i++) {
+ triple = triple*0x100u + get_and_buffer_unsigned_byte(file);
+ }
+ return (UNSIGNED_TRIPLE) triple;
+}
+
+static SIGNED_TRIPLE get_and_buffer_signed_triple(FILE *file)
+{
+ int i;
+ long triple = 0;
+ for (i=0; i<3; i++) {
+ triple = triple*0x100 + get_and_buffer_unsigned_byte(file);
+ }
+ if (triple >= 0x800000l)
+ triple -= 0x1000000l;
+ return (SIGNED_TRIPLE) triple;
+}
+
+static SIGNED_QUAD get_and_buffer_signed_quad(FILE *file)
+{
+ int byte, i;
+ long quad = 0;
+
+ /* Check sign on first byte before reading others */
+ byte = get_and_buffer_unsigned_byte(file);
+ quad = byte;
+ if (quad >= 0x80)
+ quad = byte - 0x100;
+ for (i=0; i<3; i++) {
+ quad = quad*0x100 + get_and_buffer_unsigned_byte(file);
+ }
+ return (SIGNED_QUAD) quad;
+}
+
+static UNSIGNED_QUAD get_and_buffer_unsigned_quad(FILE *file)
+{
+ int i;
+ unsigned long quad = 0;
+ for (i=0; i<4; i++) {
+ quad = quad*0x100u + get_and_buffer_unsigned_byte(file);
+ }
+ return (UNSIGNED_QUAD) quad;
+}
+
+static void get_and_buffer_bytes(FILE *file, unsigned int count)
+{
+ if (dvi_page_buf_index + count >= dvi_page_buf_size) {
+ dvi_page_buf_size = dvi_page_buf_index + count + DVI_PAGE_BUF_CHUNK;
+ dvi_page_buffer = RENEW(dvi_page_buffer, dvi_page_buf_size, unsigned char);
+ }
+ if (fread(dvi_page_buffer + dvi_page_buf_index, 1, count, file) != count)
+ ERROR ("File ended prematurely\n");
+ dvi_page_buf_index += count;
+}
+
+/* functions to fetch values from dvi_page_buffer */
+
+static UNSIGNED_BYTE get_buffered_unsigned_byte (void)
+{
+ return dvi_page_buffer[dvi_page_buf_index++];
+}
+
+static SIGNED_BYTE get_buffered_signed_byte (void)
+{
+ int byte;
+ byte = dvi_page_buffer[dvi_page_buf_index++];
+ if (byte >= 0x80)
+ byte -= 0x100;
+ return (SIGNED_BYTE) byte;
+}
+
+static UNSIGNED_PAIR get_buffered_unsigned_pair (void)
+{
+ int i;
+ UNSIGNED_BYTE byte;
+ UNSIGNED_PAIR pair = 0;
+ for (i=0; i<2; i++) {
+ byte = dvi_page_buffer[dvi_page_buf_index++];
+ pair = pair*0x100u + byte;
+ }
+ return pair;
+}
+
+static SIGNED_PAIR get_buffered_signed_pair (void)
+{
+ int i;
+ long pair = 0;
+ for (i=0; i<2; i++) {
+ pair = pair*0x100 + dvi_page_buffer[dvi_page_buf_index++];
+ }
+ if (pair >= 0x8000) {
+ pair -= 0x10000l;
+ }
+ return (SIGNED_PAIR) pair;
+}
+
+static UNSIGNED_TRIPLE get_buffered_unsigned_triple(void)
+{
+ int i;
+ long triple = 0;
+ for (i=0; i<3; i++) {
+ triple = triple*0x100u + dvi_page_buffer[dvi_page_buf_index++];
+ }
+ return (UNSIGNED_TRIPLE) triple;
+}
+
+static SIGNED_TRIPLE get_buffered_signed_triple(void)
+{
+ int i;
+ long triple = 0;
+ for (i=0; i<3; i++) {
+ triple = triple*0x100 + dvi_page_buffer[dvi_page_buf_index++];
+ }
+ if (triple >= 0x800000l)
+ triple -= 0x1000000l;
+ return (SIGNED_TRIPLE) triple;
+}
+
+static SIGNED_QUAD get_buffered_signed_quad(void)
+{
+ int byte, i;
+ long quad = 0;
+
+ /* Check sign on first byte before reading others */
+ byte = dvi_page_buffer[dvi_page_buf_index++];
+ quad = byte;
+ if (quad >= 0x80)
+ quad = byte - 0x100;
+ for (i=0; i<3; i++) {
+ quad = quad*0x100 + dvi_page_buffer[dvi_page_buf_index++];
+ }
+ return (SIGNED_QUAD) quad;
+}
+
+static UNSIGNED_QUAD get_buffered_unsigned_quad(void)
+{
+ int i;
+ unsigned long quad = 0;
+ for (i=0; i<4; i++) {
+ quad = quad*0x100u + dvi_page_buffer[dvi_page_buf_index++];
+ }
+ return (UNSIGNED_QUAD) quad;
+}
+
+
+
+void
+dvi_set_verbose (void)
+{
+ verbose++;
+ subfont_set_verbose();
+ tfm_set_verbose();
+ vf_set_verbose ();
+ spc_set_verbose();
+}
+
+unsigned
+dvi_npages (void)
+{
+ return num_pages;
+}
+
+static const char invalid_signature[] =
+"Something is wrong. Are you sure this is a DVI file?";
+
+#define range_check_loc(loc) \
+ if ((loc) > dvi_file_size) {\
+ ERROR(invalid_signature); \
+ }
+
+static long
+find_post (void)
+{
+ long current;
+ int ch;
+
+ /* First find end of file */
+ dvi_file_size = file_size(dvi_file);
+ current = dvi_file_size;
+
+ /* Scan backwards through PADDING */
+ do {
+ current--;
+ seek_absolute(dvi_file, current);
+ } while ((ch = fgetc(dvi_file)) == PADDING &&
+ current > 0);
+
+ /* file_position now points to last non padding character or
+ * beginning of file */
+ if (dvi_file_size - current < 4 || current == 0 ||
+#ifdef XETEX
+ !(ch == DVI_ID || ch == DVIV_ID || ch == XDVI_ID)) {
+#else
+ !(ch == DVI_ID || ch == DVIV_ID)) {
+#endif
+ MESG("DVI ID = %d\n", ch);
+ ERROR(invalid_signature);
+ }
+
+ /* Make sure post_post is really there */
+ current = current - 5;
+ seek_absolute(dvi_file, current);
+ if ((ch = fgetc(dvi_file)) != POST_POST) {
+ MESG("Found %d where post_post opcode should be\n", ch);
+ ERROR(invalid_signature);
+ }
+ current = get_signed_quad(dvi_file);
+ seek_absolute(dvi_file, current);
+ if ((ch = fgetc(dvi_file)) != POST) {
+ MESG("Found %d where post_post opcode should be\n", ch);
+ ERROR(invalid_signature);
+ }
+
+ return current;
+}
+
+static void
+get_page_info (long post_location)
+{
+ int i;
+
+ seek_absolute(dvi_file, post_location + 27);
+ num_pages = get_unsigned_pair(dvi_file);
+ if (num_pages == 0) {
+ ERROR("Page count is 0!");
+ }
+ if (verbose > 2) {
+ MESG("Page count:\t %4d\n", num_pages);
+ }
+
+ page_loc = NEW(num_pages, unsigned long);
+
+ seek_absolute(dvi_file, post_location + 1);
+ page_loc[num_pages-1] = get_unsigned_quad(dvi_file);
+ range_check_loc(page_loc[num_pages-1] + 41);
+ for (i = num_pages - 2; i >= 0; i--) {
+ seek_absolute(dvi_file, page_loc[i+1] + 41);
+ page_loc[i] = get_unsigned_quad(dvi_file);
+ range_check_loc(page_loc[num_pages-1] + 41);
+ }
+}
+
+/* Following are computed "constants" used for unit conversion */
+static double dvi2pts = 1.52018, total_mag = 1.0;
+
+double
+dvi_tell_mag (void)
+{
+ return total_mag;
+}
+
+static void
+do_scales (double mag)
+{
+ total_mag = (double) dvi_info.mag / 1000.0 * mag;
+ dvi2pts = (double) dvi_info.unit_num / (double) dvi_info.unit_den;
+ dvi2pts *= (72.0 / 254000.0);
+}
+
+static void
+get_dvi_info (long post_location)
+{
+ seek_absolute(dvi_file, post_location + 5);
+
+ dvi_info.unit_num = get_unsigned_quad(dvi_file);
+ dvi_info.unit_den = get_unsigned_quad(dvi_file);
+ dvi_info.mag = get_unsigned_quad(dvi_file);
+
+ dvi_info.media_height = get_unsigned_quad(dvi_file);
+ dvi_info.media_width = get_unsigned_quad(dvi_file);
+
+ dvi_info.stackdepth = get_unsigned_pair(dvi_file);
+
+ if (dvi_info.stackdepth > DVI_STACK_DEPTH_MAX) {
+ WARN("DVI need stack depth of %d,", dvi_info.stackdepth);
+ WARN("but DVI_STACK_DEPTH_MAX is %d.", DVI_STACK_DEPTH_MAX);
+ ERROR("Capacity exceeded.");
+ }
+
+ if (verbose > 2) {
+ MESG("DVI File Info\n");
+ MESG("Unit: %ld / %ld\n", dvi_info.unit_num, dvi_info.unit_den);
+ MESG("Magnification: %ld\n", dvi_info.mag);
+ MESG("Media Height: %ld\n", dvi_info.media_height);
+ MESG("Media Width: %ld\n", dvi_info.media_width);
+ MESG("Stack Depth: %d\n", dvi_info.stackdepth);
+ }
+}
+
+static void
+get_preamble_dvi_info (void)
+{
+ UNSIGNED_BYTE ch;
+
+ ch = get_unsigned_byte(dvi_file);
+ if (ch != PRE) {
+ MESG("Found %d where PRE was expected\n", ch);
+ ERROR(invalid_signature);
+ }
+
+ ch = get_unsigned_byte(dvi_file);
+#ifdef XETEX
+ if (!(ch == DVI_ID || ch == DVIV_ID || ch == XDVI_ID)) {
+#else
+ if (!(ch == DVI_ID || ch == DVIV_ID)) {
+#endif
+ MESG("DVI ID = %d\n", ch);
+ ERROR(invalid_signature);
+ }
+
+ dvi_info.unit_num = get_unsigned_quad(dvi_file);
+ dvi_info.unit_den = get_unsigned_quad(dvi_file);
+ dvi_info.mag = get_unsigned_quad(dvi_file);
+
+ ch = get_unsigned_byte(dvi_file);
+ if (fread(dvi_info.comment,
+ 1, ch, dvi_file) != ch) {
+ ERROR(invalid_signature);
+ }
+ dvi_info.comment[ch] = '\0';
+
+ if (verbose > 2) {
+ MESG("DVI File Info\n");
+ MESG("Unit: %ld / %ld\n", dvi_info.unit_num, dvi_info.unit_den);
+ MESG("Magnification: %ld\n", dvi_info.mag);
+ }
+
+ if (verbose) {
+ MESG("DVI Comment: %s\n", dvi_info.comment);
+ }
+
+ num_pages = 0x7FFFFFFUL; /* for linear processing: we just keep going! */
+}
+
+const char *
+dvi_comment (void)
+{
+ return dvi_info.comment;
+}
+
+static void
+read_font_record (SIGNED_QUAD tex_id)
+{
+ UNSIGNED_BYTE dir_length, name_length;
+ UNSIGNED_QUAD point_size, design_size;
+ char *directory, *font_name;
+
+ if (num_def_fonts >= max_def_fonts) {
+ max_def_fonts += TEX_FONTS_ALLOC_SIZE;
+ def_fonts = RENEW (def_fonts, max_def_fonts, struct font_def);
+ }
+ get_unsigned_quad(dvi_file);
+ point_size = get_unsigned_quad(dvi_file);
+ design_size = get_unsigned_quad(dvi_file);
+ dir_length = get_unsigned_byte(dvi_file);
+ name_length = get_unsigned_byte(dvi_file);
+
+ directory = NEW(dir_length + 1, char);
+ if (fread(directory, 1, dir_length, dvi_file) != dir_length) {
+ ERROR(invalid_signature);
+ }
+ directory[dir_length] = '\0';
+ RELEASE(directory); /* unused */
+
+ font_name = NEW(name_length + 1, char);
+ if (fread(font_name, 1, name_length, dvi_file) != name_length) {
+ ERROR(invalid_signature);
+ }
+ font_name[name_length] = '\0';
+ def_fonts[num_def_fonts].tex_id = tex_id;
+ def_fonts[num_def_fonts].font_name = font_name;
+ def_fonts[num_def_fonts].point_size = point_size;
+ def_fonts[num_def_fonts].design_size = design_size;
+ def_fonts[num_def_fonts].used = 0;
+#ifdef XETEX
+ def_fonts[num_def_fonts].native = 0;
+ def_fonts[num_def_fonts].rgba_color = 0xffffffff;
+ def_fonts[num_def_fonts].layout_dir = 0;
+ def_fonts[num_def_fonts].extend = 0x00010000; /* 1.0 */
+ def_fonts[num_def_fonts].slant = 0;
+ def_fonts[num_def_fonts].embolden = 0;
+#endif
+ num_def_fonts++;
+
+ return;
+}
+
+#ifdef XETEX
+static void
+read_native_font_record (SIGNED_QUAD tex_id)
+{
+ UNSIGNED_PAIR flags;
+ UNSIGNED_QUAD point_size;
+ char *font_name;
+ int plen, flen, slen, i;
+
+ if (num_def_fonts >= max_def_fonts) {
+ max_def_fonts += TEX_FONTS_ALLOC_SIZE;
+ def_fonts = RENEW (def_fonts, max_def_fonts, struct font_def);
+ }
+ point_size = get_unsigned_quad(dvi_file);
+ flags = get_unsigned_pair(dvi_file);
+
+ plen = (int) get_unsigned_byte(dvi_file); /* PS name length */
+ flen = (int) get_unsigned_byte(dvi_file); /* family name length */
+ slen = (int) get_unsigned_byte(dvi_file); /* style name length */
+ font_name = NEW(plen + 1, char);
+ if (fread(font_name, 1, plen, dvi_file) != plen) {
+ ERROR(invalid_signature);
+ }
+ font_name[plen] = '\0';
+
+ /* ignore family and style names */
+ for (i = 0; i < flen + slen; ++i)
+ get_unsigned_byte(dvi_file);
+
+ def_fonts[num_def_fonts].tex_id = tex_id;
+ def_fonts[num_def_fonts].font_name = font_name;
+ def_fonts[num_def_fonts].point_size = point_size;
+ def_fonts[num_def_fonts].design_size = 655360; /* hard-code as 10pt for now, not used anyway */
+ def_fonts[num_def_fonts].used = 0;
+ def_fonts[num_def_fonts].native = 1;
+
+ def_fonts[num_def_fonts].layout_dir = 0;
+ def_fonts[num_def_fonts].rgba_color = 0xffffffff;
+ def_fonts[num_def_fonts].extend = 0x00010000;
+ def_fonts[num_def_fonts].slant = 0;
+ def_fonts[num_def_fonts].embolden = 0;
+
+ if (flags & XDV_FLAG_VERTICAL)
+ def_fonts[num_def_fonts].layout_dir = 1;
+
+ if (flags & XDV_FLAG_COLORED)
+ def_fonts[num_def_fonts].rgba_color = get_unsigned_quad(dvi_file);
+
+ if (flags & XDV_FLAG_EXTEND)
+ def_fonts[num_def_fonts].extend = get_signed_quad(dvi_file);
+
+ if (flags & XDV_FLAG_SLANT)
+ def_fonts[num_def_fonts].slant = get_signed_quad(dvi_file);
+
+ if (flags & XDV_FLAG_EMBOLDEN)
+ def_fonts[num_def_fonts].embolden = get_signed_quad(dvi_file);
+
+ if (flags & XDV_FLAG_VARIATIONS) {
+ int v, nvars = get_unsigned_pair(dvi_file);
+ for (v = 0; v < nvars * 2; ++v)
+ (void)get_unsigned_quad(dvi_file); /* skip axis and value for each variation setting */
+ WARN("Variation axes are not supported; ignoring variation settings for font %s.\n", font_name);
+ }
+
+ num_def_fonts++;
+
+ return;
+}
+#endif
+
+static void
+get_dvi_fonts (long post_location)
+{
+ UNSIGNED_BYTE code;
+ SIGNED_QUAD tex_id = 0;
+
+ seek_absolute(dvi_file, post_location + 29);
+ while ((code = get_unsigned_byte(dvi_file)) != POST_POST) {
+ switch (code) {
+ case FNT_DEF1:
+ tex_id = get_unsigned_byte(dvi_file);
+ break;
+ case FNT_DEF2:
+ tex_id = get_unsigned_pair(dvi_file);
+ break;
+ case FNT_DEF3:
+ tex_id = get_unsigned_triple(dvi_file);
+ break;
+ case FNT_DEF4:
+#ifdef XETEX
+ case XDV_NATIVE_FONT_DEF:
+#endif
+ tex_id = get_signed_quad(dvi_file);
+ break;
+ default:
+ MESG("Unexpected op code: %3d\n", code);
+ ERROR(invalid_signature);
+ }
+#ifdef XETEX
+ if (code != XDV_NATIVE_FONT_DEF) {
+ read_font_record(tex_id);
+ } else {
+ read_native_font_record(tex_id);
+ }
+#else
+ read_font_record(tex_id);
+#endif
+ }
+ if (verbose > 2) {
+ unsigned i;
+
+ MESG("\n");
+ MESG("DVI file font info\n");
+ for (i = 0; i < num_def_fonts; i++) {
+ MESG("TeX Font: %10s loaded at ID=%5ld, ",
+ def_fonts[i].font_name, def_fonts[i].tex_id);
+ MESG("size=%5.2fpt (scaled %4.1f%%)",
+ def_fonts[i].point_size * dvi2pts,
+ 100.0 * ((double) def_fonts[i].point_size / def_fonts[i].design_size));
+ MESG("\n");
+ }
+ }
+}
+
+static void get_comment (void)
+{
+ UNSIGNED_BYTE length;
+
+ seek_absolute(dvi_file, 14);
+ length = get_unsigned_byte(dvi_file);
+ if (fread(dvi_info.comment,
+ 1, length, dvi_file) != length) {
+ ERROR(invalid_signature);
+ }
+ dvi_info.comment[length] = '\0';
+ if (verbose) {
+ MESG("DVI Comment: %s\n", dvi_info.comment);
+ }
+}
+
+/*
+ * The section below this line deals with the actual processing of the
+ * dvi file.
+ *
+ * The dvi file processor state is contained in the following variables:
+ */
+
+struct dvi_registers
+{
+ SIGNED_QUAD h, v, w, x, y, z, d;
+};
+
+static struct dvi_registers dvi_state;
+static struct dvi_registers dvi_stack[DVI_STACK_DEPTH_MAX];
+static unsigned dvi_stack_depth = 0 ;
+static int current_font = -1;
+static int processing_page = 0 ;
+
+static void
+clear_state (void)
+{
+ dvi_state.h = 0; dvi_state.v = 0; dvi_state.w = 0;
+ dvi_state.x = 0; dvi_state.y = 0; dvi_state.z = 0;
+ dvi_state.d = 0; /* direction */
+ dvi_stack_depth = 0;
+ current_font = -1;
+}
+
+/* Migrated from pdfdev.c:
+ * The following codes are originally put into pdfdev.c.
+ * But they are moved to here to make PDF output independent
+ * from DVI input.
+ * pdfdoc, pdfspecial and htex are also modified. pdfspecial
+ * and htex does tag/untag depth. pdfdev and pdfdoc now does
+ * not care about line-breaking at all.
+ */
+static unsigned marked_depth = 0;
+static int tagged_depth = -1;
+
+static void
+dvi_mark_depth (void)
+{
+ /* If decreasing below tagged_depth */
+ if (link_annot &&
+ marked_depth == tagged_depth &&
+ dvi_stack_depth == tagged_depth - 1) {
+ /*
+ * See if this appears to be the end of a "logical unit"
+ * that's been broken. If so, flush the logical unit.
+ */
+ pdf_doc_break_annot();
+ }
+ marked_depth = dvi_stack_depth;
+}
+
+/*
+ * The following routines setup and tear down a callback at a
+ * certain stack depth. This is used to handle broken (linewise)
+ * links.
+ */
+void
+dvi_tag_depth (void)
+{
+ tagged_depth = marked_depth;
+ dvi_compute_boxes(1);
+}
+
+void
+dvi_untag_depth (void)
+{
+ tagged_depth = -1;
+ dvi_compute_boxes(0);
+}
+
+void
+dvi_compute_boxes (int flag)
+{
+ compute_boxes = flag;
+}
+
+void
+dvi_link_annot (int flag)
+{
+ link_annot = flag;
+}
+
+int
+dvi_is_tracking_boxes(void)
+{
+ return (compute_boxes && link_annot && marked_depth >= tagged_depth);
+}
+
+void
+dvi_do_special (const void *buffer, UNSIGNED_QUAD size)
+{
+ double x_user, y_user, mag;
+ const char *p;
+
+ if (size > 0x7fffffffUL) {
+ WARN("Special more than %ul bytes???", size);
+ return;
+ }
+
+ graphics_mode();
+
+ p = (const char *) buffer;
+
+ x_user = dvi_state.h * dvi2pts;
+ y_user = -dvi_state.v * dvi2pts;
+ mag = dvi_tell_mag();
+
+ if (spc_exec_special(p, (long) size, x_user, y_user, mag) < 0) {
+ if (verbose) {
+ dump(p, p + size);
+ }
+ }
+
+ return;
+}
+
+double
+dvi_unit_size (void)
+{
+ return dvi2pts;
+}
+
+
+int
+dvi_locate_font (const char *tfm_name, spt_t ptsize)
+{
+ int cur_id = -1;
+ const char *name = tfm_name;
+ int subfont_id = -1, font_id; /* VF or device font ID */
+ fontmap_rec *mrec;
+
+ if (verbose)
+ MESG("<%s@%.2fpt", tfm_name, ptsize * dvi2pts);
+
+ need_more_fonts(1);
+
+ /* This routine needs to be recursive/reentrant. Load current high water
+ * mark into an automatic variable.
+ */
+ cur_id = num_loaded_fonts++;
+
+ mrec = pdf_lookup_fontmap_record(tfm_name);
+ /* Load subfont mapping table */
+ if (mrec && mrec->charmap.sfd_name && mrec->charmap.subfont_id) {
+ subfont_id = sfd_load_record(mrec->charmap.sfd_name, mrec->charmap.subfont_id);
+ }
+
+ /* TFM must exist here. */
+ loaded_fonts[cur_id].tfm_id = tfm_open(tfm_name, 1);
+ loaded_fonts[cur_id].subfont_id = subfont_id;
+ loaded_fonts[cur_id].size = ptsize;
+ /* This will be reset later if it was really generated by the dvi file. */
+ loaded_fonts[cur_id].source = VF;
+
+ /* The order of searching fonts is as follows:
+ *
+ * 1. If mrec is null, that is, there is no map entry matching
+ * with tfm_name, then search a virtual font matching with
+ * tfm_name at first. If no virtual font is found, search a
+ * PK font matching with tfm_name.
+ *
+ * 2. If mrec is non-null, search a physical scalable font.
+ *
+ * 3. Notice that every subfont gets non-null mrec. In this case,
+ * enc_name corresponding to mrec will be used instead of mrec.
+ * That is enc_name is NULL, search a virtual font for Omega (.ovf)
+ * matching with the base name of the subfont. If no virtual font
+ * for Omega is found, it is a fatal error because there is no PK font
+ * for Omega.
+ */
+ if (!mrec) {
+ font_id = vf_locate_font(tfm_name, ptsize);
+ if (font_id >= 0) {
+ loaded_fonts[cur_id].type = VIRTUAL;
+ loaded_fonts[cur_id].font_id = font_id;
+ if (verbose)
+ MESG("(VF)>");
+ return cur_id;
+ }
+ }
+#if 1
+ /* Sorry, I don't understand this well... Please fix.
+ * The purpose of this seems to be:
+ *
+ * Map 8-bit char codes in subfont to 16-bit code with SFD mapping
+ * and map subfonts to single OVF font.
+ *
+ * But it apparently only does TFM -> OVF mapping but no character
+ * code mapping. Please see dvi_set(), you can't have both font->type
+ * VIRTUAL and font->subfont_id >= 0. Am I missing something?
+ */
+ else if (subfont_id >= 0 && mrec->map_name)
+ {
+ fontmap_rec *mrec1 = pdf_lookup_fontmap_record(mrec->map_name);
+ /* enc_name=NULL should be used only for 'built-in' encoding.
+ * Please fix this!
+ */
+ if (mrec1 && !mrec1->enc_name) {
+ font_id = vf_locate_font(mrec1->font_name, ptsize);
+ if (font_id < 0)
+ WARN("Could not locate Omega Virtual Font \"%s\" for \"%s\".",
+ mrec1->font_name, tfm_name);
+ else {
+ loaded_fonts[cur_id].type = VIRTUAL;
+ loaded_fonts[cur_id].font_id = font_id;
+ if (verbose)
+ MESG("(OVF)>");
+ return cur_id;
+ }
+ }
+ }
+#endif /* 1 */
+
+ /* Failed to load a virtual font so we try to load a physical font. */
+
+ /* If mrec->map_name is not NULL, font name identified in PDF output
+ * is different than tfm_name, this can happen for subfonts grouped
+ * into a single "intermediate" font foo@SFD@.
+ * This is necessary for optimal output; to avoid unnecessary creation
+ * of multiple instances of a same font, to avoid frequent font selection
+ * and break of string_mode.
+ */
+ if (mrec && mrec->map_name) {
+ name = mrec->map_name;
+ } else {
+ name = tfm_name;
+ }
+
+ /* We need ptsize for PK font creation. */
+ font_id = pdf_dev_locate_font(name, ptsize);
+ if (font_id < 0) {
+ WARN("Could not locate a virtual/physical font for TFM \"%s\".", tfm_name);
+ if (mrec && mrec->map_name) { /* has map_name */
+ fontmap_rec *mrec1 = pdf_lookup_fontmap_record(mrec->map_name);
+ WARN(">> This font is mapped to an intermediate 16-bit font \"%s\" with SFD charmap=<%s,%s>,",
+ mrec->map_name, mrec->charmap.sfd_name, mrec->charmap.subfont_id);
+ if (!mrec1)
+ WARN(">> but I couldn't find font mapping for \"%s\".", mrec->map_name);
+ else {
+ WARN(">> and then mapped to a physical font \"%s\" by fontmap.", mrec1->font_name);
+ WARN(">> Please check if kpathsea library can find this font: %s", mrec1->font_name);
+ }
+ } else if (mrec && !mrec->map_name) {
+ WARN(">> This font is mapped to a physical font \"%s\".", mrec->font_name);
+ WARN(">> Please check if kpathsea library can find this font: %s", mrec->font_name);
+ } else {
+ WARN(">> There are no valid font mapping entry for this font.");
+ WARN(">> Font file name \"%s\" was assumed but failed to locate that font.", tfm_name);
+ }
+ ERROR("Cannot proceed without .vf or \"physical\" font for PDF output...");
+ }
+ loaded_fonts[cur_id].type = PHYSICAL;
+ loaded_fonts[cur_id].font_id = font_id;
+
+ if (verbose)
+ MESG(">");
+
+ return cur_id;
+}
+
+#ifdef XETEX
+static int
+dvi_locate_native_font (const char *ps_name,
+ spt_t ptsize, int layout_dir, int extend, int slant, int embolden)
+{
+ int cur_id = -1;
+ fontmap_rec *mrec;
+ char *fontmap_key = malloc(strlen(ps_name) + 40); // CHECK this is enough
+
+ if (verbose)
+ MESG("<%s@%.2fpt", ps_name, ptsize * dvi2pts);
+
+ need_more_fonts(1);
+
+ cur_id = num_loaded_fonts++;
+
+ sprintf(fontmap_key, "%s/%c/%d/%d/%d", ps_name, layout_dir == 0 ? 'H' : 'V', extend, slant, embolden);
+ mrec = pdf_lookup_fontmap_record(fontmap_key);
+ if (mrec == NULL) {
+ if (pdf_load_native_font(ps_name, layout_dir, extend, slant, embolden) == -1) {
+ ERROR("Cannot proceed without the \"native\" font: %s", ps_name);
+ }
+ mrec = pdf_lookup_fontmap_record(fontmap_key);
+ /* FIXME: would be more efficient if pdf_load_native_font returned the mrec ptr (or NULL for error)
+ so we could avoid doing a second lookup for the item we just inserted */
+ }
+ loaded_fonts[cur_id].font_id = pdf_dev_locate_font(fontmap_key, ptsize);
+ loaded_fonts[cur_id].size = ptsize;
+ loaded_fonts[cur_id].type = NATIVE;
+ free(fontmap_key);
+
+ loaded_fonts[cur_id].ft_face = mrec->opt.ft_face;
+ loaded_fonts[cur_id].layout_dir = layout_dir;
+ loaded_fonts[cur_id].extend = mrec->opt.extend;
+ loaded_fonts[cur_id].slant = mrec->opt.slant;
+ loaded_fonts[cur_id].embolden = mrec->opt.bold;
+
+ if (verbose)
+ MESG(">");
+
+ return cur_id;
+}
+#endif
+
+double
+dvi_dev_xpos (void)
+{
+ return dvi_state.h * dvi2pts;
+}
+
+double
+dvi_dev_ypos (void)
+{
+ return -(dvi_state.v * dvi2pts);
+}
+
+static void do_moveto (SIGNED_QUAD x, SIGNED_QUAD y)
+{
+ dvi_state.h = x;
+ dvi_state.v = y;
+}
+
+void dvi_right (SIGNED_QUAD x)
+{
+ if (!dvi_state.d) {
+ dvi_state.h += x;
+ } else {
+ dvi_state.v += x;
+ }
+}
+
+void dvi_down (SIGNED_QUAD y)
+{
+ if (!dvi_state.d) {
+ dvi_state.v += y;
+ } else {
+ dvi_state.h -= y;
+ }
+}
+
+/* Please remove this.
+ * Optimization for 8-bit encodings.
+ */
+static void
+do_string (unsigned char *s, int len)
+{
+ struct loaded_font *font;
+ spt_t width, height, depth;
+ int i;
+
+ if (current_font < 0)
+ ERROR("No font selected!");
+
+ font = &loaded_fonts[current_font];
+
+ width = tfm_string_width(font->tfm_id, s, len);
+ width = sqxfw(font->size, width);
+
+ switch (font->type) {
+ case PHYSICAL:
+ if (font->subfont_id < 0) {
+ pdf_dev_set_string(dvi_state.h, -dvi_state.v, s, len,
+ width, font->font_id, 1);
+ if (compute_boxes && link_annot &&
+ marked_depth >= tagged_depth) {
+ pdf_rect rect;
+
+ height = tfm_string_height(font->tfm_id, s, len);
+ depth = tfm_string_depth (font->tfm_id, s, len);
+ height = sqxfw(font->size, height);
+ depth = sqxfw(font->size, depth);
+
+ pdf_dev_set_rect (&rect, dvi_state.h, -dvi_state.v,
+ width, height, depth);
+ pdf_doc_expand_box(&rect);
+ }
+ } else { /* Subfonts */
+ dvi_push();
+ for (i = 0; i < len; i++) {
+ dvi_set(s[i]);
+ }
+ dvi_pop();
+ }
+ break;
+ case VIRTUAL:
+ dvi_push();
+ for (i = 0; i < len; i++) {
+ dvi_set(s[i]);
+ }
+ dvi_pop();
+ }
+ if (!dvi_state.d) {
+ dvi_state.h += width;
+ } else {
+ dvi_state.v += width;
+ }
+}
+
+/* _FIXME_
+ * CMap decoder wants multibyte strings as input but
+ * how DVI char codes are converted to multibyte sting
+ * is not clear.
+ */
+void
+dvi_set (SIGNED_QUAD ch)
+{
+ struct loaded_font *font;
+ spt_t width, height, depth;
+ unsigned char wbuf[2];
+
+ if (current_font < 0) {
+ ERROR("No font selected!");
+ }
+ /* The division by dvi2pts seems strange since we actually know the
+ * "dvi" size of the fonts contained in the DVI file. In other
+ * words, we converted from DVI units to pts and back again!
+ * The problem comes from fonts defined in VF files where we don't know
+ * the DVI size. It's keeping me sane to keep *point sizes* of *all*
+ * fonts in the dev.c file and convert them back if necessary.
+ */
+ font = &loaded_fonts[current_font];
+
+ width = tfm_get_fw_width(font->tfm_id, ch);
+ width = sqxfw(font->size, width);
+
+ switch (font->type) {
+ case PHYSICAL:
+ if (ch > 255) { /* _FIXME_ */
+ wbuf[0] = (ch >> 8) & 0xff;
+ wbuf[1] = ch & 0xff;
+ pdf_dev_set_string(dvi_state.h, -dvi_state.v, wbuf, 2,
+ width, font->font_id, 2);
+ } else if (font->subfont_id >= 0) {
+ unsigned short uch = lookup_sfd_record(font->subfont_id, (unsigned char) ch);
+ wbuf[0] = (uch >> 8) & 0xff;
+ wbuf[1] = uch & 0xff;
+ pdf_dev_set_string(dvi_state.h, -dvi_state.v, wbuf, 2,
+ width, font->font_id, 2);
+ } else {
+ wbuf[0] = (unsigned char) ch;
+ pdf_dev_set_string(dvi_state.h, -dvi_state.v, wbuf, 1,
+ width, font->font_id, 1);
+ }
+ if (compute_boxes && link_annot &&
+ marked_depth >= tagged_depth) {
+ pdf_rect rect;
+
+ height = tfm_get_fw_height(font->tfm_id, ch);
+ depth = tfm_get_fw_depth (font->tfm_id, ch);
+ height = sqxfw(font->size, height);
+ depth = sqxfw(font->size, depth);
+
+ pdf_dev_set_rect (&rect, dvi_state.h, -dvi_state.v,
+ width, height, depth);
+ pdf_doc_expand_box(&rect);
+ }
+ break;
+ case VIRTUAL:
+#if 0
+ /* See comment in locate_font() */
+ if (font->subfont_id >= 0)
+ ch = lookup_sfd_record(font->subfont_id, (unsigned char) ch);
+#endif /* 0 */
+ vf_set_char(ch, font->font_id); /* push/pop invoked */
+ break;
+ }
+
+ if (!dvi_state.d) {
+ dvi_state.h += width;
+ } else {
+ dvi_state.v += width;
+ }
+}
+
+void
+dvi_put (SIGNED_QUAD ch)
+{
+ struct loaded_font *font;
+ spt_t width, height, depth;
+ unsigned char wbuf[2];
+
+ if (current_font < 0) {
+ ERROR("No font selected!");
+ }
+
+ font = &loaded_fonts[current_font];
+
+ switch (font->type) {
+ case PHYSICAL:
+ width = tfm_get_fw_width(font->tfm_id, ch);
+ width = sqxfw(font->size, width);
+
+ /* Treat a single character as a one byte string and use the
+ * string routine.
+ */
+ if (ch > 255) { /* _FIXME_ */
+ wbuf[0] = (ch >> 8) & 0xff;
+ wbuf[1] = ch & 0xff;
+ pdf_dev_set_string(dvi_state.h, -dvi_state.v, wbuf, 2,
+ width, font->font_id, 2);
+ } else if (font->subfont_id >= 0) {
+ unsigned int uch;
+
+ uch = lookup_sfd_record(font->subfont_id, (unsigned char) ch);
+ wbuf[0] = (uch >> 8) & 0xff;
+ wbuf[1] = uch & 0xff;
+ pdf_dev_set_string(dvi_state.h, -dvi_state.v, wbuf, 2,
+ width, font->font_id, 2);
+ } else {
+ wbuf[0] = (unsigned char) ch;
+ pdf_dev_set_string(dvi_state.h, -dvi_state.v, wbuf, 1,
+ width, font->font_id, 1);
+ }
+ if (compute_boxes && link_annot &&
+ marked_depth >= tagged_depth) {
+ pdf_rect rect;
+
+ height = tfm_get_fw_height(font->tfm_id, ch);
+ depth = tfm_get_fw_depth (font->tfm_id, ch);
+ height = sqxfw(font->size, height);
+ depth = sqxfw(font->size, depth);
+
+ pdf_dev_set_rect (&rect, dvi_state.h, -dvi_state.v,
+ width, height, depth);
+ pdf_doc_expand_box(&rect);
+ }
+ break;
+ case VIRTUAL:
+#if 0
+ /* See comment in locate_font() */
+ if (font->subfont_id >= 0)
+ ch = lookup_sfd_record(font->subfont_id, (unsigned char) ch);
+#endif /* 0 */
+ vf_set_char(ch, font->font_id);
+ break;
+ }
+
+ return;
+}
+
+
+void
+dvi_rule (SIGNED_QUAD width, SIGNED_QUAD height)
+{
+ do_moveto(dvi_state.h, dvi_state.v);
+
+ if (!dvi_state.d) {
+ pdf_dev_set_rule(dvi_state.h, -dvi_state.v, width, height);
+ } else { /* right ? */
+ pdf_dev_set_rule(dvi_state.h, -dvi_state.v - width, height, width);
+ }
+}
+
+void
+dvi_dir (UNSIGNED_BYTE dir)
+{
+ dvi_state.d = dir ? 1 : 0;
+ pdf_dev_set_dirmode(dvi_state.d); /* 0: horizontal, 1: vertical */
+}
+
+static void
+do_set1 (void)
+{
+ dvi_set(get_buffered_unsigned_byte());
+}
+
+static void
+do_set2 (void)
+{
+ dvi_set(get_buffered_unsigned_pair());
+}
+
+static void
+do_setrule (void)
+{
+ SIGNED_QUAD width, height;
+
+ height = get_buffered_signed_quad();
+ width = get_buffered_signed_quad();
+ if (width > 0 && height > 0) {
+ dvi_rule(width, height);
+ }
+ dvi_right(width);
+}
+
+static void
+do_putrule (void)
+{
+ SIGNED_QUAD width, height;
+
+ height = get_buffered_signed_quad ();
+ width = get_buffered_signed_quad ();
+ if (width > 0 && height > 0) {
+ dvi_rule(width, height);
+ }
+}
+
+static void
+do_put1 (void)
+{
+ dvi_put(get_buffered_unsigned_byte());
+}
+
+static void
+do_put2 (void)
+{
+ dvi_put(get_buffered_unsigned_pair());
+}
+
+void
+dvi_push (void)
+{
+ if (dvi_stack_depth >= DVI_STACK_DEPTH_MAX)
+ ERROR("DVI stack exceeded limit.");
+
+ dvi_stack[dvi_stack_depth++] = dvi_state;
+}
+
+void
+dvi_pop (void)
+{
+ if (dvi_stack_depth <= 0)
+ ERROR ("Tried to pop an empty stack.");
+
+ dvi_state = dvi_stack[--dvi_stack_depth];
+ do_moveto(dvi_state.h, dvi_state.v);
+ pdf_dev_set_dirmode(dvi_state.d); /* 0: horizontal, 1: vertical */
+}
+
+
+static void
+do_right1 (void)
+{
+ dvi_right(get_buffered_signed_byte());
+}
+
+static void
+do_right2 (void)
+{
+ dvi_right(get_buffered_signed_pair());
+}
+
+static void
+do_right3 (void)
+{
+ dvi_right(get_buffered_signed_triple());
+}
+
+static void
+do_right4 (void)
+{
+ dvi_right(get_buffered_signed_quad());
+}
+
+void
+dvi_w (SIGNED_QUAD ch)
+{
+ dvi_state.w = ch;
+ dvi_right(ch);
+}
+
+void
+dvi_w0 (void)
+{
+ dvi_right(dvi_state.w);
+}
+
+static void
+do_w1 (void)
+{
+ dvi_w(get_buffered_signed_byte());
+}
+
+static void
+do_w2 (void)
+{
+ dvi_w(get_buffered_signed_pair());
+}
+
+static void
+do_w3 (void)
+{
+ dvi_w(get_buffered_signed_triple());
+}
+
+static void
+do_w4 (void)
+{
+ dvi_w(get_buffered_signed_quad());
+}
+
+void
+dvi_x (SIGNED_QUAD ch)
+{
+ dvi_state.x = ch;
+ dvi_right(ch);
+}
+
+void
+dvi_x0 (void)
+{
+ dvi_right(dvi_state.x);
+}
+
+static void
+do_x1 (void)
+{
+ dvi_x(get_buffered_signed_byte());
+}
+
+static void
+do_x2 (void)
+{
+ dvi_x(get_buffered_signed_pair());
+}
+
+static void
+do_x3 (void)
+{
+ dvi_x(get_buffered_signed_triple());
+}
+
+static void
+do_x4 (void)
+{
+ dvi_x(get_buffered_signed_quad());
+}
+
+static void
+do_down1 (void)
+{
+ dvi_down(get_buffered_signed_byte());
+}
+
+static void
+do_down2 (void)
+{
+ dvi_down(get_buffered_signed_pair());
+}
+
+static void
+do_down3 (void)
+{
+ dvi_down(get_buffered_signed_triple());
+}
+
+static void
+do_down4 (void)
+{
+ dvi_down(get_buffered_signed_quad());
+}
+
+void
+dvi_y (SIGNED_QUAD ch)
+{
+ dvi_state.y = ch;
+ dvi_down(ch);
+}
+
+void
+dvi_y0 (void)
+{
+ dvi_down(dvi_state.y);
+}
+
+static
+void do_y1 (void)
+{
+ dvi_y(get_buffered_signed_byte());
+}
+
+static
+void do_y2 (void)
+{
+ dvi_y(get_buffered_signed_pair());
+}
+
+static
+void do_y3 (void)
+{
+ dvi_y(get_buffered_signed_triple());
+}
+
+static
+void do_y4 (void)
+{
+ dvi_y(get_buffered_signed_quad());
+}
+
+void
+dvi_z (SIGNED_QUAD ch)
+{
+ dvi_state.z = ch;
+ dvi_down(ch);
+}
+
+void
+dvi_z0 (void)
+{
+ dvi_down(dvi_state.z);
+}
+
+static void
+do_z1 (void)
+{
+ dvi_z(get_buffered_signed_byte());
+}
+
+static void
+do_z2 (void)
+{
+ dvi_z(get_buffered_signed_pair());
+}
+
+static void
+do_z3 (void)
+{
+ dvi_z(get_buffered_signed_triple());
+}
+
+static void
+do_z4 (void)
+{
+ dvi_z(get_buffered_signed_quad());
+}
+
+static void
+skip_fntdef (void)
+{
+ int area_len, name_len, i;
+
+ get_signed_quad(dvi_file);
+ get_signed_quad(dvi_file);
+ get_signed_quad(dvi_file);
+ area_len = get_unsigned_byte(dvi_file);
+ name_len = get_unsigned_byte(dvi_file);
+ for (i = 0; i < area_len + name_len; i++) {
+ get_unsigned_byte(dvi_file);
+ }
+}
+
+static void
+do_fntdef1 (int scanning)
+{
+ if (scanning) {
+ /* when pre-scanning the page, we process fntdef and don't buffer it */
+ SIGNED_QUAD tex_id = get_unsigned_byte(dvi_file);
+ if (linear) {
+ read_font_record(tex_id);
+ }
+ else {
+ skip_fntdef();
+ }
+ --dvi_page_buf_index; /* remove the fntdef opcode from the buffer */
+ }
+}
+
+static void
+do_fntdef2 (int scanning)
+{
+ if (scanning) {
+ SIGNED_QUAD tex_id = get_unsigned_pair(dvi_file);
+ if (linear) {
+ read_font_record(tex_id);
+ }
+ else {
+ skip_fntdef();
+ }
+ --dvi_page_buf_index;
+ }
+}
+
+static void
+do_fntdef3 (int scanning)
+{
+ if (scanning) {
+ SIGNED_QUAD tex_id = get_unsigned_triple(dvi_file);
+ if (linear) {
+ read_font_record(tex_id);
+ }
+ else {
+ skip_fntdef();
+ }
+ --dvi_page_buf_index;
+ }
+}
+
+static void
+do_fntdef4 (int scanning)
+{
+ if (scanning) {
+ SIGNED_QUAD tex_id = get_signed_quad(dvi_file);
+ if (linear) {
+ read_font_record(tex_id);
+ }
+ else {
+ skip_fntdef();
+ }
+ --dvi_page_buf_index;
+ }
+}
+
+void
+dvi_set_font (int font_id)
+{
+ current_font = font_id;
+}
+
+static void
+do_fnt (SIGNED_QUAD tex_id)
+{
+ int i;
+
+ for (i = 0; i < num_def_fonts; i++) {
+ if (def_fonts[i].tex_id == tex_id)
+ break;
+ }
+
+ if (i == num_def_fonts) {
+ ERROR("Tried to select a font that hasn't been defined: id=%ld", tex_id);
+ }
+
+ if (!def_fonts[i].used) {
+ int font_id;
+
+#ifdef XETEX
+ if (def_fonts[i].native) {
+ font_id = dvi_locate_native_font(def_fonts[i].font_name,
+ def_fonts[i].point_size,
+ def_fonts[i].layout_dir,
+ def_fonts[i].extend,
+ def_fonts[i].slant,
+ def_fonts[i].embolden);
+ } else {
+ font_id = dvi_locate_font(def_fonts[i].font_name,
+ def_fonts[i].point_size);
+ }
+ loaded_fonts[font_id].rgba_color = def_fonts[i].rgba_color;
+#else
+ font_id = dvi_locate_font(def_fonts[i].font_name, def_fonts[i].point_size);
+#endif
+ loaded_fonts[font_id].source = DVI;
+ def_fonts[i].used = 1;
+ def_fonts[i].font_id = font_id;
+ }
+ current_font = def_fonts[i].font_id;
+}
+
+static void
+do_fnt1 (void)
+{
+ SIGNED_QUAD tex_id;
+
+ tex_id = get_buffered_unsigned_byte();
+ do_fnt(tex_id);
+}
+
+static void
+do_fnt2 (void)
+{
+ SIGNED_QUAD tex_id;
+
+ tex_id = get_buffered_unsigned_pair();
+ do_fnt(tex_id);
+}
+
+static void
+do_fnt3 (void)
+{
+ SIGNED_QUAD tex_id;
+
+ tex_id = get_buffered_unsigned_triple();
+ do_fnt(tex_id);
+}
+
+static void
+do_fnt4 (void)
+{
+ SIGNED_QUAD tex_id;
+
+ tex_id = get_buffered_signed_quad();
+ do_fnt(tex_id);
+}
+
+static void
+do_xxx (UNSIGNED_QUAD size)
+{
+#if 0
+ UNSIGNED_QUAD i;
+ Ubyte *buffer; /* FIXME - no need for new buffer here */
+
+ buffer = NEW(size+1, Ubyte);
+ for (i = 0; i < size; i++) {
+ buffer[i] = get_buffered_unsigned_byte();
+ }
+ dvi_do_special(buffer, size);
+ RELEASE(buffer);
+#else
+ dvi_do_special(dvi_page_buffer + dvi_page_buf_index, size);
+ dvi_page_buf_index += size;
+#endif
+}
+
+static void
+do_xxx1 (void)
+{
+ SIGNED_QUAD size;
+
+ size = get_buffered_unsigned_byte();
+ do_xxx(size);
+}
+
+static void
+do_xxx2 (void)
+{
+ SIGNED_QUAD size;
+
+ size = get_buffered_unsigned_pair();
+ do_xxx(size);
+}
+
+static void
+do_xxx3 (void)
+{
+ SIGNED_QUAD size;
+
+ size = get_buffered_unsigned_triple();
+ do_xxx(size);
+}
+
+static void
+do_xxx4 (void)
+{
+ SIGNED_QUAD size;
+
+ size = get_buffered_unsigned_quad();
+ do_xxx(size);
+}
+
+static void
+do_bop (void)
+{
+ int i;
+
+ if (processing_page)
+ ERROR("Got a bop in the middle of a page!");
+
+ /* For now, ignore TeX's count registers */
+ for (i = 0; i < 10; i++) {
+ get_buffered_signed_quad();
+ }
+ /* Ignore previous page pointer since we have already
+ * saved this information
+ */
+ get_buffered_signed_quad();
+ clear_state();
+ processing_page = 1;
+
+ pdf_doc_begin_page(dvi_tell_mag(), dev_origin_x, dev_origin_y);
+ spc_exec_at_begin_page();
+
+ return;
+}
+
+static void
+do_eop (void)
+{
+ processing_page = 0;
+
+ if (dvi_stack_depth != 0) {
+ ERROR("DVI stack depth is not zero at end of page");
+ }
+ spc_exec_at_end_page();
+
+ pdf_doc_end_page();
+
+ return;
+}
+
+static void
+do_dir (void)
+{
+ dvi_state.d = get_buffered_unsigned_byte() ? 1 : 0;
+ pdf_dev_set_dirmode(dvi_state.d); /* 0: horizontal, 1: vertical */
+}
+
+#ifdef XETEX
+static void
+do_native_font_def (int scanning)
+{
+ if (scanning) {
+ SIGNED_QUAD tex_id = get_signed_quad(dvi_file);
+ if (linear) {
+ read_native_font_record(tex_id);
+ } else {
+ UNSIGNED_PAIR flags;
+ int name_length, nvars, i;
+
+ get_unsigned_quad(dvi_file); /* skip point size */
+ flags = get_unsigned_pair(dvi_file);
+ name_length = (int) get_unsigned_byte(dvi_file);
+ name_length += (int) get_unsigned_byte(dvi_file);
+ name_length += (int) get_unsigned_byte(dvi_file);
+ for (i = 0; i < name_length; ++i)
+ get_unsigned_byte(dvi_file);
+ if (flags & XDV_FLAG_COLORED) {
+ get_unsigned_quad(dvi_file);
+ }
+ if (flags & XDV_FLAG_VARIATIONS) {
+ nvars = get_unsigned_pair(dvi_file);
+ for (i = 0; i < nvars * 2; ++i)
+ get_unsigned_quad(dvi_file); /* skip axis and value for each variation setting */
+ }
+ }
+ --dvi_page_buf_index; /* don't buffer the opcode */
+ }
+}
+
+static void
+do_glyph_array (int yLocsPresent)
+{
+ struct loaded_font *font;
+ spt_t width, height, depth, *xloc, *yloc, glyph_width = 0;
+ unsigned char wbuf[2];
+ unsigned int i, glyph_id, slen = 0;
+
+ if (current_font < 0)
+ ERROR("No font selected!");
+
+ font = &loaded_fonts[current_font];
+
+ width = get_buffered_signed_quad();
+
+ slen = (unsigned int) get_buffered_unsigned_pair();
+ xloc = NEW(slen, spt_t);
+ yloc = NEW(slen, spt_t);
+ for (i = 0; i < slen; i++) {
+ xloc[i] = get_buffered_signed_quad();
+ yloc[i] = yLocsPresent ? get_buffered_signed_quad() : 0;
+ }
+
+ if (font->rgba_color != 0xffffffff) {
+ pdf_color color;
+ pdf_color_rgbcolor(&color,
+ (double)((unsigned char)(font->rgba_color >> 24) & 0xff) / 255,
+ (double)((unsigned char)(font->rgba_color >> 16) & 0xff) / 255,
+ (double)((unsigned char)(font->rgba_color >> 8) & 0xff) / 255);
+ pdf_color_push(&color, &color);
+ }
+
+ for (i = 0; i < slen; i++) {
+ glyph_id = get_buffered_unsigned_pair(); /* freetype glyph index */
+ if (glyph_id < font->ft_face->num_glyphs) {
+ FT_Error error;
+ FT_Fixed advance;
+ int flags = FT_LOAD_NO_SCALE;
+
+ if (font->layout_dir == 1)
+ flags |= FT_LOAD_VERTICAL_LAYOUT;
+
+ error = FT_Get_Advance(font->ft_face, glyph_id, flags, &advance);
+ if (error)
+ advance = 0;
+
+ glyph_width = (double)font->size * (double)advance / (double)font->ft_face->units_per_EM;
+ glyph_width = glyph_width * font->extend;
+ if (compute_boxes && link_annot && marked_depth >= tagged_depth) {
+ pdf_rect rect;
+ height = (double)font->size * (double)font->ft_face->ascender / (double)font->ft_face->units_per_EM;
+ depth = (double)font->size * -(double)font->ft_face->descender / (double)font->ft_face->units_per_EM;
+ pdf_dev_set_rect(&rect, dvi_state.h + xloc[i], -dvi_state.v - yloc[i], glyph_width, height, depth);
+ pdf_doc_expand_box(&rect);
+ }
+ }
+
+ wbuf[0] = glyph_id >> 8;
+ wbuf[1] = glyph_id & 0xff;
+ pdf_dev_set_string(dvi_state.h + xloc[i], -dvi_state.v - yloc[i], wbuf, 2,
+ glyph_width, font->font_id, -1);
+ }
+
+ if (font->rgba_color != 0xffffffff) {
+ pdf_color_pop();
+ }
+ RELEASE(xloc);
+ RELEASE(yloc);
+
+ if (!dvi_state.d) {
+ dvi_state.h += width;
+ } else {
+ dvi_state.v += width;
+ }
+
+ return;
+}
+
+static void
+do_pic_file(void)
+ /* parameters for XDV_PIC_FILE opcode: pdf_box[1] t[4][6] p[2] len[2] path[l] */
+{
+ int page_no;
+ UNSIGNED_PAIR len;
+ char *path;
+ int i;
+ int xobj_id;
+ transform_info ti;
+
+ transform_info_clear(&ti);
+
+ /* pdf_box = */ get_buffered_unsigned_byte();
+
+ ti.matrix.a = get_buffered_signed_quad() / 65536.0; /* convert 16.16 Fixed to floating-point */
+ ti.matrix.b = get_buffered_signed_quad() / 65536.0;
+ ti.matrix.c = get_buffered_signed_quad() / 65536.0;
+ ti.matrix.d = get_buffered_signed_quad() / 65536.0;
+ ti.matrix.e = get_buffered_signed_quad() / 65536.0;
+ ti.matrix.f = get_buffered_signed_quad() / 65536.0;
+
+ page_no = get_buffered_signed_pair();
+ len = get_buffered_unsigned_pair();
+ path = NEW(len + 1, char);
+ for (i = 0; i < len; ++i)
+ path[i] = get_buffered_unsigned_byte();
+ path[len] = 0;
+
+ /*
+ now we need to place page /page_no/ of the graphic file from /path/, applying /transform/
+ if pdf_box=0 the file is a raster image (.jpg, .png, .tif, etc; need to determine format
+ by examining the file)
+ else it is a PDF document, pdf_box tells which PDF box (media, trim, crop, etc) to use
+ page_no is currently only used with PDF documents, though in theory could be used
+ with multi-page TIFFs, etc
+ transform is a 3x2 affine transform matrix expressed in fixed-point values
+ */
+
+ xobj_id = pdf_ximage_findresource(path, page_no, NULL);
+ if (xobj_id >= 0) {
+ /* FIXME: this seems to work for 72dpi JPEGs, but isn't right for others;
+ need to take the actual image resolution into account in pdf_dev_put_image,
+ not just assume the "original" size is 100dpi
+ */
+ pdf_dev_put_image(xobj_id, &ti, dvi_dev_xpos(), dvi_dev_ypos());
+ }
+
+ RELEASE(path);
+}
+#endif
+
+/* Note to be absolutely certain that the string escape buffer doesn't
+ * hit its limit, FORMAT_BUF_SIZE should set to 4 times S_BUFFER_SIZE
+ * in pdfobj.c. Is there any application that genenerate words with
+ * 1k characters?
+ */
+
+#define SBUF_SIZE 1024
+
+/* Most of the work of actually interpreting
+ * the dvi file is here.
+ */
+void
+dvi_do_page (long n,
+ double paper_width, double paper_height,
+ double hmargin, double vmargin)
+{
+ unsigned char opcode;
+ unsigned char sbuf[SBUF_SIZE];
+ unsigned int slen = 0;
+
+ /* before this is called, we have scanned the page for papersize specials
+ and the complete DVI data is now in dvi_page_buffer */
+ dvi_page_buf_index = 0;
+
+ /* DVI coordinate */
+ dev_origin_x = hmargin;
+ dev_origin_y = paper_height - vmargin;
+
+ dvi_stack_depth = 0;
+ for (;;) {
+ /* The most likely opcodes are individual setchars.
+ * These are buffered for speed. */
+ slen = 0;
+ while ((opcode = get_buffered_unsigned_byte()) <= SET_CHAR_127 &&
+ slen < SBUF_SIZE) {
+ sbuf[slen++] = opcode;
+ }
+ if (slen > 0) {
+ do_string(sbuf, slen);
+ }
+ if (slen == SBUF_SIZE)
+ continue;
+
+ /* If we are here, we have an opcode that is something
+ * other than SET_CHAR.
+ */
+ if (opcode >= FNT_NUM_0 && opcode <= FNT_NUM_63) {
+ do_fnt(opcode - FNT_NUM_0);
+ continue;
+ }
+
+ switch (opcode) {
+ case SET1: do_set1(); break;
+ case SET2: do_set2(); break;
+ case SET3: case SET4:
+ ERROR("Multibyte (>16 bits) character not supported!");
+ break;
+
+ case SET_RULE:
+ do_setrule();
+ break;
+
+ case PUT1: do_put1(); break;
+ case PUT2: do_put2(); break;
+ case PUT3: case PUT4:
+ ERROR ("Multibyte character (>16 bits) not supported!");
+ break;
+
+ case PUT_RULE:
+ do_putrule();
+ break;
+
+ case NOP:
+ break;
+
+ case BOP:
+ do_bop();
+ MESG("[%d", n+1);
+ break;
+ case EOP:
+ do_eop();
+ MESG("]");
+ return;
+ break;
+
+ case PUSH:
+ dvi_push();
+ /* The following line needs to go here instead of in
+ * dvi_push() since logical structure of document is
+ * oblivous to virtual fonts. For example the last line on a
+ * page could be at stack level 3 and the page footer should
+ * be at stack level 3. However, if the page footer contains
+ * virtual fonts (or other nested constructions), it could
+ * fool the link breaker into thinking it was a continuation
+ * of the link */
+ dvi_mark_depth();
+ break;
+ case POP:
+ dvi_pop();
+ /* Above explanation holds for following line too */
+ dvi_mark_depth();
+ break;
+
+ case RIGHT1: do_right1(); break;
+ case RIGHT2: do_right2(); break;
+ case RIGHT3: do_right3(); break;
+ case RIGHT4: do_right4(); break;
+
+ case W0: dvi_w0(); break;
+ case W1: do_w1 (); break;
+ case W2: do_w2 (); break;
+ case W3: do_w3 (); break;
+ case W4: do_w4 (); break;
+
+ case X0: dvi_x0(); break;
+ case X1: do_x1 (); break;
+ case X2: do_x2 (); break;
+ case X3: do_x3 (); break;
+ case X4: do_x4 (); break;
+
+ case DOWN1: do_down1(); break;
+ case DOWN2: do_down2(); break;
+ case DOWN3: do_down3(); break;
+ case DOWN4: do_down4(); break;
+
+ case Y0: dvi_y0(); break;
+ case Y1: do_y1 (); break;
+ case Y2: do_y2 (); break;
+ case Y3: do_y3 (); break;
+ case Y4: do_y4 (); break;
+
+ case Z0: dvi_z0(); break;
+ case Z1: do_z1 (); break;
+ case Z2: do_z2 (); break;
+ case Z3: do_z3 (); break;
+ case Z4: do_z4 (); break;
+
+ case FNT1: do_fnt1(); break;
+ case FNT2: do_fnt2(); break;
+ case FNT3: do_fnt3(); break;
+ case FNT4: do_fnt4(); break;
+
+ /* Specials */
+ case XXX1: do_xxx1(); break;
+ case XXX2: do_xxx2(); break;
+ case XXX3: do_xxx3(); break;
+ case XXX4: do_xxx4(); break;
+
+ /* Font definition - skipped except in linear mode. */
+ /* actually, these should not occur! */
+ case FNT_DEF1: do_fntdef1(0); break;
+ case FNT_DEF2: do_fntdef2(0); break;
+ case FNT_DEF3: do_fntdef3(0); break;
+ case FNT_DEF4: do_fntdef4(0); break;
+
+ /* pTeX extension */
+ case PTEXDIR:
+ do_dir();
+ break;
+
+#ifdef XETEX
+ /* XeTeX extension */
+ case XDV_GLYPH_STRING:
+ do_glyph_array(0);
+ break;
+ case XDV_GLYPH_ARRAY:
+ do_glyph_array(1);
+ break;
+ case XDV_NATIVE_FONT_DEF:
+ do_native_font_def(0); /* should not occur - processed during pre-scanning */
+ break;
+ case XDV_PIC_FILE:
+ do_pic_file();
+ break;
+#endif
+ case POST:
+ if (linear && !processing_page) {
+ /* for linear processing, this means there are no more pages */
+ num_pages = 0; /* force loop to terminate */
+ return;
+ }
+ /* else fall through to error case */
+ case PRE: case POST_POST:
+ ERROR("Unexpected preamble or postamble in dvi file");
+ break;
+ default:
+ ERROR("Unexpected opcode or DVI file ended prematurely");
+ }
+ }
+}
+
+#ifdef WIN32
+#define STR_CMP strcasecmp
+#else
+#define STR_CMP strcmp
+#endif
+
+double
+dvi_init (char *dvi_filename, double mag)
+{
+ long post_location;
+
+ if (dvi_filename == NULL) { /* no filename: reading from stdin, probably a pipe */
+#ifdef WIN32
+ setmode(fileno(stdin), _O_BINARY);
+#endif
+ dvi_file = stdin;
+ linear = 1;
+
+ get_preamble_dvi_info();
+ do_scales(mag);
+ }
+ else {
+ dvi_file = MFOPEN(dvi_filename, FOPEN_RBIN_MODE);
+ if (!dvi_file) {
+ char *p;
+ p = strrchr(dvi_filename, '.');
+#ifdef XETEX
+ if (p == NULL || (STR_CMP(p, ".dvi") && STR_CMP(p, ".xdv"))) {
+#else
+ if (p == NULL || STR_CMP(p, ".dvi")) {
+#endif
+#ifdef XETEX
+ strcat(dvi_filename, ".xdv");
+ dvi_file = MFOPEN(dvi_filename, FOPEN_RBIN_MODE);
+ if (!dvi_file) {
+ dvi_filename[strlen(dvi_filename) - 4] = '\0';
+#endif
+ strcat(dvi_filename, ".dvi");
+ dvi_file = MFOPEN(dvi_filename, FOPEN_RBIN_MODE);
+#ifdef XETEX
+ }
+#endif
+ }
+ }
+ if (!dvi_file) {
+#ifdef XETEX
+ ERROR("Could not open specified DVI (or XDV) file: %s", dvi_filename);
+#else
+ ERROR("Could not open specified DVI file: %s", dvi_filename);
+#endif
+ return 0.0;
+ }
+
+ /* DVI files are most easily read backwards by
+ * searching for post_post and then post opcode.
+ */
+ post_location = find_post();
+ get_dvi_info(post_location);
+ do_scales(mag);
+ get_page_info(post_location);
+ get_comment();
+ get_dvi_fonts(post_location);
+ }
+
+ clear_state();
+
+ dvi_page_buf_size = DVI_PAGE_BUF_CHUNK;
+ dvi_page_buffer = NEW(dvi_page_buf_size, unsigned char);
+
+ return dvi2pts;
+}
+
+void
+dvi_close (void)
+{
+ int i;
+
+ if (linear) {
+ /* probably reading a pipe from xetex; consume any remaining data */
+ while (fgetc(dvi_file) != EOF)
+ ;
+ }
+
+ /* We add comment in dvi_close instead of dvi_init so user
+ * has a change to overwrite it. The docinfo dictionary is
+ * treated as a write-once record.
+ */
+
+ /* Do some house cleaning */
+ MFCLOSE(dvi_file);
+ dvi_file = NULL;
+
+ if (def_fonts) {
+ for (i = 0; i < num_def_fonts; i++) {
+ if (def_fonts[i].font_name)
+ RELEASE(def_fonts[i].font_name);
+ def_fonts[i].font_name = NULL;
+ }
+ RELEASE(def_fonts);
+ }
+ def_fonts = NULL;
+
+ if (page_loc)
+ RELEASE(page_loc);
+ page_loc = NULL;
+ num_pages = 0;
+
+ if (loaded_fonts)
+ RELEASE(loaded_fonts);
+ loaded_fonts = NULL;
+ num_loaded_fonts = 0;
+
+ vf_close_all_fonts();
+ tfm_close_all ();
+
+ if (dvi_page_buffer) {
+ RELEASE(dvi_page_buffer);
+ dvi_page_buffer = NULL;
+ dvi_page_buf_size = 0;
+ }
+}
+
+/* The following are need to implement virtual fonts
+ According to documentation, the vf "subroutine"
+ must have state pushed and must have
+ w,v,y, and z set to zero. The current font
+ is determined by the virtual font header, which
+ may be undefined */
+
+static int saved_dvi_font[VF_NESTING_MAX];
+static int num_saved_fonts = 0;
+
+void
+dvi_vf_init (int dev_font_id)
+{
+ dvi_push();
+
+ dvi_state.w = 0; dvi_state.x = 0;
+ dvi_state.y = 0; dvi_state.z = 0;
+
+ /* do not reset dvi_state.d. */
+ if (num_saved_fonts < VF_NESTING_MAX) {
+ saved_dvi_font[num_saved_fonts++] = current_font;
+ } else
+ ERROR("Virtual fonts nested too deeply!");
+ current_font = dev_font_id;
+}
+
+/* After VF subroutine is finished, we simply pop the DVI stack */
+void
+dvi_vf_finish (void)
+{
+ dvi_pop();
+ if (num_saved_fonts > 0)
+ current_font = saved_dvi_font[--num_saved_fonts];
+ else {
+ ERROR("Tried to pop an empty font stack");
+ }
+}
+
+
+/* Scan various specials */
+#include "dpxutil.h"
+
+/* This need to allow 'true' prefix for unit and
+ * length value must be divided by current magnification.
+ */
+static int
+read_length (double *vp, double mag, const char **pp, const char *endptr)
+{
+ char *q;
+ const char *p = *pp;
+ double v, u = 1.0;
+ const char *_ukeys[] = {
+#define K_UNIT__PT 0
+#define K_UNIT__IN 1
+#define K_UNIT__CM 2
+#define K_UNIT__MM 3
+#define K_UNIT__BP 4
+ "pt", "in", "cm", "mm", "bp",
+ NULL
+ };
+ int k, error = 0;
+
+ q = parse_float_decimal(&p, endptr);
+ if (!q) {
+ *vp = 0.0; *pp = p;
+ return -1;
+ }
+
+ v = atof(q);
+ RELEASE(q);
+
+ skip_white(&p, endptr);
+ q = parse_c_ident(&p, endptr);
+ if (q) {
+ char *qq = q; /* remember this for RELEASE, because q may be advanced */
+ if (strlen(q) >= strlen("true") &&
+ !memcmp(q, "true", strlen("true"))) {
+ u /= mag != 0.0 ? mag : 1.0; /* inverse magnify */
+ q += strlen("true");
+ }
+ if (strlen(q) == 0) { /* "true" was a separate word from the units */
+ RELEASE(qq);
+ skip_white(&p, endptr);
+ qq = q = parse_c_ident(&p, endptr);
+ }
+ if (q) {
+ for (k = 0; _ukeys[k] && strcmp(_ukeys[k], q); k++);
+ switch (k) {
+ case K_UNIT__PT: u *= 72.0 / 72.27; break;
+ case K_UNIT__IN: u *= 72.0; break;
+ case K_UNIT__CM: u *= 72.0 / 2.54 ; break;
+ case K_UNIT__MM: u *= 72.0 / 25.4 ; break;
+ case K_UNIT__BP: u *= 1.0 ; break;
+ default:
+ WARN("Unknown unit of measure: %s", q);
+ error = -1;
+ break;
+ }
+ RELEASE(qq);
+ }
+ else {
+ WARN("Missing unit of measure after \"true\"");
+ error = -1;
+ }
+ }
+
+ *vp = v * u; *pp = p;
+ return error;
+}
+
+
+static int
+scan_special (double *wd, double *ht, double *xo, double *yo, char *lm,
+ unsigned *minorversion,
+ int *do_enc, unsigned *key_bits, unsigned *permission, char *owner_pw, char *user_pw,
+ const char *buf, UNSIGNED_QUAD size)
+{
+ char *q;
+ const char *p = buf, *endptr;
+ int ns_pdf = 0, error = 0;
+ double tmp;
+
+ endptr = p + size;
+
+ skip_white(&p, endptr);
+
+ q = parse_c_ident(&p, endptr);
+ if (q && !strcmp(q, "pdf")) {
+ skip_white(&p, endptr);
+ if (p < endptr && *p == ':') {
+ p++;
+ skip_white(&p, endptr);
+ RELEASE(q);
+ q = parse_c_ident(&p, endptr); ns_pdf = 1;
+ }
+ }
+ else if (q && !strcmp(q, "x")) {
+ skip_white(&p, endptr);
+ if (p < endptr && *p == ':') {
+ p++;
+ skip_white(&p, endptr);
+ RELEASE(q);
+ q = parse_c_ident(&p, endptr);
+ }
+ }
+ skip_white(&p, endptr);
+
+ if (q) {
+ if (!strcmp(q, "landscape")) {
+ *lm = 1;
+ } else if (ns_pdf && !strcmp(q, "pagesize")) {
+ while (!error && p < endptr) {
+ char *kp = parse_c_ident(&p, endptr);
+ if (!kp)
+ break;
+ else {
+ skip_white(&p, endptr);
+ if (!strcmp(kp, "width")) {
+ error = read_length(&tmp, dvi_tell_mag(), &p, endptr);
+ if (!error)
+ *wd = tmp * dvi_tell_mag();
+ } else if (!strcmp(kp, "height")) {
+ error = read_length(&tmp, dvi_tell_mag(), &p, endptr);
+ if (!error)
+ *ht = tmp * dvi_tell_mag();
+ } else if (!strcmp(kp, "xoffset")) {
+ error = read_length(&tmp, dvi_tell_mag(), &p, endptr);
+ if (!error)
+ *xo = tmp * dvi_tell_mag();
+ } else if (!strcmp(kp, "yoffset")) {
+ error = read_length(&tmp, dvi_tell_mag(), &p, endptr);
+ if (!error)
+ *yo = tmp * dvi_tell_mag();
+ } else if (!strcmp(kp, "default")) {
+ *wd = paper_width;
+ *ht = paper_height;
+ *lm = landscape_mode;
+ *xo = *yo = 72.0;
+ }
+ RELEASE(kp);
+ }
+ skip_white(&p, endptr);
+ }
+ } else if (!strcmp(q, "papersize")) {
+ char qchr = 0;
+ if (*p == '=') p++;
+ skip_white(&p, endptr);
+ if (p < endptr && (*p == '\'' || *p == '\"')) {
+ qchr = *p; p++;
+ skip_white(&p, endptr);
+ }
+ error = read_length(&tmp, dvi_tell_mag(), &p, endptr);
+ if (!error) {
+ *wd = tmp * dvi_tell_mag();
+ skip_white(&p, endptr);
+ if (p < endptr && *p == ',') {
+ p++; skip_white(&p, endptr);
+ }
+ error = read_length(&tmp, dvi_tell_mag(), &p, endptr);
+ if (!error)
+ *ht = tmp * dvi_tell_mag();
+ skip_white(&p, endptr);
+ }
+ if (!error && qchr) { /* Check if properly quoted */
+ if (p >= endptr || *p != qchr)
+ error = -1;
+ }
+ if (error == 0) {
+ paper_width = *wd;
+ paper_height = *ht;
+ }
+ } else if (minorversion && ns_pdf && !strcmp(q, "minorversion")) {
+ char *kv;
+ if (*p == '=') p++;
+ skip_white(&p, endptr);
+ kv = parse_float_decimal(&p, endptr);
+ if (kv) {
+ *minorversion = (unsigned)strtol(kv, NULL, 10);
+ RELEASE(kv);
+ }
+ } else if (ns_pdf && !strcmp(q, "encrypt") && do_enc) {
+ *do_enc = 1;
+ *owner_pw = *user_pw = 0;
+ while (!error && p < endptr) {
+ char *kp = parse_c_ident(&p, endptr);
+ if (!kp)
+ break;
+ else {
+ pdf_obj *obj;
+ skip_white(&p, endptr);
+ if (!strcmp(kp, "ownerpw")) {
+ if ((obj = parse_pdf_string(&p, endptr))) {
+ strncpy(owner_pw, pdf_string_value(obj), MAX_PWD_LEN);
+ pdf_release_obj(obj);
+ } else
+ error = -1;
+ } else if (!strcmp(kp, "userpw")) {
+ if ((obj = parse_pdf_string(&p, endptr))) {
+ strncpy(user_pw, pdf_string_value(obj), MAX_PWD_LEN);
+ pdf_release_obj(obj);
+ } else
+ error = -1;
+ } else if (!strcmp(kp, "length")) {
+ if ((obj = parse_pdf_number(&p, endptr)) && PDF_OBJ_NUMBERTYPE(obj)) {
+ *key_bits = (unsigned) pdf_number_value(obj);
+ } else
+ error = -1;
+ if (obj)
+ pdf_release_obj(obj);
+ } else if (!strcmp(kp, "perm")) {
+ if ((obj = parse_pdf_number(&p, endptr)) && PDF_OBJ_NUMBERTYPE(obj)) {
+ *permission = (unsigned) pdf_number_value(obj);
+ } else
+ error = -1;
+ if (obj)
+ pdf_release_obj(obj);
+ } else
+ error = -1;
+ RELEASE(kp);
+ }
+ skip_white(&p, endptr);
+ }
+ }
+ RELEASE(q);
+ }
+
+ return error;
+}
+
+
+void
+dvi_scan_specials (long page_no,
+ double *page_width, double *page_height,
+ double *x_offset, double *y_offset, char *landscape,
+ unsigned *minorversion,
+ int *do_enc, unsigned *key_bits, unsigned *permission, char *owner_pw, char *user_pw)
+{
+ FILE *fp = dvi_file;
+ long offset;
+ unsigned char opcode;
+ static long buffered_page = -1;
+
+ if (page_no == buffered_page)
+ return; /* because dvipdfmx wants to scan first page twice! */
+ buffered_page = page_no;
+
+ dvi_page_buf_index = 0;
+
+ if (!linear) {
+ if (page_no >= num_pages)
+ ERROR("Invalid page number: %u", page_no);
+ offset = page_loc[page_no];
+
+ seek_absolute(fp, offset);
+ }
+
+ while ((opcode = get_and_buffer_unsigned_byte(fp)) != EOP) {
+ if (opcode <= SET_CHAR_127 ||
+ (opcode >= FNT_NUM_0 && opcode <= FNT_NUM_63))
+ continue;
+ else if (opcode == XXX1 || opcode == XXX2 ||
+ opcode == XXX3 || opcode == XXX4) {
+ UNSIGNED_QUAD size = 0UL;
+ switch (opcode) {
+ case XXX1: size = get_and_buffer_unsigned_byte(fp); break;
+ case XXX2: size = get_and_buffer_unsigned_pair(fp); break;
+ case XXX3: size = get_and_buffer_unsigned_triple(fp); break;
+ case XXX4: size = get_and_buffer_unsigned_quad(fp); break;
+ }
+ if (dvi_page_buf_index + size >= dvi_page_buf_size) {
+ dvi_page_buf_size = (dvi_page_buf_index + size + DVI_PAGE_BUF_CHUNK);
+ dvi_page_buffer = RENEW(dvi_page_buffer, dvi_page_buf_size, unsigned char);
+ }
+ if (fread(dvi_page_buffer + dvi_page_buf_index, sizeof(char), size, fp) != size)
+ ERROR("Reading DVI file failed!");
+ if (scan_special(page_width, page_height, x_offset, y_offset, landscape, minorversion,
+ do_enc, key_bits, permission, owner_pw, user_pw,
+ (char*)dvi_page_buffer + dvi_page_buf_index, size))
+ WARN("Reading special command failed: \"%.*s\"", size, (char*)dvi_page_buffer + dvi_page_buf_index);
+ dvi_page_buf_index += size;
+ continue;
+ }
+
+ /* Skipping... */
+ switch (opcode) {
+ case BOP:
+ get_and_buffer_bytes(fp, 44);
+ break;
+ case NOP: case PUSH: case POP:
+ case W0: case X0: case Y0: case Z0:
+ break;
+ case SET1: case PUT1: case RIGHT1: case DOWN1:
+ case W1: case X1: case Y1: case Z1: case FNT1:
+ get_and_buffer_unsigned_byte(fp);
+ break;
+
+ case SET2: case PUT2: case RIGHT2: case DOWN2:
+ case W2: case X2: case Y2: case Z2: case FNT2:
+ get_and_buffer_signed_pair(fp);
+ break;
+
+ case SET3: case PUT3: case RIGHT3: case DOWN3:
+ case W3: case X3: case Y3: case Z3: case FNT3:
+ get_and_buffer_signed_triple(fp);
+ break;
+
+ case SET4: case PUT4: case RIGHT4: case DOWN4:
+ case W4: case X4: case Y4: case Z4: case FNT4:
+ get_and_buffer_signed_quad(fp);
+ break;
+
+ case SET_RULE: case PUT_RULE:
+ get_and_buffer_bytes(fp, 8);
+ break;
+
+ case FNT_DEF1: do_fntdef1(1); break;
+ case FNT_DEF2: do_fntdef2(1); break;
+ case FNT_DEF3: do_fntdef3(1); break;
+ case FNT_DEF4: do_fntdef4(1); break;
+
+#ifdef XETEX
+ case XDV_GLYPH_STRING:
+ {
+ UNSIGNED_PAIR count;
+ get_and_buffer_unsigned_quad(fp); /* width */
+ count = get_and_buffer_unsigned_pair(fp); /* glyph count */
+ get_and_buffer_bytes(fp, count * 6); /* 2 bytes ID + 4 bytes x-location per glyph */
+ }
+ break;
+ case XDV_GLYPH_ARRAY:
+ {
+ UNSIGNED_PAIR count;
+ get_and_buffer_unsigned_quad(fp); /* width */
+ count = get_and_buffer_unsigned_pair(fp); /* glyph count */
+ get_and_buffer_bytes(fp, count * 10); /* 2 bytes ID + 8 bytes x,y-location per glyph */
+ }
+ break;
+ case XDV_NATIVE_FONT_DEF:
+ do_native_font_def(1);
+ break;
+ case XDV_PIC_FILE:
+ /* params: flags[1] t[4][6] p[2] len[2] path[l] */
+ {
+ UNSIGNED_PAIR len;
+ get_and_buffer_bytes(fp, 1 + 4 * 6 + 2);
+ len = get_and_buffer_unsigned_pair(fp); /* length of pathname */
+ get_and_buffer_bytes(fp, len);
+ }
+ break;
+#endif
+ case PTEXDIR:
+ get_and_buffer_unsigned_byte(fp);
+ break;
+
+ case POST:
+ if (linear && dvi_page_buf_index == 1) {
+ /* this is actually an indication that we've reached the end of the input */
+ return;
+ }
+ /* else fall through to error case */
+
+ default: /* case PRE: case POST_POST: and others */
+ ERROR("Unexpected opcode %d at pos=0x%x", opcode, tell_position(fp));
+ break;
+ }
+ }
+
+ return;
+}
+
diff --git a/Build/source/texk/dvipdf-x/xsrc/dvi.h b/Build/source/texk/dvipdf-x/xsrc/dvi.h
new file mode 100644
index 00000000000..9801309730f
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/dvi.h
@@ -0,0 +1,103 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _DVI_H_
+#define _DVI_H_
+
+#include "error.h"
+#include "numbers.h"
+/* spt_t */
+#include "pdfdev.h"
+
+/* instantiated in dvipdfmx.c */
+extern double paper_width, paper_height;
+extern char landscape_mode;
+
+extern double get_origin (int x);
+
+extern void dvi_set_verbose (void);
+
+/* returns scale (dvi2pts) */
+extern double dvi_init (char *dvi_filename, double mag); /* may append .dvi or .xdv to filename */
+extern void dvi_close (void); /* Closes data structures created by dvi_open */
+
+extern double dvi_tell_mag (void);
+extern double dvi_unit_size (void);
+extern double dvi_dev_xpos (void);
+extern double dvi_dev_ypos (void);
+extern unsigned dvi_npages (void);
+extern const char *dvi_comment (void);
+
+extern void dvi_vf_init (int dev_font_id);
+extern void dvi_vf_finish (void);
+
+extern void dvi_set_font (int font_id);
+extern void dvi_set (SIGNED_QUAD ch);
+extern void dvi_rule (SIGNED_QUAD width, SIGNED_QUAD height);
+
+extern void dvi_right (SIGNED_QUAD x);
+extern void dvi_put (SIGNED_QUAD ch);
+extern void dvi_push (void);
+extern void dvi_pop (void);
+extern void dvi_w0 (void);
+extern void dvi_w (SIGNED_QUAD ch);
+extern void dvi_x0 (void);
+extern void dvi_x (SIGNED_QUAD ch);
+extern void dvi_down (SIGNED_QUAD y);
+extern void dvi_y (SIGNED_QUAD ch);
+extern void dvi_y0 (void);
+extern void dvi_z (SIGNED_QUAD ch);
+extern void dvi_z0 (void);
+extern void dvi_dir (UNSIGNED_BYTE dir);
+
+extern void dvi_do_page (long page_no,
+ double paper_width, double paper_height,
+ double x_offset, double y_offset);
+extern void dvi_scan_specials (long page_no,
+ double *width, double *height,
+ double *x_offset, double *y_offset,
+ char *landscape, unsigned *minorversion,
+ int *do_enc, unsigned *key_bits, unsigned *permission, char *owner_pw, char *user_pw);
+extern int dvi_locate_font (const char *name, spt_t ptsize);
+
+/* link or nolink:
+ * See dvipdfm (not x) user's manual on pdf:link and pdf:nolink.
+ * This is workaround for preventing inclusion of pagenation artifact such as
+ * footnote and page number in link annotation.
+ */
+extern void dvi_link_annot (int flag);
+/* The followings are for calculating bounding box of text for annotation.
+ * DVI uses push/pop to do line-feed-carriage-return. So line breaking is
+ * handled by inspecting current depth of DVI register stack.
+ */
+extern void dvi_tag_depth (void);
+extern void dvi_untag_depth (void);
+extern void dvi_compute_boxes (int flag);
+
+extern void dvi_do_special (const void *buffer, UNSIGNED_QUAD size);
+
+/* allow other modules (pdfdev) to ask whether we're collecting box areas */
+int dvi_is_tracking_boxes(void);
+
+#endif /* _DVI_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/dvipdfmx.c b/Build/source/texk/dvipdf-x/xsrc/dvipdfmx.c
new file mode 100644
index 00000000000..ac97ed11198
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/dvipdfmx.c
@@ -0,0 +1,992 @@
+/*
+
+ This is xdvipdfmx, an extended version of...
+
+ DVIPDFMx, an eXtended-2013 version of DVIPDFM by Mark A. Wicks.
+
+ Copyright (c) 2006 SIL. (xdvipdfmx extensions for XeTeX support)
+
+ Copyright (C) 2008-2013 by Jin-Hwan Cho, Matthias Franz, and Shunsaku Hirata,
+ the DVIPDFMx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdio.h>
+#include <string.h>
+#include <limits.h>
+#include <ctype.h>
+
+#include "system.h"
+#include "mem.h"
+
+#include "dpxconf.h"
+#include "dpxfile.h"
+#include "dpxutil.h"
+
+#include "dvi.h"
+
+#include "pdflimits.h"
+#include "pdfdoc.h"
+#include "pdfdev.h"
+#include "pdfparse.h"
+#include "pdfencrypt.h"
+
+#include "spc_tpic.h"
+#include "specials.h"
+
+#include "mpost.h"
+
+#include "fontmap.h"
+#include "pdffont.h"
+#include "pdfximage.h"
+#include "cid.h"
+
+#include "xbb.h"
+
+#include "tt_aux.h"
+
+#include "error.h"
+
+static int verbose = 0;
+
+static int mp_mode = 0;
+
+static long opt_flags = 0;
+
+#define OPT_TPIC_TRANSPARENT_FILL (1 << 1)
+#define OPT_CIDFONT_FIXEDPITCH (1 << 2)
+#define OPT_FONTMAP_FIRST_MATCH (1 << 3)
+
+static char ignore_colors = 0;
+static double annot_grow = 0.0;
+static int bookmark_open = 0;
+static double mag = 1.0;
+static int font_dpi = 600;
+static int really_quiet = 0;
+/*
+ * Precision is essentially limited to 0.01pt.
+ * See, dev_set_string() in pdfdev.c.
+ */
+static int pdfdecimaldigits = 2;
+
+/* Image cache life in hours */
+/* 0 means erase all old images and leave new images */
+/* -1 means erase all old images and also erase new images */
+/* -2 means ignore image cache (default) */
+static int image_cache_life = -2;
+
+/* Encryption */
+static int do_encryption = 0;
+static unsigned key_bits = 40;
+static unsigned permission = 0x003C;
+
+/* Page device */
+double paper_width = 595.0; /* not static, we allow dvi.c to access them */
+double paper_height = 842.0;
+char landscape_mode = 0;
+
+static double x_offset = 72.0;
+static double y_offset = 72.0;
+
+int always_embed = 0; /* always embed fonts, regardless of licensing flags */
+
+char *dvi_filename = NULL, *pdf_filename = NULL;
+
+static void
+read_config_file (const char *config);
+
+#ifdef WIN32
+#define STRN_CMP strncasecmp
+#else
+#define STRN_CMP strncmp
+#endif
+
+static void
+set_default_pdf_filename(void)
+{
+ const char *dvi_base;
+
+ dvi_base = xbasename(dvi_filename);
+ if (mp_mode &&
+ strlen(dvi_base) > 4 &&
+ !STRN_CMP(".mps", dvi_base + strlen(dvi_base) - 4, 4)) {
+ pdf_filename = NEW(strlen(dvi_base)+1, char);
+ strncpy(pdf_filename, dvi_base, strlen(dvi_base) - 4);
+ pdf_filename[strlen(dvi_base)-4] = '\0';
+ } else if (strlen(dvi_base) > 4 &&
+#ifdef XETEX
+ (!STRN_CMP(".dvi", dvi_base+strlen(dvi_base)-4, 4) ||
+ !STRN_CMP(".xdv", dvi_base+strlen(dvi_base)-4, 4))) {
+#else
+ !STRN_CMP(".dvi", dvi_base+strlen(dvi_base)-4, 4)) {
+#endif
+ pdf_filename = NEW(strlen(dvi_base)+1, char);
+ strncpy(pdf_filename, dvi_base, strlen(dvi_base)-4);
+ pdf_filename[strlen(dvi_base)-4] = '\0';
+ } else {
+ pdf_filename = NEW(strlen(dvi_base)+5, char);
+ strcpy(pdf_filename, dvi_base);
+ }
+
+ strcat (pdf_filename, ".pdf");
+}
+
+static void
+usage (int exit_code)
+{
+ fprintf (stdout, "\nThis is %s-%s by Jonathan Kew and Jin-Hwan Cho,\n", PACKAGE, VERSION);
+ fprintf (stdout, "an extended version of DVIPDFMx, which in turn was\n");
+ fprintf (stdout, "an extended version of dvipdfm-0.13.2c developed by Mark A. Wicks.\n");
+ fprintf (stdout, "\nCopyright (c) 2006-2013 SIL International and Jin-Hwan Cho.\n");
+ fprintf (stdout, "\nThis is free software; you can redistribute it and/or modify\n");
+ fprintf (stdout, "it under the terms of the GNU General Public License as published by\n");
+ fprintf (stdout, "the Free Software Foundation; either version 2 of the License, or\n");
+ fprintf (stdout, "(at your option) any later version.\n");
+ fprintf (stdout, "\nUsage: xdvipdfmx [options] xdvfile\n");
+ fprintf (stdout, "-c \t\tIgnore color specials (for B&W printing)\n");
+ fprintf (stdout, "-d number\tSet PDF decimal digits (0-5) [2]\n");
+ fprintf (stdout, "-f filename\tSet font map file name [cid-x.map]\n");
+ fprintf (stdout, "-g dimension\tAnnotation \"grow\" amount [0.0in]\n");
+ fprintf (stdout, "-h \t\tShow this help message\n");
+ fprintf (stdout, "-l \t\tLandscape mode\n");
+ fprintf (stdout, "-m number\tSet additional magnification\n");
+ fprintf (stdout, "-o filename\tSet output file name [dvifile.pdf]\n");
+ fprintf (stdout, "-p papersize\tSet papersize [a4]\n");
+ fprintf (stdout, "-q \t\tBe quiet\n");
+ fprintf (stdout, "-r resolution\tSet resolution (in DPI) for raster fonts [600]\n");
+ fprintf (stdout, "-s pages\tSelect page ranges (-)\n");
+ fprintf (stdout, "-t \t\tEmbed thumbnail images of PNG format [dvifile.1] \n");
+ fprintf (stdout, "-x dimension\tSet horizontal offset [1.0in]\n");
+ fprintf (stdout, "-y dimension\tSet vertical offset [1.0in]\n");
+ fprintf (stdout, "-z number \tSet zlib compression level (0-9) [9]\n");
+
+ fprintf (stdout, "-v \t\tBe verbose\n");
+ fprintf (stdout, "-vv\t\tBe more verbose\n");
+ fprintf (stdout, "-C number\tSpecify miscellaneous option flags [0]:\n");
+ fprintf (stdout, "\t\t 0x0001 reserved\n");
+ fprintf (stdout, "\t\t 0x0002 Use semi-transparent filling for tpic shading command,\n");
+ fprintf (stdout, "\t\t\t instead of opaque gray color. (requires PDF 1.4)\n");
+ fprintf (stdout, "\t\t 0x0004 Treat all CIDFont as fixed-pitch font.\n");
+ fprintf (stdout, "\t\t 0x0008 Do not replace duplicate fontmap entries.\n");
+ fprintf (stdout, "\t\tPositive values are always ORed with previously given flags.\n");
+ fprintf (stdout, "\t\tAnd negative values replace old values.\n");
+ fprintf (stdout, "-D template\tPS->PDF conversion command line template [none]\n");
+ fprintf (stdout, "-E \t\tAlways try to embed fonts, regardless of licensing flags.\n");
+ fprintf (stdout, "-I number\tImage cache life in hours [-2]\n");
+ fprintf (stdout, " \t 0: erase all old images and leave new images\n");
+ fprintf (stdout, " \t-1: erase all old images and also erase new images\n");
+ fprintf (stdout, " \t-2: ignore image cache\n");
+ fprintf (stdout, "-K number\tEncryption key length [40]\n");
+ fprintf (stdout, "-O number\tSet maximum depth of open bookmark items [0]\n");
+ fprintf (stdout, "-P number\tSet permission flags for PDF encryption [0x003C]\n");
+ fprintf (stdout, "-S \t\tEnable PDF encryption\n");
+ fprintf (stdout, "-V number\tSet PDF minor version [4]\n");
+ fprintf (stdout, "\nAll dimensions entered on the command line are \"true\" TeX dimensions.\n");
+ fprintf (stdout, "Argument of \"-s\" lists physical page ranges separated by commas, e.g., \"-s 1-3,5-6\"\n");
+ fprintf (stdout, "Papersize is specified by paper format (e.g., \"a4\") or by w<unit>,h<unit> (e.g., \"20cm,30cm\").\n");
+
+ exit(exit_code);
+}
+
+
+static int
+read_length (double *vp, const char **pp, const char *endptr)
+{
+ char *q;
+ const char *p = *pp;
+ double v, u = 1.0;
+ const char *_ukeys[] = {
+#define K_UNIT__PT 0
+#define K_UNIT__IN 1
+#define K_UNIT__CM 2
+#define K_UNIT__MM 3
+#define K_UNIT__BP 4
+ "pt", "in", "cm", "mm", "bp",
+ NULL
+ };
+ int k, error = 0;
+
+ q = parse_float_decimal(&p, endptr);
+ if (!q) {
+ *vp = 0.0; *pp = p;
+ return -1;
+ }
+
+ v = atof(q);
+ RELEASE(q);
+
+ skip_white(&p, endptr);
+ q = parse_c_ident(&p, endptr);
+ if (q) {
+ char *qq = q;
+ if (strlen(q) >= strlen("true") &&
+ !memcmp(q, "true", strlen("true"))) {
+ q += strlen("true"); /* just skip "true" */
+ }
+ if (strlen(q) == 0) {
+ RELEASE(qq);
+ skip_white(&p, endptr);
+ qq = q = parse_c_ident(&p, endptr);
+ }
+ if (q) {
+ for (k = 0; _ukeys[k] && strcmp(_ukeys[k], q); k++);
+ switch (k) {
+ case K_UNIT__PT: u *= 72.0 / 72.27; break;
+ case K_UNIT__IN: u *= 72.0; break;
+ case K_UNIT__CM: u *= 72.0 / 2.54 ; break;
+ case K_UNIT__MM: u *= 72.0 / 25.4 ; break;
+ case K_UNIT__BP: u *= 1.0 ; break;
+ default:
+ WARN("Unknown unit of measure: %s", q);
+ error = -1;
+ break;
+ }
+ RELEASE(qq);
+ }
+ else {
+ WARN("Missing unit of measure after \"true\"");
+ error = -1;
+ }
+ }
+
+ *vp = v * u; *pp = p;
+ return error;
+}
+
+static void
+select_paper (const char *paperspec)
+{
+ const struct paper *pi;
+ int error = 0;
+
+ pi = paperinfo(paperspec);
+ if (pi && papername(pi)) {
+ paper_width = paperpswidth (pi);
+ paper_height = paperpsheight(pi);
+ } else {
+ const char *p = paperspec, *endptr, *comma;
+ comma = strchr(p, ',');
+ endptr = p + strlen(p);
+ if (!comma)
+ ERROR("Unrecognized paper format: %s", paperspec);
+ error = read_length(&paper_width, &p, comma);
+ p = comma + 1;
+ error = read_length(&paper_height, &p, endptr);
+ }
+ if (error || paper_width <= 0.0 || paper_height <= 0.0)
+ ERROR("Invalid paper size: %s (%.2fx%.2f)", paperspec, paper_width, paper_height);
+}
+
+struct page_range
+{
+ long first, last;
+} *page_ranges = NULL;
+
+int num_page_ranges = 0;
+int max_page_ranges = 0;
+
+static void
+select_pages (const char *pagespec)
+{
+ char *q;
+ const char *p = pagespec;
+
+ while (*p != '\0') {
+ /* Enlarge page range table if necessary */
+ if (num_page_ranges >= max_page_ranges) {
+ max_page_ranges += 4;
+ page_ranges = RENEW(page_ranges, max_page_ranges, struct page_range);
+ }
+
+ page_ranges[num_page_ranges].first = 0;
+ page_ranges[num_page_ranges].last = 0;
+
+ for ( ; *p && isspace(*p); p++);
+ q = parse_unsigned(&p, p + strlen(p)); /* Can't be signed. */
+ if (q) { /* '-' is allowed here */
+ page_ranges[num_page_ranges].first = atoi(q) - 1;
+ page_ranges[num_page_ranges].last = page_ranges[num_page_ranges].first;
+ RELEASE(q);
+ }
+ for ( ; *p && isspace(*p); p++);
+
+ if (*p == '-') {
+ for (++p; *p && isspace(*p); p++);
+ page_ranges[num_page_ranges].last = -1;
+ if (*p) {
+ q = parse_unsigned(&p, p + strlen(p));
+ if (q) {
+ page_ranges[num_page_ranges].last = atoi(q) - 1;
+ RELEASE(q);
+ }
+ for ( ; *p && isspace(*p); p++);
+ }
+ } else {
+ page_ranges[num_page_ranges].last = page_ranges[num_page_ranges].first;
+ }
+
+ num_page_ranges++;
+
+ if (*p == ',')
+ p++;
+ else {
+ for ( ; *p && isspace(*p); p++);
+ if (*p)
+ ERROR("Bad page range specification: %s", p);
+ }
+ }
+ return;
+}
+
+#define POP_ARG() {argv += 1; argc -= 1;}
+/* It doesn't work as expected (due to dvi filename). */
+#define CHECK_ARG(n,m) if (argc < (n) + 1) {\
+ fprintf (stderr, "\nMissing %s after \"-%c\".\n", (m), *flag);\
+ usage(1);\
+}
+
+static void
+set_verbose (int argc, char *argv[])
+{
+ while (argc > 0 && *argv[0] == '-') {
+ char *flag;
+
+ for (flag = argv[0] + 1; *flag != 0; flag++) {
+ if (*flag == 'q')
+ really_quiet++;
+ if (*flag == 'v')
+ verbose++;
+ }
+ POP_ARG();
+ }
+
+ if (!really_quiet) {
+ int i;
+
+ for (i = 0; i < verbose; i++) {
+ dvi_set_verbose();
+ pdf_dev_set_verbose();
+ pdf_doc_set_verbose();
+ pdf_enc_set_verbose();
+ pdf_obj_set_verbose();
+ pdf_fontmap_set_verbose();
+ dpx_file_set_verbose();
+ }
+ }
+}
+
+
+static void
+do_args (int argc, char *argv[])
+{
+ while (argc > 0 && *argv[0] == '-') {
+ char *flag, *nextptr;
+ const char *nnextptr;
+
+ for (flag = argv[0] + 1; *flag != 0; flag++) {
+ switch (*flag) {
+ case 'D':
+ CHECK_ARG(1, "PS->PDF conversion command line template");
+ set_distiller_template(argv[1]);
+ POP_ARG();
+ break;
+ case 'r':
+ CHECK_ARG(1, "bitmap font dpi");
+ font_dpi = atoi(argv[1]);
+ if (font_dpi <= 0)
+ ERROR("Invalid bitmap font dpi specified: %s", argv[1]);
+ POP_ARG();
+ break;
+ case 'm':
+ CHECK_ARG(1, "magnification value");
+ mag = strtod(argv[1], &nextptr);
+ if (mag < 0.0 || nextptr == argv[1])
+ ERROR("Invalid magnification specifiied: %s", argv[1]);
+ POP_ARG();
+ break;
+ case 'g':
+ CHECK_ARG(1, "annotation \"grow\" amount");
+ nnextptr = nextptr = argv[1];
+ read_length(&annot_grow, &nnextptr, nextptr + strlen(nextptr));
+ POP_ARG();
+ break;
+ case 'x':
+ CHECK_ARG(1, "horizontal offset value");
+ nnextptr = nextptr = argv[1];
+ read_length(&x_offset, &nnextptr, nextptr + strlen(nextptr));
+ POP_ARG();
+ break;
+ case 'y':
+ CHECK_ARG(1, "vertical offset value");
+ nnextptr = nextptr = argv[1];
+ read_length(&y_offset, &nnextptr, nextptr + strlen(nextptr));
+ POP_ARG();
+ break;
+ case 'o':
+ CHECK_ARG(1, "output file name");
+ pdf_filename = NEW (strlen(argv[1])+1,char);
+ strcpy(pdf_filename, argv[1]);
+ POP_ARG();
+ break;
+ case 's':
+ CHECK_ARG(1, "page selection specification");
+ select_pages(argv[1]);
+ POP_ARG();
+ break;
+ case 't':
+ pdf_doc_enable_manual_thumbnails();
+ break;
+ case 'p':
+ CHECK_ARG(1, "paper format/size");
+ select_paper(argv[1]);
+ POP_ARG();
+ break;
+ case 'c':
+ ignore_colors = 1;
+ break;
+ case 'l':
+ landscape_mode = 1;
+ break;
+ case 'f':
+ CHECK_ARG(1, "fontmap file name");
+ if (opt_flags & OPT_FONTMAP_FIRST_MATCH)
+ pdf_load_fontmap_file(argv[1], FONTMAP_RMODE_APPEND);
+ else
+ pdf_load_fontmap_file(argv[1], FONTMAP_RMODE_REPLACE);
+ POP_ARG();
+ break;
+ case 'i':
+ CHECK_ARG(1, "subsidiary config file");
+ read_config_file(argv[1]);
+ POP_ARG();
+ break;
+ case 'e':
+ WARN("dvipdfm \"-e\" option not supported.");
+ break;
+ case 'q': case 'v':
+ break;
+ case 'V':
+ {
+ int ver_minor;
+
+ if (isdigit(*(flag+1))) {
+ flag++;
+ ver_minor = atoi(flag);
+ } else {
+ CHECK_ARG(1, "PDF minor version number");
+ ver_minor = atoi(argv[1]);
+ POP_ARG();
+ }
+ if (ver_minor < PDF_VERSION_MIN) {
+ WARN("PDF version 1.%d not supported. Using PDF 1.%d instead.",
+ ver_minor, PDF_VERSION_MIN);
+ ver_minor = PDF_VERSION_MIN;
+ } else if (ver_minor > PDF_VERSION_MAX) {
+ WARN("PDF version 1.%d not supported. Using PDF 1.%d instead.",
+ ver_minor, PDF_VERSION_MAX);
+ ver_minor = PDF_VERSION_MAX;
+ }
+ pdf_set_version((unsigned) ver_minor);
+ }
+ break;
+ case 'z':
+ {
+ int level;
+
+ if (isdigit(*(flag+1))) {
+ flag++;
+ level = atoi(flag);
+ } else {
+ CHECK_ARG(1, "compression level");
+ level = atoi(argv[1]);
+ POP_ARG();
+ }
+ pdf_set_compression(level);
+ }
+ break;
+ case 'd':
+ if (isdigit(*(flag+1))) {
+ flag++;
+ pdfdecimaldigits = atoi(flag);
+ } else {
+ CHECK_ARG(1, "number of fractional digits");
+ pdfdecimaldigits = atoi(argv[1]);
+ POP_ARG();
+ }
+ break;
+ case 'I':
+ CHECK_ARG(1, "image cache life in hours");
+ image_cache_life = atoi(argv[1]);
+ POP_ARG();
+ break;
+ case 'S':
+ do_encryption = 1;
+ break;
+ case 'K':
+ CHECK_ARG(1, "encryption key length");
+ key_bits = (unsigned) atoi(argv[1]);
+ if (key_bits < 40 || key_bits > 128 || (key_bits & 0x7))
+ ERROR("Invalid encryption key length specified: %s", argv[1]);
+ POP_ARG();
+ break;
+ case 'P':
+ CHECK_ARG(1, "encryption permission flag");
+ permission = (unsigned) strtoul(argv[1], &nextptr, 0);
+ if (nextptr == argv[1])
+ ERROR("Invalid encryption permission flag: %s", argv[1]);
+ POP_ARG();
+ break;
+ case 'O':
+ /* Bookmark open level */
+ CHECK_ARG(1, "bookmark open level");
+ bookmark_open = atoi(argv[1]);
+ POP_ARG();
+ break;
+ case 'M':
+ mp_mode = 1;
+ break;
+ case 'C':
+ CHECK_ARG(1, "a number");
+ {
+ long flags;
+
+ flags = (unsigned) strtol(argv[1], &nextptr, 0);
+ if (nextptr == argv[1])
+ ERROR("Invalid flag: %s", argv[1]);
+ if (flags < 0)
+ opt_flags = -flags;
+ else
+ opt_flags |= flags;
+ }
+ POP_ARG();
+ break;
+ case 'E':
+ always_embed = 1;
+ break;
+ case 'h':
+ usage(0);
+ break;
+ default:
+ fprintf (stderr, "Unknown option in \"%s\"", flag);
+ usage(1);
+ break;
+ }
+ }
+ POP_ARG();
+ }
+
+ if (argc > 1) {
+ fprintf(stderr, "Multiple dvi filenames?");
+ usage(1);
+ } else if (argc > 0) {
+ /*
+ * The only legitimate way to have argc == 0 here is
+ * do_args was called from config file. In that case, there is
+ * no dvi file name. Check for that case .
+ */
+ dvi_filename = NEW(strlen(argv[0]) + 5, char); /* space to append .dvi */
+ strcpy(dvi_filename, argv[0]);
+ }
+}
+
+static void
+cleanup (void)
+{
+ if (dvi_filename)
+ RELEASE(dvi_filename);
+ if (pdf_filename)
+ RELEASE(pdf_filename);
+ if (page_ranges)
+ RELEASE(page_ranges);
+}
+
+static void
+read_config_file (const char *config)
+{
+ const char *start, *end;
+ char *option;
+ FILE *fp;
+
+ fp = DPXFOPEN(config, DPX_RES_TYPE_TEXT);
+ if (!fp) {
+ WARN("Could not open config file \"%s\".", config);
+ return;
+ }
+ while ((start = mfgets (work_buffer, WORK_BUFFER_SIZE, fp)) != NULL) {
+ char *argv[2];
+ int argc;
+
+ argc = 0;
+ end = work_buffer + strlen(work_buffer);
+ skip_white (&start, end);
+ if (start >= end)
+ continue;
+ /* Build up an argument list as if it were passed on the command
+ line */
+ if ((option = parse_ident (&start, end))) {
+ argc = 1;
+ argv[0] = NEW (strlen(option)+2, char);
+ strcpy (argv[0]+1, option);
+ RELEASE (option);
+ *argv[0] = '-';
+ skip_white (&start, end);
+ if (start < end) {
+ argc += 1;
+ if (*start == '"') {
+ argv[1] = parse_c_string (&start, end);
+ }
+ else
+ argv[1] = parse_ident (&start, end);
+ }
+ }
+ do_args (argc, argv);
+ while (argc > 0) {
+ RELEASE (argv[--argc]);
+ }
+ }
+ if (fp)
+ MFCLOSE(fp);
+}
+
+static void
+system_default (void)
+{
+ if (systempapername() != NULL) {
+ select_paper(systempapername());
+ } else if (defaultpapername() != NULL) {
+ select_paper(defaultpapername());
+ }
+}
+
+void
+error_cleanup (void)
+{
+ pdf_error_cleanup();
+ if (pdf_filename) {
+ remove(pdf_filename);
+ fprintf(stderr, "\nOutput file removed.\n");
+ }
+}
+
+#define SWAP(v1,v2) do {\
+ double _tmp = (v1);\
+ (v1) = (v2);\
+ (v2) = _tmp;\
+ } while (0)
+
+static void
+do_dvi_pages (void)
+{
+ long page_no, page_count, i, step;
+ double page_width, page_height;
+ double init_paper_width, init_paper_height;
+ pdf_rect mediabox;
+
+ spc_exec_at_begin_document();
+
+ if (num_page_ranges == 0) {
+ if (!page_ranges) {
+ page_ranges = NEW(1, struct page_range);
+ max_page_ranges = 1;
+ }
+ page_ranges[0].first = 0;
+ page_ranges[0].last = -1; /* last page */
+ num_page_ranges = 1;
+ }
+
+ init_paper_width = page_width = paper_width;
+ init_paper_height = page_height = paper_height;
+ page_count = 0;
+
+ mediabox.llx = 0.0;
+ mediabox.lly = 0.0;
+ mediabox.urx = paper_width;
+ mediabox.ury = paper_height;
+
+ pdf_doc_set_mediabox(0, &mediabox); /* Root node */
+
+ for (i = 0; i < num_page_ranges && dvi_npages() > 0; i++) {
+ if (page_ranges[i].last < 0)
+ page_ranges[i].last += dvi_npages();
+
+ step = (page_ranges[i].first <= page_ranges[i].last) ? 1 : -1;
+ page_no = page_ranges[i].first;
+ while (dvi_npages() > 0) {
+ if (page_no < dvi_npages()) {
+ double w, h, xo, yo;
+ char lm;
+
+ /* Users want to change page size even after page is started! */
+ page_width = paper_width; page_height = paper_height;
+ w = page_width; h = page_height; lm = landscape_mode;
+ xo = x_offset; yo = y_offset;
+ dvi_scan_specials(page_no, &w, &h, &xo, &yo, &lm, NULL, NULL, NULL, NULL, NULL, NULL);
+ if (lm != landscape_mode) {
+ SWAP(w, h);
+ landscape_mode = lm;
+ }
+ if (page_width != w || page_height != h) {
+ page_width = w;
+ page_height = h;
+ }
+ if (x_offset != xo || y_offset != yo) {
+ x_offset = xo;
+ y_offset = yo;
+ }
+ if (page_width != init_paper_width ||
+ page_height != init_paper_height) {
+ mediabox.llx = 0.0;
+ mediabox.lly = 0.0;
+ mediabox.urx = page_width;
+ mediabox.ury = page_height;
+ pdf_doc_set_mediabox(page_count+1, &mediabox);
+ }
+ dvi_do_page(page_no,
+ page_width, page_height, x_offset, y_offset);
+ page_count++;
+ }
+
+ if (step > 0 &&
+ page_no >= page_ranges[i].last)
+ break;
+ else if (step < 0 &&
+ page_no <= page_ranges[i].last)
+ break;
+ else {
+ page_no += step;
+ }
+ }
+ }
+
+ if (page_count < 1) {
+ ERROR("No pages fall in range!");
+ }
+
+ spc_exec_at_end_document();
+}
+
+static void
+do_mps_pages (void)
+{
+ FILE *fp;
+
+ /* _FIXME_ */
+ fp = MFOPEN(dvi_filename, FOPEN_RBIN_MODE);
+ if (fp) {
+ mps_do_page(fp);
+ MFCLOSE(fp);
+ } else {
+ int i, page_no, step, page_count = 0;
+ char *filename;
+ /* Process filename.1, filename.2,... */
+ filename = NEW(strlen(dvi_filename) + 16 + 1, char);
+ for (i = 0; i < num_page_ranges; i++) {
+ if (page_ranges[i].last < 0)
+ ERROR("Invalid page number for MPS input: -1");
+
+ step = (page_ranges[i].first <= page_ranges[i].last) ? 1 : -1;
+ page_no = page_ranges[i].first;
+ for (;;) {
+ sprintf(filename, "%s.%d", dvi_filename, page_no + 1);
+ fp = MFOPEN(filename, FOPEN_RBIN_MODE);
+ if (fp) {
+ MESG("[%d<%s>", page_no + 1, filename);
+ mps_do_page(fp);
+ page_count++;
+ MESG("]");
+ MFCLOSE(fp);
+ }
+ if (step > 0 &&
+ page_no >= page_ranges[i].last)
+ break;
+ else if (step < 0 &&
+ page_no <= page_ranges[i].last)
+ break;
+ else {
+ page_no += step;
+ }
+ }
+ }
+ RELEASE(filename);
+ if (page_count == 0)
+ ERROR("No page output for \"%s\".", dvi_filename);
+ }
+}
+
+
+/* TODO: MetaPost mode */
+#if defined(MIKTEX)
+# define main Main
+#endif
+int CDECL
+main (int argc, char *argv[])
+{
+ double dvi2pts;
+
+ const char *av0 = xbasename(argv[0]);
+ if (STRN_CMP(av0, "ebb", 3) == 0)
+ return extractbb(argc, argv, EBB_OUTPUT);
+ else if (STRN_CMP(av0, "xbb", 3) == 0 || STRN_CMP(av0, "extractbb", 9) == 0)
+ return extractbb(argc, argv, XBB_OUTPUT);
+
+#ifdef MIKTEX
+ miktex_initialize();
+#else
+ kpse_set_program_name(argv[0], "dvipdfmx"); /* we pretend to be dvipdfmx for kpse purposes */
+#ifdef WIN32
+ texlive_gs_init ();
+#endif
+#endif
+
+ paperinit();
+ system_default();
+
+ argv+=1;
+ argc-=1;
+
+ set_verbose(argc, argv);
+
+ pdf_init_fontmaps(); /* This must come before parsing options... */
+
+ read_config_file(DPX_CONFIG_FILE);
+
+ do_args (argc, argv);
+
+ if (really_quiet)
+ shut_up(really_quiet);
+
+#ifndef MIKTEX
+ kpse_init_prog("", font_dpi, NULL, NULL);
+ kpse_set_program_enabled(kpse_pk_format, true, kpse_src_texmf_cnf);
+#endif
+ pdf_font_set_dpi(font_dpi);
+ dpx_delete_old_cache(image_cache_life);
+
+ if (dvi_filename == NULL) {
+ if (verbose)
+ MESG("No dvi filename specified, reading standard input.\n");
+ if (pdf_filename == NULL)
+ if (verbose)
+ MESG("No pdf filename specified, writing to standard output.\n");
+ }
+
+ if (pdf_filename == NULL && dvi_filename != NULL)
+ set_default_pdf_filename();
+
+ pdf_enc_compute_id_string(dvi_filename, pdf_filename);
+ if (do_encryption) {
+ pdf_enc_set_passwd(key_bits, permission, NULL, NULL);
+ if (key_bits > 40 && pdf_get_version() < 4)
+ pdf_set_version(4);
+ }
+
+ if (mp_mode) {
+ x_offset = 0.0;
+ y_offset = 0.0;
+ dvi2pts = 0.01; /* dvi2pts controls accuracy. */
+ } else {
+ unsigned ver_minor = 0;
+ char owner_pw[MAX_PWD_LEN], user_pw[MAX_PWD_LEN];
+ /* Dependency between DVI and PDF side is rather complicated... */
+ dvi2pts = dvi_init(dvi_filename, mag);
+ if (dvi2pts == 0.0)
+ ERROR("dvi_init() failed!");
+
+ pdf_doc_set_creator(dvi_comment());
+
+ if (do_encryption)
+ /* command line takes precedence */
+ dvi_scan_specials(0, &paper_width, &paper_height, &x_offset, &y_offset, &landscape_mode,
+ &ver_minor, NULL, NULL, NULL, NULL, NULL);
+ else {
+ dvi_scan_specials(0, &paper_width, &paper_height, &x_offset, &y_offset, &landscape_mode,
+ &ver_minor, &do_encryption, &key_bits, &permission, owner_pw, user_pw);
+ if (do_encryption) {
+ if (key_bits < 40 || key_bits > 128 || (key_bits & 0x7))
+ ERROR("Invalid encryption key length specified: %u", key_bits);
+ else if (key_bits > 40 && pdf_get_version() < 4)
+ ERROR("Chosen key length requires at least PDF 1.4. "
+ "Use \"-V 4\" to change.");
+ do_encryption = 1;
+ pdf_enc_set_passwd(key_bits, permission, owner_pw, user_pw);
+ }
+ }
+ if (ver_minor >= PDF_VERSION_MIN && ver_minor <= PDF_VERSION_MAX) {
+ pdf_set_version(ver_minor);
+ }
+ if (landscape_mode) {
+ SWAP(paper_width, paper_height);
+ }
+ }
+
+ MESG("%s -> %s\n", dvi_filename == NULL ? "stdin" : dvi_filename,
+ pdf_filename == NULL ? "stdout" : pdf_filename);
+
+ pdf_files_init();
+
+ /* Set default paper size here so that all page's can inherite it.
+ * annot_grow: Margin of annotation.
+ * bookmark_open: Miximal depth of open bookmarks.
+ */
+ pdf_open_document(pdf_filename, do_encryption,
+ paper_width, paper_height, annot_grow, bookmark_open);
+
+ /* Ignore_colors placed here since
+ * they are considered as device's capacity.
+ */
+ pdf_init_device(dvi2pts, pdfdecimaldigits, ignore_colors);
+
+ if (opt_flags & OPT_CIDFONT_FIXEDPITCH)
+ CIDFont_set_flags(CIDFONT_FORCE_FIXEDPITCH);
+
+ /* Please move this to spc_init_specials(). */
+ if (opt_flags & OPT_TPIC_TRANSPARENT_FILL)
+ tpic_set_fill_mode(1);
+
+ if (mp_mode) {
+ do_mps_pages();
+ } else {
+ do_dvi_pages();
+ }
+
+ pdf_files_close();
+
+ /* Order of close... */
+ pdf_close_device ();
+ /* pdf_close_document flushes XObject (image) and other resources. */
+ pdf_close_document();
+
+ pdf_close_fontmaps(); /* pdf_font may depend on fontmap. */
+
+ if (!mp_mode)
+ dvi_close();
+
+ MESG("\n");
+ cleanup();
+
+ paperdone();
+#ifdef MIKTEX
+ miktex_uninitialize ();
+#endif
+
+ return 0;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/epdf.c b/Build/source/texk/dvipdf-x/xsrc/epdf.c
new file mode 100644
index 00000000000..73a8ec21f63
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/epdf.c
@@ -0,0 +1,906 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2007-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+/*
+ * Concatinating content streams are only supported for streams that only uses
+ * single FlateDecode filter, i.e.,
+ *
+ * /Filter /FlateDecode or /Filter [/FlateDecode]
+ *
+ * TrimBox, BleedBox, ArtBox, Rotate ...
+ */
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "system.h"
+#include "mem.h"
+#include "mfileio.h"
+#include "error.h"
+
+#include "pdfobj.h"
+#include "pdfdev.h"
+#include "pdfdraw.h"
+#include "pdfparse.h"
+
+#include "pdfximage.h"
+
+#include "pdfdoc.h"
+
+#include "epdf.h"
+
+#if HAVE_ZLIB
+#include <zlib.h>
+static int add_stream_flate (pdf_obj *dst, const void *data, long len);
+#endif
+static int concat_stream (pdf_obj *dst, pdf_obj *src);
+
+static int rect_equal (pdf_obj *rect1, pdf_obj *rect2);
+
+/*
+ * From PDFReference15_v6.pdf (p.119 and p.834)
+ *
+ * MediaBox rectangle (Required; inheritable)
+ *
+ * The media box defines the boundaries of the physical medium on which the
+ * page is to be printed. It may include any extended area surrounding the
+ * finished page for bleed, printing marks, or other such purposes. It may
+ * also include areas close to the edges of the medium that cannot be marked
+ * because of physical limitations of the output device. Content falling
+ * outside this boundary can safely be discarded without affecting the
+ * meaning of the PDF file.
+ *
+ * CropBox rectangle (Optional; inheritable)
+ *
+ * The crop box defines the region to which the contents of the page are to be
+ * clipped (cropped) when displayed or printed. Unlike the other boxes, the
+ * crop box has no defined meaning in terms of physical page geometry or
+ * intended use; it merely imposes clipping on the page contents. However,
+ * in the absence of additional information (such as imposition instructions
+ * specified in a JDF or PJTF job ticket), the crop box will determine how
+ * the page’s contents are to be positioned on the output medium. The default
+ * value is the page’s media box.
+ *
+ * BleedBox rectangle (Optional; PDF 1.3)
+ *
+ * The bleed box (PDF 1.3) defines the region to which the contents of the
+ * page should be clipped when output in a production environment. This may
+ * include any extra “bleed area” needed to accommodate the physical
+ * limitations of cutting, folding, and trimming equipment. The actual printed
+ * page may include printing marks that fall outside the bleed box.
+ * The default value is the page’s crop box.
+ *
+ * TrimBox rectangle (Optional; PDF 1.3)
+ *
+ * The trim box (PDF 1.3) defines the intended dimensions of the finished page
+ * after trimming. It may be smaller than the media box, to allow for
+ * production-related content such as printing instructions, cut marks, or
+ * color bars. The default value is the page’s crop box.
+ *
+ * ArtBox rectangle (Optional; PDF 1.3)
+ *
+ * The art box (PDF 1.3) defines the extent of the page’s meaningful content
+ * (including potential white space) as intended by the page’s creator.
+ * The default value is the page’s crop box.
+ *
+ * Rotate integer (Optional; inheritable)
+ *
+ * The number of degrees by which the page should be rotated clockwise when
+ * displayed or printed. The value must be a multiple of 90. Default value: 0.
+ */
+
+static int
+rect_equal (pdf_obj *rect1, pdf_obj *rect2)
+{
+ int i;
+
+ if (!rect1 || !rect2)
+ return 0;
+ for (i = 0; i < 4; i++) {
+ if (pdf_number_value(pdf_get_array(rect1, i)) !=
+ pdf_number_value(pdf_get_array(rect2, i)))
+ return 0;
+ }
+
+ return 1;
+}
+
+static pdf_obj*
+pdf_get_page_obj (pdf_file *pf, long page_no,
+ pdf_obj **ret_bbox, pdf_obj **ret_resources)
+{
+ pdf_obj *page_tree;
+ pdf_obj *bbox = NULL, *resources = NULL, *rotate = NULL;
+ long page_idx;
+
+ /*
+ * Get Page Tree.
+ */
+ page_tree = NULL;
+ {
+ pdf_obj *trailer, *catalog;
+ pdf_obj *markinfo, *tmp;
+
+ trailer = pdf_file_get_trailer(pf);
+
+ if (pdf_lookup_dict(trailer, "Encrypt")) {
+ WARN("This PDF document is encrypted.");
+ pdf_release_obj(trailer);
+ return NULL;
+ }
+
+ catalog = pdf_deref_obj(pdf_lookup_dict(trailer, "Root"));
+ if (!PDF_OBJ_DICTTYPE(catalog)) {
+ WARN("Can't read document catalog.");
+ pdf_release_obj(trailer);
+ if (catalog)
+ pdf_release_obj(catalog);
+ return NULL;
+ }
+ pdf_release_obj(trailer);
+
+ markinfo = pdf_deref_obj(pdf_lookup_dict(catalog, "MarkInfo"));
+ if (markinfo) {
+ tmp = pdf_lookup_dict(markinfo, "Marked");
+ if (PDF_OBJ_BOOLEANTYPE(tmp) && pdf_boolean_value(tmp))
+ WARN("File contains tagged PDF. Ignoring tags.");
+ pdf_release_obj(markinfo);
+ }
+
+ page_tree = pdf_deref_obj(pdf_lookup_dict(catalog, "Pages"));
+ pdf_release_obj(catalog);
+ }
+ if (!page_tree) {
+ WARN("Page tree not found.");
+ return NULL;
+ }
+
+ /*
+ * Negative page numbers are counted from the back.
+ */
+ {
+ long count = pdf_number_value(pdf_lookup_dict(page_tree, "Count"));
+ page_idx = page_no + (page_no >= 0 ? -1 : count);
+ if (page_idx < 0 || page_idx >= count) {
+ WARN("Page %ld does not exist.", page_no);
+ pdf_release_obj(page_tree);
+ return NULL;
+ }
+ page_no = page_idx+1;
+ }
+
+ /*
+ * Seek correct page. Get Media/Crop Box.
+ * Media box and resources can be inherited.
+ */
+ {
+ pdf_obj *kids_ref, *kids;
+ pdf_obj *crop_box = NULL;
+ pdf_obj *tmp;
+
+ tmp = pdf_lookup_dict(page_tree, "Resources");
+ resources = tmp ? pdf_deref_obj(tmp) : pdf_new_dict();
+
+ while (1) {
+ long kids_length, i;
+
+ if ((tmp = pdf_deref_obj(pdf_lookup_dict(page_tree, "MediaBox")))) {
+ if (bbox)
+ pdf_release_obj(bbox);
+ bbox = tmp;
+ }
+ if ((tmp = pdf_deref_obj(pdf_lookup_dict(page_tree, "BleedBox")))) {
+ if (!rect_equal(tmp, bbox)) {
+ if (bbox)
+ pdf_release_obj(bbox);
+ bbox = tmp;
+ } else
+ pdf_release_obj(tmp);
+ }
+ if ((tmp = pdf_deref_obj(pdf_lookup_dict(page_tree, "TrimBox")))) {
+ if (!rect_equal(tmp, bbox)) {
+ if (bbox)
+ pdf_release_obj(bbox);
+ bbox = tmp;
+ } else
+ pdf_release_obj(tmp);
+ }
+ if ((tmp = pdf_deref_obj(pdf_lookup_dict(page_tree, "ArtBox")))) {
+ if (!rect_equal(tmp, bbox)) {
+ if (bbox)
+ pdf_release_obj(bbox);
+ bbox = tmp;
+ } else
+ pdf_release_obj(tmp);
+ }
+ if ((tmp = pdf_deref_obj(pdf_lookup_dict(page_tree, "CropBox")))) {
+ if (crop_box)
+ pdf_release_obj(crop_box);
+ crop_box = tmp;
+ }
+ if ((tmp = pdf_deref_obj(pdf_lookup_dict(page_tree, "Rotate")))) {
+ if (rotate)
+ pdf_release_obj(rotate);
+ rotate = tmp;
+ }
+ if ((tmp = pdf_deref_obj(pdf_lookup_dict(page_tree, "Resources")))) {
+#if 0
+ pdf_merge_dict(tmp, resources);
+#endif
+ if (resources)
+ pdf_release_obj(resources);
+ resources = tmp;
+ }
+
+ kids_ref = pdf_lookup_dict(page_tree, "Kids");
+ if (!kids_ref)
+ break;
+ kids = pdf_deref_obj(kids_ref);
+ kids_length = pdf_array_length(kids);
+
+ for (i = 0; i < kids_length; i++) {
+ long count;
+
+ pdf_release_obj(page_tree);
+ page_tree = pdf_deref_obj(pdf_get_array(kids, i));
+
+ tmp = pdf_deref_obj(pdf_lookup_dict(page_tree, "Count"));
+ if (tmp) {
+ /* Pages object */
+ count = pdf_number_value(tmp);
+ pdf_release_obj(tmp);
+ } else
+ /* Page object */
+ count = 1;
+
+ if (page_idx < count)
+ break;
+
+ page_idx -= count;
+ }
+
+ pdf_release_obj(kids);
+
+ if (i == kids_length) {
+ WARN("Page %ld not found! Broken PDF file?", page_no);
+ if (bbox)
+ pdf_release_obj(bbox);
+ if (crop_box)
+ pdf_release_obj(crop_box);
+ if (rotate)
+ pdf_release_obj(rotate);
+ pdf_release_obj(resources);
+ pdf_release_obj(page_tree);
+ return NULL;
+ }
+ }
+ if (crop_box) {
+ pdf_release_obj(bbox);
+ bbox = crop_box;
+ }
+ }
+
+ if (!bbox) {
+ WARN("No BoundingBox information available.");
+ pdf_release_obj(page_tree);
+ pdf_release_obj(resources);
+ if (rotate)
+ pdf_release_obj(rotate);
+ return NULL;
+ }
+
+ if (rotate) {
+ if (pdf_number_value(rotate) != 0.0)
+ WARN("<< /Rotate %d >> found. (Not supported yet)", (int)pdf_number_value(rotate));
+ pdf_release_obj(rotate);
+ rotate = NULL;
+ }
+
+ if (ret_bbox != NULL)
+ *ret_bbox = bbox;
+ if (ret_resources != NULL)
+ *ret_resources = resources;
+
+ return page_tree;
+}
+
+static pdf_obj*
+pdf_get_page_content (pdf_obj* page)
+{
+ pdf_obj *contents, *content_new;
+
+ contents = pdf_deref_obj(pdf_lookup_dict(page, "Contents"));
+ if (!contents)
+ return NULL;
+
+ if (pdf_obj_typeof(contents) == PDF_NULL) {
+ /* empty page */
+ pdf_release_obj(contents);
+ /* TODO: better don't include anything if the page is empty */
+ contents = pdf_new_stream(0);
+ } else if (PDF_OBJ_ARRAYTYPE(contents)) {
+ /*
+ * Concatenate all content streams.
+ */
+ pdf_obj *content_seg;
+ int idx = 0;
+ content_new = pdf_new_stream(STREAM_COMPRESS);
+ for (;;) {
+ content_seg = pdf_deref_obj(pdf_get_array(contents, idx));
+ if (!content_seg)
+ break;
+ else if (PDF_OBJ_NULLTYPE(content_seg)) {
+ /* Silently ignore. */
+ } else if (!PDF_OBJ_STREAMTYPE(content_seg)) {
+ WARN("Page content not a stream object. Broken PDF file?");
+ pdf_release_obj(content_seg);
+ pdf_release_obj(content_new);
+ pdf_release_obj(contents);
+ return NULL;
+ } else if (concat_stream(content_new, content_seg) < 0) {
+ WARN("Could not handle content stream with multiple segments.");
+ pdf_release_obj(content_seg);
+ pdf_release_obj(content_new);
+ pdf_release_obj(contents);
+ return NULL;
+ }
+ pdf_release_obj(content_seg);
+ idx++;
+ }
+ pdf_release_obj(contents);
+ contents = content_new;
+ } else {
+ if (!PDF_OBJ_STREAMTYPE(contents)) {
+ WARN("Page content not a stream object. Broken PDF file?");
+ pdf_release_obj(contents);
+ return NULL;
+ }
+ /* Flate the contents if necessary. */
+ content_new = pdf_new_stream(STREAM_COMPRESS);
+ if (concat_stream(content_new, contents) < 0) {
+ WARN("Could not handle a content stream.");
+ pdf_release_obj(contents);
+ pdf_release_obj(content_new);
+ return NULL;
+ }
+ pdf_release_obj(contents);
+ contents = content_new;
+ }
+
+ return contents;
+}
+
+int
+pdf_include_page (pdf_ximage *ximage, FILE *image_file)
+{
+ xform_info info;
+ pdf_obj *contents, *contents_dict;
+ pdf_obj *page_tree;
+ pdf_obj *matrix;
+ pdf_obj *bbox = NULL, *resources = NULL;
+ long page_no;
+ pdf_file *pf;
+ char *ident = pdf_ximage_get_ident(ximage);
+
+ pdf_ximage_init_form_info(&info);
+
+ pf = pdf_open(ident, image_file);
+ if (!pf)
+ return -1;
+
+ /*
+ * Get Page Tree.
+ */
+ page_no = pdf_ximage_get_page(ximage);
+ if (page_no == 0)
+ page_no = 1;
+
+ page_tree = pdf_get_page_obj(pf, page_no, &bbox, &resources);
+ if (page_tree == NULL) {
+ pdf_close(pf);
+ return -1;
+ }
+
+ if (bbox != NULL) {
+ pdf_obj *tmp;
+
+ tmp = pdf_deref_obj(pdf_get_array(bbox, 0));
+ info.bbox.llx = pdf_number_value(tmp);
+ pdf_release_obj(tmp);
+ tmp = pdf_deref_obj(pdf_get_array(bbox, 1));
+ info.bbox.lly = pdf_number_value(tmp);
+ pdf_release_obj(tmp);
+ tmp = pdf_deref_obj(pdf_get_array(bbox, 2));
+ info.bbox.urx = pdf_number_value(tmp);
+ pdf_release_obj(tmp);
+ tmp = pdf_deref_obj(pdf_get_array(bbox, 3));
+ info.bbox.ury = pdf_number_value(tmp);
+ pdf_release_obj(tmp);
+ }
+
+ /*
+ * Handle page content stream.
+ * page_tree is now set to the correct page.
+ */
+ contents = pdf_get_page_content(page_tree);
+ pdf_release_obj(page_tree);
+ if (contents == NULL) {
+ pdf_close(pf);
+ return -1;
+ }
+
+ {
+ pdf_obj *tmp;
+
+ tmp = pdf_import_object(resources);
+ pdf_release_obj(resources);
+ resources = tmp;
+ tmp = pdf_import_object(bbox);
+ pdf_release_obj(bbox);
+ bbox = tmp;
+ }
+
+ pdf_close(pf);
+
+ contents_dict = pdf_stream_dict(contents);
+ pdf_add_dict(contents_dict,
+ pdf_new_name("Type"),
+ pdf_new_name("XObject"));
+ pdf_add_dict(contents_dict,
+ pdf_new_name("Subtype"),
+ pdf_new_name("Form"));
+ pdf_add_dict(contents_dict,
+ pdf_new_name("FormType"),
+ pdf_new_number(1.0));
+
+ pdf_add_dict(contents_dict, pdf_new_name("BBox"), bbox);
+
+ matrix = pdf_new_array();
+ pdf_add_array(matrix, pdf_new_number(1.0));
+ pdf_add_array(matrix, pdf_new_number(0.0));
+ pdf_add_array(matrix, pdf_new_number(0.0));
+ pdf_add_array(matrix, pdf_new_number(1.0));
+ pdf_add_array(matrix, pdf_new_number(0.0));
+ pdf_add_array(matrix, pdf_new_number(0.0));
+
+ pdf_add_dict(contents_dict, pdf_new_name("Matrix"), matrix);
+
+ pdf_add_dict(contents_dict, pdf_new_name("Resources"), resources);
+
+ pdf_ximage_set_form(ximage, &info, contents);
+
+ return 0;
+}
+
+typedef enum {
+ OP_SETCOLOR = 1,
+ OP_CLOSEandCLIP = 2,
+ OP_CLIP = 3,
+ OP_CONCATMATRIX = 4,
+ OP_SETCOLORSPACE = 5,
+ OP_RECTANGLE = 6,
+ OP_CURVETO = 7,
+ OP_CLOSEPATH = 8,
+ OP_LINETO = 9,
+ OP_MOVETO = 10,
+ OP_NOOP = 11,
+ OP_GSAVE = 12,
+ OP_GRESTORE = 13,
+ OP_CURVETO1 = 14,
+ OP_CURVETO2 = 15,
+ OP_UNKNOWN = 16
+} pdf_opcode;
+
+static struct operator
+{
+ const char *token;
+ int opcode;
+} pdf_operators[] = {
+ {"SCN", OP_SETCOLOR},
+ {"b*", OP_CLOSEandCLIP},
+ {"B*", OP_CLIP},
+ {"cm", OP_CONCATMATRIX},
+ {"CS", OP_SETCOLORSPACE},
+ {"f*", 0},
+ {"gs", -1},
+ {"re", OP_RECTANGLE},
+ {"rg", -3},
+ {"RG", -3},
+ {"sc", OP_SETCOLOR},
+ {"SC", OP_SETCOLOR},
+ {"W*", OP_CLIP},
+ {"b", OP_CLOSEandCLIP},
+ {"B", OP_CLIP},
+ {"c", OP_CURVETO},
+ {"d", -2},
+ {"f", 0},
+ {"F", 0},
+ {"g", -1},
+ {"G", -1},
+ {"h", OP_CLOSEPATH},
+ {"i", -1},
+ {"j", -1},
+ {"J", -1},
+ {"k", -4},
+ {"K", -4},
+ {"l", OP_LINETO},
+ {"m", OP_MOVETO},
+ {"M", -1},
+ {"n", OP_NOOP},
+ {"q", OP_GSAVE},
+ {"Q", OP_GRESTORE},
+ {"s", OP_CLOSEandCLIP},
+ {"S", OP_CLIP},
+ {"v", OP_CURVETO1},
+ {"w", -1},
+ {"W", OP_CLIP},
+ {"y", OP_CURVETO2}
+};
+
+
+int
+pdf_copy_clip (FILE *image_file, int pageNo, double x_user, double y_user)
+{
+ pdf_obj *page_tree, *contents;
+ int depth = 0, top = -1;
+ const char *clip_path, *end_path;
+ char *save_path, *temp;
+ pdf_tmatrix M;
+ double stack[6];
+ pdf_file *pf;
+
+ pf = pdf_open(NULL, image_file);
+ if (!pf)
+ return -1;
+
+ pdf_dev_currentmatrix(&M);
+ pdf_invertmatrix(&M);
+ M.e += x_user; M.f += y_user;
+ page_tree = pdf_get_page_obj (pf, pageNo, NULL, NULL);
+ if (!page_tree) {
+ pdf_close(pf);
+ return -1;
+ }
+
+ contents = pdf_get_page_content(page_tree);
+ pdf_release_obj(page_tree);
+ if (!contents) {
+ pdf_close(pf);
+ return -1;
+ }
+
+ pdf_doc_add_page_content(" ", 1);
+
+ save_path = malloc(pdf_stream_length(contents) + 1);
+ strncpy(save_path, (const char *) pdf_stream_dataptr(contents), pdf_stream_length(contents));
+ clip_path = save_path;
+ end_path = clip_path + pdf_stream_length(contents);
+ depth = 0;
+
+ for (; clip_path < end_path; clip_path++) {
+ int color_dimen = 0; /* silence uninitialized warning */
+ char *token;
+ skip_white(&clip_path, end_path);
+ if (clip_path == end_path)
+ break;
+ if (depth > 1) {
+ if (*clip_path == 'q')
+ depth++;
+ if (*clip_path == 'Q')
+ depth--;
+ parse_ident(&clip_path, end_path);
+ continue;
+ } else if (*clip_path == '-'
+ || *clip_path == '+'
+ || *clip_path == '.'
+ || isdigit(*clip_path)) {
+ stack[++top] = strtod(clip_path, &temp);
+ clip_path = temp;
+ } else if (*clip_path == '[') {
+ /* Ignore, but put a dummy value on the stack (in case of d operator) */
+ parse_pdf_array(&clip_path, end_path, pf);
+ stack[++top] = 0;
+ } else if (*clip_path == '/') {
+ if (strncmp("/DeviceGray", clip_path, 11) == 0
+ || strncmp("/Indexed", clip_path, 8) == 0
+ || strncmp("/CalGray", clip_path, 8) == 0) {
+ color_dimen = 1;
+ continue;
+ }
+ else if (strncmp("/DeviceRGB", clip_path, 10) == 0
+ || strncmp("/CalRGB", clip_path, 7) == 0
+ || strncmp("/Lab", clip_path, 4) == 0) {
+ color_dimen = 3;
+ continue;
+ }
+ else if (strncmp("/DeviceCMYK", clip_path, 11) == 0) {
+ color_dimen = 4;
+ continue;
+ }
+ else {
+ clip_path++;
+ parse_ident(&clip_path, end_path);
+ skip_white(&clip_path, end_path);
+ token = parse_ident(&clip_path, end_path);
+ if (strcmp(token, "gs") == 0) {
+ continue;
+ }
+ return -1;
+ }
+ } else {
+ int j;
+ pdf_tmatrix T;
+ pdf_coord p0, p1, p2, p3;
+
+ token = parse_ident(&clip_path, end_path);
+ for (j = 0; j < sizeof(pdf_operators) / sizeof(pdf_operators[0]); j++)
+ if (strcmp(token, pdf_operators[j].token) == 0)
+ break;
+ if (j == sizeof(pdf_operators) / sizeof(pdf_operators[0])) {
+ return -1;
+ }
+ switch (pdf_operators[j].opcode) {
+ case 0:
+ case -1:
+ case -2:
+ case -3:
+ case -4:
+ /* Just pop the stack and do nothing. */
+ top += pdf_operators[j].opcode;
+ if (top < -1)
+ return -1;
+ break;
+ case OP_SETCOLOR:
+ top -= color_dimen;
+ if (top < -1)
+ return -1;
+ break;
+ case OP_CLOSEandCLIP:
+ pdf_dev_closepath();
+ case OP_CLIP:
+#if 0
+ pdf_dev_clip();
+#else
+ pdf_dev_flushpath('W', PDF_FILL_RULE_NONZERO);
+#endif
+ break;
+ case OP_CONCATMATRIX:
+ if (top < 5)
+ return -1;
+ T.f = stack[top--];
+ T.e = stack[top--];
+ T.d = stack[top--];
+ T.c = stack[top--];
+ T.b = stack[top--];
+ T.a = stack[top--];
+ pdf_concatmatrix(&M, &T);
+ break;
+ case OP_SETCOLORSPACE:
+ /* Do nothing. */
+ break;
+ case OP_RECTANGLE:
+ if (top < 3)
+ return -1;
+ p1.y = stack[top--];
+ p1.x = stack[top--];
+ p0.y = stack[top--];
+ p0.x = stack[top--];
+ if (M.b == 0 && M.c == 0) {
+ pdf_tmatrix M0;
+ M0.a = M.a; M0.b = M.b; M0.c = M.c; M0.d = M.d;
+ M0.e = 0; M0.f = 0;
+ pdf_dev_transform(&p0, &M);
+ pdf_dev_transform(&p1, &M0);
+ pdf_dev_rectadd(p0.x, p0.y, p1.x, p1.y);
+ } else {
+ p2.x = p0.x + p1.x; p2.y = p0.y + p1.y;
+ p3.x = p0.x; p3.y = p0.y + p1.y;
+ p1.x += p0.x; p1.y = p0.y;
+ pdf_dev_transform(&p0, &M);
+ pdf_dev_transform(&p1, &M);
+ pdf_dev_transform(&p2, &M);
+ pdf_dev_transform(&p3, &M);
+ pdf_dev_moveto(p0.x, p0.y);
+ pdf_dev_lineto(p1.x, p1.y);
+ pdf_dev_lineto(p2.x, p2.y);
+ pdf_dev_lineto(p3.x, p3.y);
+ pdf_dev_closepath();
+ }
+ break;
+ case OP_CURVETO:
+ if (top < 5)
+ return -1;
+ p0.y = stack[top--];
+ p0.x = stack[top--];
+ pdf_dev_transform(&p0, &M);
+ p1.y = stack[top--];
+ p1.x = stack[top--];
+ pdf_dev_transform(&p1, &M);
+ p2.y = stack[top--];
+ p2.x = stack[top--];
+ pdf_dev_transform(&p2, &M);
+ pdf_dev_curveto(p2.x, p2.y, p1.x, p1.y, p0.x, p0.y);
+ break;
+ case OP_CLOSEPATH:
+ pdf_dev_closepath();
+ break;
+ case OP_LINETO:
+ if (top < 1)
+ return -1;
+ p0.y = stack[top--];
+ p0.x = stack[top--];
+ pdf_dev_transform(&p0, &M);
+ pdf_dev_lineto(p0.x, p0.y);
+ break;
+ case OP_MOVETO:
+ if (top < 1)
+ return -1;
+ p0.y = stack[top--];
+ p0.x = stack[top--];
+ pdf_dev_transform(&p0, &M);
+ pdf_dev_moveto(p0.x, p0.y);
+ break;
+ case OP_NOOP:
+ pdf_doc_add_page_content(" n", 2);
+ break;
+ case OP_GSAVE:
+ depth++;
+ break;
+ case OP_GRESTORE:
+ depth--;
+ break;
+ case OP_CURVETO1:
+ if (top < 3)
+ return -1;
+ p0.y = stack[top--];
+ p0.x = stack[top--];
+ pdf_dev_transform(&p0, &M);
+ p1.y = stack[top--];
+ p1.x = stack[top--];
+ pdf_dev_transform(&p1, &M);
+ pdf_dev_vcurveto(p1.x, p1.y, p0.x, p0.y);
+ break;
+ case OP_CURVETO2:
+ if (top < 3)
+ return -1;
+ p0.y = stack[top--];
+ p0.x = stack[top--];
+ pdf_dev_transform(&p0, &M);
+ p1.y = stack[top--];
+ p1.x = stack[top--];
+ pdf_dev_transform(&p1, &M);
+ pdf_dev_ycurveto(p1.x, p1.y, p0.x, p0.y);
+ break;
+ default:
+ return -1;
+ }
+ }
+ }
+ free(save_path);
+
+ pdf_release_obj(contents);
+ pdf_close(pf);
+
+ return 0;
+}
+
+#define WBUF_SIZE 4096
+#if HAVE_ZLIB
+static int
+add_stream_flate (pdf_obj *dst, const void *data, long len)
+{
+ z_stream z;
+ Bytef wbuf[WBUF_SIZE];
+
+ z.zalloc = Z_NULL; z.zfree = Z_NULL; z.opaque = Z_NULL;
+
+ z.next_in = (Bytef *) data; z.avail_in = len;
+ z.next_out = (Bytef *) wbuf; z.avail_out = WBUF_SIZE;
+
+ if (inflateInit(&z) != Z_OK) {
+ WARN("inflateInit() failed.");
+ return -1;
+ }
+
+ for (;;) {
+ int status;
+ status = inflate(&z, Z_NO_FLUSH);
+ if (status == Z_STREAM_END)
+ break;
+ else if (status != Z_OK) {
+ WARN("inflate() failed. Broken PDF file?");
+ inflateEnd(&z);
+ return -1;
+ }
+
+ if (z.avail_out == 0) {
+ pdf_add_stream(dst, wbuf, WBUF_SIZE);
+ z.next_out = wbuf;
+ z.avail_out = WBUF_SIZE;
+ }
+ }
+
+ if (WBUF_SIZE - z.avail_out > 0)
+ pdf_add_stream(dst, wbuf, WBUF_SIZE - z.avail_out);
+
+ return (inflateEnd(&z) == Z_OK ? 0 : -1);
+}
+#endif
+
+static int
+concat_stream (pdf_obj *dst, pdf_obj *src)
+{
+ const char *stream_data;
+ long stream_length;
+ pdf_obj *stream_dict;
+ pdf_obj *filter;
+
+ if (!PDF_OBJ_STREAMTYPE(dst) || !PDF_OBJ_STREAMTYPE(src))
+ ERROR("Invalid type.");
+
+ stream_data = pdf_stream_dataptr(src);
+ stream_length = pdf_stream_length (src);
+ stream_dict = pdf_stream_dict (src);
+
+ if (pdf_lookup_dict(stream_dict, "DecodeParms")) {
+ WARN("DecodeParams not supported.");
+ return -1;
+ }
+
+ filter = pdf_lookup_dict(stream_dict, "Filter");
+ if (!filter) {
+ pdf_add_stream(dst, stream_data, stream_length);
+ return 0;
+#if HAVE_ZLIB
+ } else {
+ char *filter_name;
+ if (PDF_OBJ_NAMETYPE(filter)) {
+ filter_name = pdf_name_value(filter);
+ if (filter_name && !strcmp(filter_name, "FlateDecode"))
+ return add_stream_flate(dst, stream_data, stream_length);
+ else {
+ WARN("DecodeFilter \"%s\" not supported.", filter_name);
+ return -1;
+ }
+ } else if (PDF_OBJ_ARRAYTYPE(filter)) {
+ if (pdf_array_length(filter) > 1) {
+ WARN("Multiple DecodeFilter not supported.");
+ return -1;
+ } else {
+ filter_name = pdf_name_value(pdf_get_array(filter, 0));
+ if (filter_name && !strcmp(filter_name, "FlateDecode"))
+ return add_stream_flate(dst, stream_data, stream_length);
+ else {
+ WARN("DecodeFilter \"%s\" not supported.", filter_name);
+ return -1;
+ }
+ }
+ } else
+ ERROR("Broken PDF file?");
+#endif /* HAVE_ZLIB */
+ }
+
+ return -1;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/epdf.h b/Build/source/texk/dvipdf-x/xsrc/epdf.h
new file mode 100644
index 00000000000..698b5140b8e
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/epdf.h
@@ -0,0 +1,41 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _EPDF_H_
+#define _EPDF_H_
+
+#include "mfileio.h"
+#include "pdfximage.h"
+
+#define pdfbox_crop 1
+#define pdfbox_media 2
+#define pdfbox_bleed 3
+#define pdfbox_trim 4
+#define pdfbox_art 5
+
+extern int pdf_copy_clip (FILE *image_file, int page_index, double x_user, double y_user);
+//extern int pdf_include_page (pdf_ximage *ximage, FILE *file, int page_index, int pdf_box);
+extern int pdf_include_page (pdf_ximage *ximage, FILE *file);
+
+#endif /* _EPDF_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/error.c b/Build/source/texk/dvipdf-x/xsrc/error.c
new file mode 100644
index 00000000000..d9070f5350b
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/error.c
@@ -0,0 +1,92 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#include <stdarg.h>
+#include <stdio.h>
+
+#include "error.h"
+
+#define DPX_MESG 0
+#define DPX_MESG_WARN 1
+#define DPX_MESG_ERROR 2
+
+static int _mesg_type = DPX_MESG;
+#define WANT_NEWLINE() (_mesg_type != DPX_MESG_WARN && _mesg_type != DPX_MESG_ERROR)
+
+static int really_quiet = 0;
+
+void
+shut_up (int quietness)
+{
+ really_quiet = quietness;
+}
+
+void
+MESG (const char *fmt, ...)
+{
+ va_list argp;
+
+ if (really_quiet < 1) {
+ va_start(argp, fmt);
+ vfprintf(stderr, fmt, argp);
+ va_end(argp);
+ _mesg_type = DPX_MESG;
+ }
+}
+
+void
+WARN (const char *fmt, ...)
+{
+ va_list argp;
+
+ if (really_quiet < 2) {
+ if (WANT_NEWLINE())
+ fprintf(stderr, "\n");
+ fprintf(stderr, "** WARNING ** ");
+ va_start(argp, fmt);
+ vfprintf(stderr, fmt, argp);
+ va_end(argp);
+ fprintf(stderr, "\n");
+
+ _mesg_type = DPX_MESG_WARN;
+ }
+}
+
+void
+ERROR (const char *fmt, ...)
+{
+ va_list argp;
+
+ if (really_quiet < 3) {
+ if (WANT_NEWLINE())
+ fprintf(stderr, "\n");
+ fprintf(stderr, "** ERROR ** ");
+ va_start(argp, fmt);
+ vfprintf(stderr, fmt, argp);
+ va_end(argp);
+ fprintf(stderr, "\n");
+ }
+ error_cleanup();
+ exit( 1 );
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/error.h b/Build/source/texk/dvipdf-x/xsrc/error.h
new file mode 100644
index 00000000000..a4dbb6bb39f
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/error.h
@@ -0,0 +1,46 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _ERROR_H_
+#define _ERROR_H_
+
+#include "system.h"
+
+extern void error_cleanup (void);
+
+#define FATAL_ERROR -1
+#define NO_ERROR 0
+
+#include <assert.h>
+#include <stdio.h>
+
+extern void shut_up (int quietness);
+
+extern void ERROR (const char *fmt, ...);
+extern void MESG (const char *fmt, ...);
+extern void WARN (const char *fmt, ...);
+
+#define ASSERT(e) assert(e)
+
+#endif /* _ERROR_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/fontmap.c b/Build/source/texk/dvipdf-x/xsrc/fontmap.c
new file mode 100644
index 00000000000..044dea7d803
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/fontmap.c
@@ -0,0 +1,1513 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+
+#include "dpxfile.h"
+#include "dpxutil.h"
+
+#include "subfont.h"
+
+#include "fontmap.h"
+
+#ifdef XETEX
+#include "ft2build.h"
+#include FT_FREETYPE_H
+#endif
+
+/* CIDFont */
+static char *strip_options (const char *map_name, fontmap_opt *opt);
+
+static int verbose = 0;
+void
+pdf_fontmap_set_verbose (void)
+{
+ verbose++;
+}
+
+
+void
+pdf_init_fontmap_record (fontmap_rec *mrec)
+{
+ ASSERT(mrec);
+
+ mrec->map_name = NULL;
+
+ /* SFD char mapping */
+ mrec->charmap.sfd_name = NULL;
+ mrec->charmap.subfont_id = NULL;
+ /* for OFM */
+ mrec->opt.mapc = -1; /* compatibility */
+
+ mrec->font_name = NULL;
+ mrec->enc_name = NULL;
+
+ mrec->opt.slant = 0.0;
+ mrec->opt.extend = 1.0;
+ mrec->opt.bold = 0.0;
+
+ mrec->opt.flags = 0;
+
+ mrec->opt.design_size = -1.0;
+
+ mrec->opt.tounicode = NULL;
+ mrec->opt.otl_tags = NULL; /* deactivated */
+ mrec->opt.index = 0;
+ mrec->opt.charcoll = NULL;
+ mrec->opt.style = FONTMAP_STYLE_NONE;
+ mrec->opt.stemv = -1; /* not given explicitly by an option */
+
+#ifdef XETEX
+ mrec->opt.ft_face = NULL;
+#endif
+}
+
+void
+pdf_clear_fontmap_record (fontmap_rec *mrec)
+{
+ ASSERT(mrec);
+
+ if (mrec->map_name)
+ RELEASE(mrec->map_name);
+ if (mrec->charmap.sfd_name)
+ RELEASE(mrec->charmap.sfd_name);
+ if (mrec->charmap.subfont_id)
+ RELEASE(mrec->charmap.subfont_id);
+ if (mrec->enc_name)
+ RELEASE(mrec->enc_name);
+ if (mrec->font_name)
+ RELEASE(mrec->font_name);
+
+ if (mrec->opt.tounicode)
+ RELEASE(mrec->opt.tounicode);
+ if (mrec->opt.otl_tags)
+ RELEASE(mrec->opt.otl_tags);
+ if (mrec->opt.charcoll)
+ RELEASE(mrec->opt.charcoll);
+ pdf_init_fontmap_record(mrec);
+}
+
+/* strdup: just returns NULL for NULL */
+static char *
+mstrdup (const char *s)
+{
+ char *r;
+ if (!s)
+ return NULL;
+ r = NEW(strlen(s) + 1, char);
+ strcpy(r, s);
+ return r;
+}
+
+static void
+pdf_copy_fontmap_record (fontmap_rec *dst, const fontmap_rec *src)
+{
+ ASSERT( dst && src );
+
+ dst->map_name = mstrdup(src->map_name);
+
+ dst->charmap.sfd_name = mstrdup(src->charmap.sfd_name);
+ dst->charmap.subfont_id = mstrdup(src->charmap.subfont_id);
+
+ dst->font_name = mstrdup(src->font_name);
+ dst->enc_name = mstrdup(src->enc_name);
+
+ dst->opt.slant = src->opt.slant;
+ dst->opt.extend = src->opt.extend;
+ dst->opt.bold = src->opt.bold;
+
+ dst->opt.flags = src->opt.flags;
+ dst->opt.mapc = src->opt.mapc;
+
+ dst->opt.tounicode = mstrdup(src->opt.tounicode);
+ dst->opt.otl_tags = mstrdup(src->opt.otl_tags);
+ dst->opt.index = src->opt.index;
+ dst->opt.charcoll = mstrdup(src->opt.charcoll);
+ dst->opt.style = src->opt.style;
+ dst->opt.stemv = src->opt.stemv;
+
+#ifdef XETEX
+ dst->opt.ft_face = src->opt.ft_face;
+#endif
+}
+
+
+static void
+hval_free (void *vp)
+{
+ fontmap_rec *mrec = (fontmap_rec *) vp;
+ pdf_clear_fontmap_record(mrec);
+ RELEASE(mrec);
+}
+
+
+static void
+fill_in_defaults (fontmap_rec *mrec, const char *tex_name)
+{
+ if (mrec->enc_name &&
+ (!strcmp(mrec->enc_name, "default") ||
+ !strcmp(mrec->enc_name, "none"))) {
+ RELEASE(mrec->enc_name);
+ mrec->enc_name = NULL;
+ }
+ if (mrec->font_name &&
+ (!strcmp(mrec->font_name, "default") ||
+ !strcmp(mrec->font_name, "none"))) {
+ RELEASE(mrec->font_name);
+ mrec->font_name = NULL;
+ }
+ /* We *must* fill font_name either explicitly or by default */
+ if (!mrec->font_name) {
+ mrec->font_name = NEW(strlen(tex_name)+1, char);
+ strcpy(mrec->font_name, tex_name);
+ }
+
+ mrec->map_name = NEW(strlen(tex_name)+1, char);
+ strcpy(mrec->map_name, tex_name);
+
+#ifndef WITHOUT_COMPAT
+ /* Use "UCS" character collection for Unicode SFD
+ * and Identity CMap combination. For backward
+ * compatibility.
+ */
+ if (mrec->charmap.sfd_name && mrec->enc_name &&
+ !mrec->opt.charcoll) {
+ if ((!strcmp(mrec->enc_name, "Identity-H") ||
+ !strcmp(mrec->enc_name, "Identity-V"))
+ &&
+ (strstr(mrec->charmap.sfd_name, "Uni") ||
+ strstr(mrec->charmap.sfd_name, "UBig") ||
+ strstr(mrec->charmap.sfd_name, "UBg") ||
+ strstr(mrec->charmap.sfd_name, "UGB") ||
+ strstr(mrec->charmap.sfd_name, "UKS") ||
+ strstr(mrec->charmap.sfd_name, "UJIS"))) {
+ mrec->opt.charcoll = NEW(strlen("UCS")+1, char);
+ strcpy(mrec->opt.charcoll, "UCS");
+ }
+ }
+#endif /* WITHOUT_COMPAT */
+
+ return;
+}
+
+static char *
+readline (char *buf, int buf_len, FILE *fp)
+{
+ char *p, *q;
+ ASSERT( buf && buf_len > 0 && fp );
+ p = mfgets(buf, buf_len, fp);
+ if (!p)
+ return NULL;
+ q = strchr(p, '%'); /* we don't have quoted string */
+ if (q)
+ *q = '\0';
+ return p;
+}
+
+#ifndef ISBLANK
+# define ISBLANK(c) ((c) == ' ' || (c) == '\t')
+#endif
+static void
+skip_blank (const char **pp, const char *endptr)
+{
+ const char *p = *pp;
+ if (!p || p >= endptr)
+ return;
+ for ( ; p < endptr && ISBLANK(*p); p++);
+ *pp = p;
+}
+
+static char *
+parse_string_value (const char **pp, const char *endptr)
+{
+ char *q = NULL;
+ const char *p = *pp;
+ int n;
+
+ if (!p || p >= endptr)
+ return NULL;
+ if (*p == '"')
+ q = parse_c_string(&p, endptr);
+ else {
+ for (n = 0; p < endptr && !isspace(*p); p++, n++);
+ if (n == 0)
+ return NULL;
+ q = NEW(n + 1, char);
+ memcpy(q, *pp, n); q[n] = '\0';
+ }
+
+ *pp = p;
+ return q;
+}
+
+/* no preceeding spaces allowed */
+static char *
+parse_integer_value (const char **pp, const char *endptr, int base)
+{
+ char *q;
+ const char *p = *pp;
+ int has_sign = 0, has_prefix = 0, n;
+
+ ASSERT( base == 0 || (base >= 2 && base <= 36) );
+
+ if (!p || p >= endptr)
+ return NULL;
+
+ if (*p == '-' || *p == '+') {
+ p++; has_sign = 1;
+ }
+ if ((base == 0 || base == 16) &&
+ p + 2 <= endptr &&
+ p[0] == '0' && p[1] == 'x') {
+ p += 2; has_prefix = 1;
+ }
+ if (base == 0) {
+ if (has_prefix)
+ base = 16;
+ else if (p < endptr && *p == '0')
+ base = 8;
+ else {
+ base = 10;
+ }
+ }
+#define ISDIGIT_WB(c,b) ( \
+ ((b) <= 10 && (c) >= '0' && (c) < '0' + (b)) || \
+ ((b) > 10 && ( \
+ ((c) >= '0' && (c) <= '9') || \
+ ((c) >= 'a' && (c) < 'a' + ((b) - 10)) || \
+ ((c) >= 'A' && (c) < 'A' + ((b) - 10)) \
+ ) \
+ ) \
+)
+ for (n = 0; p < endptr && ISDIGIT_WB(*p, base); p++, n++);
+ if (n == 0)
+ return NULL;
+ if (has_sign)
+ n += 1;
+ if (has_prefix)
+ n += 2;
+
+ q = NEW(n + 1, char);
+ memcpy(q, *pp, n); q[n] = '\0';
+
+ *pp = p;
+ return q;
+}
+
+static int
+fontmap_parse_mapdef_dpm (fontmap_rec *mrec,
+ const char *mapdef, const char *endptr)
+{
+ const char *p = mapdef;
+
+ /*
+ * Parse record line in map file. First two fields (after TeX font
+ * name) are position specific. Arguments start at the first token
+ * beginning with a '-'.
+ *
+ * NOTE:
+ * Dvipdfm basically uses parse_ident() for parsing enc_name,
+ * font_name, and other string values which assumes PostScript-like
+ * syntax.
+ * skip_white() skips '\r' and '\n' but they should terminate
+ * fontmap line here.
+ */
+
+ skip_blank(&p, endptr);
+ /* encoding field */
+ if (p < endptr && *p != '-') { /* May be NULL */
+ mrec->enc_name = parse_string_value(&p, endptr);
+ skip_blank(&p, endptr);
+ }
+
+ /* fontname or font filename field */
+ if (p < endptr && *p != '-') { /* May be NULL */
+ mrec->font_name = parse_string_value(&p, endptr);
+ skip_blank(&p, endptr);
+ }
+ if (mrec->font_name) {
+ char *tmp;
+ /* Several options are encoded in font_name for
+ * compatibility with dvipdfm.
+ */
+ tmp = strip_options(mrec->font_name, &mrec->opt);
+ if (tmp) {
+ RELEASE(mrec->font_name);
+ mrec->font_name = tmp;
+ }
+ }
+
+ skip_blank(&p, endptr);
+ /* Parse any remaining arguments */
+ while (p + 1 < endptr &&
+ *p != '\r' && *p != '\n' && *p == '-') {
+ char *q, mopt = p[1];
+ long v;
+
+ p += 2; skip_blank(&p, endptr);
+ switch (mopt) {
+
+ case 's': /* Slant option */
+ q = parse_float_decimal(&p, endptr);
+ if (!q) {
+ WARN("Missing a number value for 's' option.");
+ return -1;
+ }
+ mrec->opt.slant = atof(q);
+ RELEASE(q);
+ break;
+
+ case 'e': /* Extend option */
+ q = parse_float_decimal(&p, endptr);
+ if (!q) {
+ WARN("Missing a number value for 'e' option.");
+ return -1;
+ }
+ mrec->opt.extend = atof(q);
+ if (mrec->opt.extend <= 0.0) {
+ WARN("Invalid value for 'e' option: %s", q);
+ return -1;
+ }
+ RELEASE(q);
+ break;
+
+ case 'b': /* Fake-bold option */
+ q = parse_float_decimal(&p, endptr);
+ if (!q) {
+ WARN("Missing a number value for 'b' option.");
+ return -1;
+ }
+ mrec->opt.bold = atof(q);
+ if (mrec->opt.bold <= 0.0) {
+ WARN("Invalid value for 'b' option: %s", q);
+ return -1;
+ }
+ RELEASE(q);
+ break;
+
+ case 'r': /* Remap option; obsolete; just ignore */
+ break;
+
+ case 'i': /* TTC index */
+ q = parse_integer_value(&p, endptr, 10);
+ if (!q) {
+ WARN("Missing TTC index number...");
+ return -1;
+ }
+ mrec->opt.index = atoi(q);
+ if (mrec->opt.index < 0) {
+ WARN("Invalid TTC index number: %s", q);
+ return -1;
+ }
+ RELEASE(q);
+ break;
+
+ case 'p': /* UCS plane: just for testing */
+ q = parse_integer_value(&p, endptr, 0);
+ if (!q) {
+ WARN("Missing a number for 'p' option.");
+ return -1;
+ }
+ v = strtol(q, NULL, 0);
+ if (v < 0 || v > 16)
+ WARN("Invalid value for option 'p': %s", q);
+ else {
+ mrec->opt.mapc = v << 16;
+ }
+ RELEASE(q);
+ break;
+
+ case 'u': /* ToUnicode */
+ q = parse_string_value(&p, endptr);
+ if (q)
+ mrec->opt.tounicode = q;
+ else {
+ WARN("Missing string value for option 'u'.");
+ return -1;
+ }
+ break;
+
+ case 'v': /* StemV */
+ q = parse_integer_value(&p, endptr, 10);
+ if (!q) {
+ WARN("Missing a number for 'v' option.");
+ return -1;
+ }
+ mrec->opt.stemv = strtol(q, NULL, 0);
+ RELEASE(q);
+ break;
+
+ /* Omega uses both single-byte and double-byte set_char command
+ * even for double-byte OFMs. This confuses CMap decoder.
+ */
+ case 'm':
+ /* Map single bytes char 0xab to double byte char 0xcdab */
+ if (p + 4 <= endptr &&
+ p[0] == '<' && p[3] == '>') {
+ p++;
+ q = parse_integer_value(&p, endptr, 16);
+ if (!q) {
+ WARN("Invalid value for option 'm'.");
+ return -1;
+ } else if (p < endptr && *p != '>') {
+ WARN("Invalid value for option 'm': %s", q);
+ RELEASE(q);
+ return -1;
+ }
+ v = strtol(q, NULL, 16);
+ mrec->opt.mapc = ((v << 8) & 0x0000ff00L);
+ RELEASE(q); p++;
+ } else if (p + 4 <= endptr &&
+ !memcmp(p, "sfd:", strlen("sfd:"))) {
+ char *r;
+ const char *rr;
+ /* SFD mapping: sfd:Big5,00 */
+ p += 4; skip_blank(&p, endptr);
+ q = parse_string_value(&p, endptr);
+ if (!q) {
+ WARN("Missing value for option 'm'.");
+ return -1;
+ }
+ r = strchr(q, ',');
+ if (!r) {
+ WARN("Invalid value for option 'm': %s", q);
+ RELEASE(q);
+ return -1;
+ }
+ *r = 0; rr = ++r; skip_blank(&rr, r + strlen(r));
+ if (*rr == '\0') {
+ WARN("Invalid value for option 'm': %s,", q);
+ RELEASE(q);
+ return -1;
+ }
+ mrec->charmap.sfd_name = mstrdup(q);
+ mrec->charmap.subfont_id = mstrdup(rr);
+ RELEASE(q);
+ } else if (p + 4 < endptr &&
+ !memcmp(p, "pad:", strlen("pad:"))) {
+ p += 4; skip_blank(&p, endptr);
+ q = parse_integer_value(&p, endptr, 16);
+ if (!q) {
+ WARN("Invalid value for option 'm'.");
+ return -1;
+ } else if (p < endptr && !isspace(*p)) {
+ WARN("Invalid value for option 'm': %s", q);
+ RELEASE(q);
+ return -1;
+ }
+ v = strtol(q, NULL, 16);
+ mrec->opt.mapc = ((v << 8) & 0x0000ff00L);
+ RELEASE(q);
+ } else {
+ WARN("Invalid value for option 'm'.");
+ return -1;
+ }
+ break;
+
+ case 'w': /* Writing mode (for unicode encoding) */
+ if (!mrec->enc_name ||
+ strcmp(mrec->enc_name, "unicode")) {
+ WARN("Fontmap option 'w' meaningless for encoding other than \"unicode\".");
+ return -1;
+ }
+ q = parse_integer_value(&p, endptr, 10);
+ if (!q) {
+ WARN("Missing wmode value...");
+ return -1;
+ }
+ if (atoi(q) == 1)
+ mrec->opt.flags |= FONTMAP_OPT_VERT;
+ else if (atoi(q) == 0)
+ mrec->opt.flags &= ~FONTMAP_OPT_VERT;
+ else {
+ WARN("Invalid value for option 'w': %s", q);
+ }
+ RELEASE(q);
+ break;
+
+ default:
+ WARN("Unrecognized font map option: '%c'", mopt);
+ return -1;
+ break;
+ }
+ skip_blank(&p, endptr);
+ }
+
+ if (p < endptr && *p != '\r' && *p != '\n') {
+ WARN("Invalid char in fontmap line: %c", *p);
+ return -1;
+ }
+
+ return 0;
+}
+
+
+/* Parse record line in map file of DVIPS/pdfTeX format. */
+static int
+fontmap_parse_mapdef_dps (fontmap_rec *mrec,
+ const char *mapdef, const char *endptr)
+{
+ const char *p = mapdef;
+ char *q;
+
+ skip_blank(&p, endptr);
+
+ /* The first field (after TFM name) must be PostScript name. */
+ /* However, pdftex.map allows a line without PostScript name. */
+
+ if (*p != '"' && *p != '<') {
+ if (p < endptr) {
+ q = parse_string_value(&p, endptr);
+ if (q) RELEASE(q);
+ skip_blank(&p, endptr);
+ } else {
+ WARN("Missing a PostScript font name.");
+ return -1;
+ }
+ }
+
+ if (p >= endptr) return 0;
+
+ /* Parse any remaining arguments */
+ while (p < endptr && *p != '\r' && *p != '\n' && (*p == '<' || *p == '"')) {
+ switch (*p) {
+ case '<': /* encoding or fontfile field */
+ if (++p < endptr && *p == '[') p++; /*skip */
+ skip_blank(&p, endptr);
+ if ((q = parse_string_value(&p, endptr))) {
+ int n = strlen(q);
+ if (n > 4 && strncmp(q+n-4, ".enc", 4) == 0)
+ mrec->enc_name = q;
+ else
+ mrec->font_name = q;
+ }
+ skip_blank(&p, endptr);
+ break;
+
+ case '"': /* Options */
+ if ((q = parse_string_value(&p, endptr))) {
+ const char *r = q, *e = q+strlen(q);
+ char *s, *t;
+ skip_blank(&r, e);
+ while (r < e) {
+ if ((s = parse_float_decimal(&r, e))) {
+ skip_blank(&r, e);
+ if ((t = parse_string_value(&r, e))) {
+ if (strcmp(t, "SlantFont") == 0)
+ mrec->opt.slant = atof(s);
+ else if (strcmp(t, "ExtendFont") == 0)
+ mrec->opt.extend = atof(s);
+ RELEASE(t);
+ }
+ RELEASE(s);
+ } else if ((s = parse_string_value(&r, e))) { /* skip */
+ RELEASE(s);
+ }
+ skip_blank(&r, e);
+ }
+ RELEASE(q);
+ }
+ skip_blank(&p, endptr);
+ break;
+
+ default:
+ WARN("Found an invalid entry: %s", p);
+ return -1;
+ break;
+ }
+ skip_blank(&p, endptr);
+ }
+
+ if (p < endptr && *p != '\r' && *p != '\n') {
+ WARN("Invalid char in fontmap line: %c", *p);
+ return -1;
+ }
+
+ return 0;
+}
+
+
+static struct ht_table *fontmap = NULL;
+
+#define fontmap_invalid(m) (!(m) || !(m)->map_name || !(m)->font_name)
+static char *
+chop_sfd_name (const char *tex_name, char **sfd_name)
+{
+ char *fontname;
+ char *p, *q;
+ int m, n, len;
+
+ *sfd_name = NULL;
+
+ p = strchr(tex_name, '@');
+ if (!p ||
+ p[1] == '\0' || p == tex_name) {
+ return NULL;
+ }
+ m = (int) (p - tex_name);
+ p++;
+ q = strchr(p, '@');
+ if (!q || q == p) {
+ return NULL;
+ }
+ n = (int) (q - p);
+ q++;
+
+ len = strlen(tex_name) - n;
+ fontname = NEW(len+1, char);
+ memcpy(fontname, tex_name, m);
+ fontname[m] = '\0';
+ if (*q)
+ strcat(fontname, q);
+
+ *sfd_name = NEW(n+1, char);
+ memcpy(*sfd_name, p, n);
+ (*sfd_name)[n] = '\0';
+
+ return fontname;
+}
+
+static char *
+make_subfont_name (const char *map_name, const char *sfd_name, const char *sub_id)
+{
+ char *tfm_name;
+ int n, m;
+ char *p, *q;
+
+ p = strchr(map_name, '@');
+ if (!p || p == map_name)
+ return NULL;
+ m = (int) (p - map_name);
+ q = strchr(p + 1, '@');
+ if (!q || q == p + 1)
+ return NULL;
+ n = (int) (q - p) + 1; /* including two '@' */
+ if (strlen(sfd_name) != n - 2 ||
+ memcmp(p + 1, sfd_name, n - 2))
+ return NULL;
+ tfm_name = NEW(strlen(map_name) - n + strlen(sub_id) + 1, char);
+ memcpy(tfm_name, map_name, m);
+ tfm_name[m] = '\0';
+ strcat(tfm_name, sub_id);
+ if (q[1]) /* not ending with '@' */
+ strcat(tfm_name, q + 1);
+
+ return tfm_name;
+}
+
+/* "foo@A@ ..." is expanded to
+ * fooab ... -m sfd:A,ab
+ * ...
+ * fooyz ... -m sfd:A,yz
+ * where 'ab' ... 'yz' is subfont IDs in SFD 'A'.
+ */
+int
+pdf_append_fontmap_record (const char *kp, const fontmap_rec *vp)
+{
+ fontmap_rec *mrec;
+ char *fnt_name, *sfd_name = NULL;
+
+ if (!kp || fontmap_invalid(vp)) {
+ WARN("Invalid fontmap record...");
+ return -1;
+ }
+
+ if (verbose > 3)
+ MESG("fontmap>> append key=\"%s\"...", kp);
+
+ fnt_name = chop_sfd_name(kp, &sfd_name);
+ if (fnt_name && sfd_name) {
+ char *tfm_name;
+ char **subfont_ids;
+ int n = 0;
+ subfont_ids = sfd_get_subfont_ids(sfd_name, &n);
+ if (!subfont_ids)
+ return -1;
+ while (n-- > 0) {
+ tfm_name = make_subfont_name(kp, sfd_name, subfont_ids[n]);
+ if (!tfm_name)
+ continue;
+ mrec = ht_lookup_table(fontmap, tfm_name, strlen(tfm_name));
+ if (!mrec) {
+ mrec = NEW(1, fontmap_rec);
+ pdf_init_fontmap_record(mrec);
+ mrec->map_name = mstrdup(kp); /* link */
+ mrec->charmap.sfd_name = mstrdup(sfd_name);
+ mrec->charmap.subfont_id = mstrdup(subfont_ids[n]);
+ ht_insert_table(fontmap, tfm_name, strlen(tfm_name), mrec);
+ }
+ RELEASE(tfm_name);
+ }
+ RELEASE(fnt_name);
+ RELEASE(sfd_name);
+ }
+
+ mrec = ht_lookup_table(fontmap, kp, strlen(kp));
+ if (!mrec) {
+ mrec = NEW(1, fontmap_rec);
+ pdf_copy_fontmap_record(mrec, vp);
+ if (mrec->map_name && !strcmp(kp, mrec->map_name)) {
+ RELEASE(mrec->map_name);
+ mrec->map_name = NULL;
+ }
+ ht_insert_table(fontmap, kp, strlen(kp), mrec);
+ }
+ if (verbose > 3)
+ MESG("\n");
+
+ return 0;
+}
+
+int
+pdf_remove_fontmap_record (const char *kp)
+{
+ char *fnt_name, *sfd_name = NULL;
+
+ if (!kp)
+ return -1;
+
+ if (verbose > 3)
+ MESG("fontmap>> remove key=\"%s\"...", kp);
+
+ fnt_name = chop_sfd_name(kp, &sfd_name);
+ if (fnt_name && sfd_name) {
+ char *tfm_name;
+ char **subfont_ids;
+ int n = 0;
+ subfont_ids = sfd_get_subfont_ids(sfd_name, &n);
+ if (!subfont_ids)
+ return -1;
+ if (verbose > 3)
+ MESG("\nfontmap>> Expand @%s@:", sfd_name);
+ while (n-- > 0) {
+ tfm_name = make_subfont_name(kp, sfd_name, subfont_ids[n]);
+ if (!tfm_name)
+ continue;
+ if (verbose > 3)
+ MESG(" %s", tfm_name);
+ ht_remove_table(fontmap, tfm_name, strlen(tfm_name));
+ RELEASE(tfm_name);
+ }
+ RELEASE(fnt_name);
+ RELEASE(sfd_name);
+ }
+
+ ht_remove_table(fontmap, kp, strlen(kp));
+
+ if (verbose > 3)
+ MESG("\n");
+
+ return 0;
+}
+
+int
+pdf_insert_fontmap_record (const char *kp, const fontmap_rec *vp)
+{
+ fontmap_rec *mrec;
+ char *fnt_name, *sfd_name;
+
+ if (!kp || fontmap_invalid(vp)) {
+ WARN("Invalid fontmap record...");
+ return -1;
+ }
+
+ if (verbose > 3)
+ MESG("fontmap>> insert key=\"%s\"...", kp);
+
+ fnt_name = chop_sfd_name(kp, &sfd_name);
+ if (fnt_name && sfd_name) {
+ char *tfm_name;
+ char **subfont_ids;
+ int n = 0;
+ subfont_ids = sfd_get_subfont_ids(sfd_name, &n);
+ if (!subfont_ids) {
+ RELEASE(fnt_name);
+ RELEASE(sfd_name);
+ return -1;
+ }
+ if (verbose > 3)
+ MESG("\nfontmap>> Expand @%s@:", sfd_name);
+ while (n-- > 0) {
+ tfm_name = make_subfont_name(kp, sfd_name, subfont_ids[n]);
+ if (!tfm_name)
+ continue;
+ if (verbose > 3)
+ MESG(" %s", tfm_name);
+ mrec = NEW(1, fontmap_rec);
+ pdf_init_fontmap_record(mrec);
+ mrec->map_name = mstrdup(kp); /* link to this entry */
+ mrec->charmap.sfd_name = mstrdup(sfd_name);
+ mrec->charmap.subfont_id = mstrdup(subfont_ids[n]);
+ ht_insert_table(fontmap, tfm_name, strlen(tfm_name), mrec);
+ RELEASE(tfm_name);
+ }
+ RELEASE(fnt_name);
+ RELEASE(sfd_name);
+ }
+
+ mrec = NEW(1, fontmap_rec);
+ pdf_copy_fontmap_record(mrec, vp);
+ if (mrec->map_name && !strcmp(kp, mrec->map_name)) {
+ RELEASE(mrec->map_name);
+ mrec->map_name = NULL;
+ }
+ ht_insert_table(fontmap, kp, strlen(kp), mrec);
+
+ if (verbose > 3)
+ MESG("\n");
+
+ return 0;
+}
+
+
+int
+pdf_read_fontmap_line (fontmap_rec *mrec, const char *mline, long mline_len, int format)
+{
+ int error;
+ char *q;
+ const char *p, *endptr;
+
+ ASSERT(mrec);
+
+ p = mline;
+ endptr = p + mline_len;
+
+ skip_blank(&p, endptr);
+ if (p >= endptr)
+ return -1;
+
+ q = parse_string_value(&p, endptr);
+ if (!q)
+ return -1;
+
+ if (format > 0) /* DVIPDFM format */
+ error = fontmap_parse_mapdef_dpm(mrec, p, endptr);
+ else /* DVIPS/pdfTeX format */
+ error = fontmap_parse_mapdef_dps(mrec, p, endptr);
+ if (!error) {
+ char *fnt_name, *sfd_name = NULL;
+ fnt_name = chop_sfd_name(q, &sfd_name);
+ if (fnt_name && sfd_name) {
+ if (!mrec->font_name) {
+ /* In the case of subfonts, the base name (before the character '@')
+ * will be used as a font_name by default.
+ * Otherwise tex_name will be used as a font_name by default.
+ */
+ mrec->font_name = fnt_name;
+ } else {
+ RELEASE(fnt_name);
+ }
+ if (mrec->charmap.sfd_name)
+ RELEASE(mrec->charmap.sfd_name);
+ mrec->charmap.sfd_name = sfd_name ;
+ }
+ fill_in_defaults(mrec, q);
+ }
+ RELEASE(q);
+
+ return error;
+}
+
+/* DVIPS/pdfTeX fontmap line if one of the following three cases found:
+ *
+ * (1) any line including the character '"'
+ * (2) any line including the character '<'
+ * (3) if the line consists of two entries (tfmname and psname)
+ *
+ * DVIPDFM fontmap line otherwise.
+ */
+int
+is_pdfm_mapline (const char *mline) /* NULL terminated. */
+{
+ int n = 0;
+ const char *p, *endptr;
+
+ if (strchr(mline, '"') || strchr(mline, '<'))
+ return -1; /* DVIPS/pdfTeX format */
+
+ p = mline;
+ endptr = p + strlen(mline);
+
+ skip_blank(&p, endptr);
+
+ while (p < endptr) {
+ /* Break if '-' preceeded by blanks is found. (DVIPDFM format) */
+ if (*p == '-') return 1;
+ for (n++; p < endptr && !ISBLANK(*p); p++);
+ skip_blank(&p, endptr);
+ }
+
+ /* Two entries: TFM_NAME PS_NAME only (DVIPS format)
+ * Otherwise (DVIPDFM format) */
+ return (n == 2 ? 0 : 1);
+}
+
+int
+pdf_load_fontmap_file (const char *filename, int mode)
+{
+ fontmap_rec *mrec;
+ FILE *fp;
+ const char *p = NULL, *endptr;
+ long llen, lpos = 0;
+ int error = 0, format = 0;
+
+ ASSERT(filename);
+ ASSERT(fontmap) ;
+
+ if (verbose)
+ MESG("<FONTMAP:%s", filename);
+
+ fp = DPXFOPEN(filename, DPX_RES_TYPE_FONTMAP);
+ if (!fp) {
+ WARN("Couldn't open font map file \"%s\".", filename);
+ return -1;
+ }
+
+ while (!error &&
+ (p = readline(work_buffer, WORK_BUFFER_SIZE, fp)) != NULL) {
+ int m;
+
+ lpos++;
+ llen = strlen(work_buffer);
+ endptr = p + llen;
+
+ skip_blank(&p, endptr);
+ if (p == endptr)
+ continue;
+
+ m = is_pdfm_mapline(p);
+
+ if (format * m < 0) { /* mismatch */
+ WARN("Found a mismatched fontmap line %d from %s.", lpos, filename);
+ WARN("-- Ignore the current input buffer: %s", p);
+ continue;
+ } else
+ format += m;
+
+ mrec = NEW(1, fontmap_rec);
+ pdf_init_fontmap_record(mrec);
+
+ /* format > 0: DVIPDFM, format <= 0: DVIPS/pdfTeX */
+ error = pdf_read_fontmap_line(mrec, p, llen, format);
+ if (error) {
+ WARN("Invalid map record in fontmap line %d from %s.", lpos, filename);
+ WARN("-- Ignore the current input buffer: %s", p);
+ pdf_clear_fontmap_record(mrec);
+ RELEASE(mrec);
+ continue;
+ } else {
+ switch (mode) {
+ case FONTMAP_RMODE_REPLACE:
+ pdf_insert_fontmap_record(mrec->map_name, mrec);
+ break;
+ case FONTMAP_RMODE_APPEND:
+ pdf_append_fontmap_record(mrec->map_name, mrec);
+ break;
+ case FONTMAP_RMODE_REMOVE:
+ pdf_remove_fontmap_record(mrec->map_name);
+ break;
+ }
+ }
+ pdf_clear_fontmap_record(mrec);
+ RELEASE(mrec);
+ }
+ DPXFCLOSE(fp);
+
+ if (verbose)
+ MESG(">");
+
+ return error;
+}
+
+#ifdef XETEX
+static int
+pdf_insert_native_fontmap_record (const char *name, const char *path, int index, FT_Face face,
+ int layout_dir, int extend, int slant, int embolden)
+{
+ char *fontmap_key;
+ fontmap_rec *mrec;
+
+ ASSERT(name);
+ ASSERT(path || face);
+
+ fontmap_key = malloc(strlen(name) + 40); // CHECK
+ sprintf(fontmap_key, "%s/%c/%d/%d/%d", name, layout_dir == 0 ? 'H' : 'V', extend, slant, embolden);
+
+ if (verbose)
+ MESG("<NATIVE-FONTMAP:%s", fontmap_key);
+
+ mrec = NEW(1, fontmap_rec);
+ pdf_init_fontmap_record(mrec);
+
+ mrec->map_name = fontmap_key;
+ mrec->enc_name = mstrdup(layout_dir == 0 ? "Identity-H" : "Identity-V");
+ mrec->font_name = (path != NULL) ? mstrdup(path) : NULL;
+ mrec->opt.index = index;
+ mrec->opt.ft_face = face;
+ if (layout_dir != 0)
+ mrec->opt.flags |= FONTMAP_OPT_VERT;
+
+ fill_in_defaults(mrec, fontmap_key);
+
+ mrec->opt.extend = extend / 65536.0;
+ mrec->opt.slant = slant / 65536.0;
+ mrec->opt.bold = embolden / 65536.0;
+
+ pdf_insert_fontmap_record(mrec->map_name, mrec);
+ pdf_clear_fontmap_record(mrec);
+ RELEASE(mrec);
+
+ if (verbose)
+ MESG(">");
+
+ return 0;
+}
+
+static FT_Library ftLib;
+
+int
+pdf_load_native_font (const char *ps_name,
+ int layout_dir, int extend, int slant, int embolden)
+{
+ const char *p;
+ char *filename = NEW(strlen(ps_name), char);
+ char *q = filename;
+ int index = 0;
+ FT_Face face = NULL;
+ int error = -1;
+
+ if (ps_name[0] != '[') {
+ ERROR("Loading fonts by font name is not supported: %s", ps_name);
+ return error;
+ }
+
+ if (FT_Init_FreeType(&ftLib) != 0) {
+ ERROR("FreeType initialization failed.");
+ return error;
+ }
+
+#ifdef WIN32
+ for (p = ps_name + 1; *p && *p != ']'; ++p) {
+ if (*p == ':') {
+ if (p == ps_name+2 && isalpha(*(p-1)) && (*(p+1) == '/' || *(p+1) == '\\'))
+ *q++ = *p;
+ else
+ break;
+ }
+ else
+ *q++ = *p;
+ }
+#else
+ for (p = ps_name + 1; *p && *p != ':' && *p != ']'; ++p)
+ *q++ = *p;
+#endif
+ *q = 0;
+ if (*p == ':') {
+ ++p;
+ while (*p && *p != ']')
+ index = index * 10 + *p++ - '0';
+ }
+
+ /* try loading the filename directly */
+ error = FT_New_Face(ftLib, filename, index, &face);
+
+ /* if failed, try locating the file in the TEXMF tree */
+ if ( error &&
+ ( (q = dpx_find_opentype_file(filename)) != NULL
+ || (q = dpx_find_truetype_file(filename)) != NULL
+ || (q = dpx_find_type1_file(filename)) != NULL
+ || (q = dpx_find_dfont_file(filename)) != NULL) ) {
+ error = FT_New_Face(ftLib, q, index, &face);
+ RELEASE(q);
+ }
+
+ if (error == 0)
+ error = pdf_insert_native_fontmap_record(ps_name, filename, index, face,
+ layout_dir, extend, slant, embolden);
+ RELEASE(filename);
+ return error;
+}
+#endif /* XETEX */
+
+#if 0
+/* tfm_name="dmjhira10", map_name="dmj@DNP@10", sfd_name="DNP"
+ * --> sub_id="hira"
+ * Test if tfm_name can be really considered as subfont.
+ */
+static int
+test_subfont (const char *tfm_name, const char *map_name, const char *sfd_name)
+{
+ int r = 0;
+ char **ids;
+ int n, m;
+ char *p = (char *) map_name;
+ char *q = (char *) tfm_name;
+
+ ASSERT( tfm_name && map_name && sfd_name );
+
+ /* until first occurence of '@' */
+ for ( ; *p && *q && *p == *q && *p != '@'; p++, q++);
+ if (*p != '@')
+ return 0;
+ p++;
+ /* compare sfd_name (should be always true here) */
+ if (strlen(p) <= strlen(sfd_name) ||
+ memcmp(p, sfd_name, strlen(sfd_name)) ||
+ p[strlen(sfd_name)] != '@')
+ return 0;
+ /* check tfm_name follows second '@' */
+ p += strlen(sfd_name) + 1;
+ if (*p) {
+ char *r = (char *) tfm_name;
+ r += strlen(tfm_name) - strlen(p);
+ if (strcmp(r, p))
+ return 0;
+ }
+ /* Now 'p' is located at next to SFD name terminator
+ * (second '@') in map_name and 'q' is at first char
+ * of subfont_id substring in tfm_name.
+ */
+ n = strlen(q) - strlen(p); /* length of subfont_id string */
+ if (n <= 0)
+ return 0;
+ /* check if n-length substring 'q' is valid as subfont ID */
+ ids = sfd_get_subfont_ids(sfd_name, &m);
+ if (!ids)
+ return 0;
+ while (!r && m-- > 0) {
+ if (strlen(ids[m]) == n &&
+ !memcmp(q, ids[m], n)) {
+ r = 1;
+ }
+ }
+
+ return r;
+}
+#endif /* 0 */
+
+
+fontmap_rec *
+pdf_lookup_fontmap_record (const char *tfm_name)
+{
+ fontmap_rec *mrec = NULL;
+
+ if (fontmap && tfm_name)
+ mrec = ht_lookup_table(fontmap, tfm_name, strlen(tfm_name));
+
+ return mrec;
+}
+
+
+void
+pdf_init_fontmaps (void)
+{
+ fontmap = NEW(1, struct ht_table);
+ ht_init_table(fontmap, hval_free);
+}
+
+void
+pdf_close_fontmaps (void)
+{
+ if (fontmap) {
+ ht_clear_table(fontmap);
+ RELEASE(fontmap);
+ }
+ fontmap = NULL;
+
+ release_sfd_record();
+}
+
+#if 0
+void
+pdf_clear_fontmaps (void)
+{
+ pdf_close_fontmaps();
+ pdf_init_fontmaps();
+}
+#endif
+
+/* CIDFont options
+ *
+ * FORMAT:
+ *
+ * (:int:)?!?string(/string)?(,string)?
+ */
+
+static char *
+substr (const char **str, char stop)
+{
+ char *sstr;
+ const char *endptr;
+
+ endptr = strchr(*str, stop);
+ if (!endptr || endptr == *str)
+ return NULL;
+ sstr = NEW(endptr-(*str)+1, char);
+ memcpy(sstr, *str, endptr-(*str));
+ sstr[endptr-(*str)] = '\0';
+
+ *str = endptr+1;
+ return sstr;
+}
+
+#include <ctype.h>
+#define CID_MAPREC_CSI_DELIM '/'
+
+static char *
+strip_options (const char *map_name, fontmap_opt *opt)
+{
+ char *font_name;
+ const char *p;
+ char *next = NULL;
+ int have_csi = 0, have_style = 0;
+
+ ASSERT(opt);
+
+ p = map_name;
+ font_name = NULL;
+ opt->charcoll = NULL;
+ opt->index = 0;
+ opt->style = FONTMAP_STYLE_NONE;
+ opt->flags = 0;
+
+ if (*p == ':' && isdigit(*(p+1))) {
+ opt->index = (int) strtoul(p+1, &next, 10);
+ if (*next == ':')
+ p = next + 1;
+ else {
+ opt->index = 0;
+ }
+ }
+ if (*p == '!') { /* no-embedding */
+ if (*(++p) == '\0')
+ ERROR("Invalid map record: %s (--> %s)", map_name, p);
+ opt->flags |= FONTMAP_OPT_NOEMBED;
+ }
+
+ if ((next = strchr(p, CID_MAPREC_CSI_DELIM)) != NULL) {
+ if (next == p)
+ ERROR("Invalid map record: %s (--> %s)", map_name, p);
+ font_name = substr(&p, CID_MAPREC_CSI_DELIM);
+ have_csi = 1;
+ } else if ((next = strchr(p, ',')) != NULL) {
+ if (next == p)
+ ERROR("Invalid map record: %s (--> %s)", map_name, p);
+ font_name = substr(&p, ',');
+ have_style = 1;
+ } else {
+ font_name = NEW(strlen(p)+1, char);
+ strcpy(font_name, p);
+ }
+
+ if (have_csi) {
+ if ((next = strchr(p, ',')) != NULL) {
+ opt->charcoll = substr(&p, ',');
+ have_style = 1;
+ } else if (p[0] == '\0') {
+ ERROR("Invalid map record: %s.", map_name);
+ } else {
+ opt->charcoll = NEW(strlen(p)+1, char);
+ strcpy(opt->charcoll, p);
+ }
+ }
+
+ if (have_style) {
+ if (!strncmp(p, "BoldItalic", 10)) {
+ if (*(p+10))
+ ERROR("Invalid map record: %s (--> %s)", map_name, p);
+ opt->style = FONTMAP_STYLE_BOLDITALIC;
+ } else if (!strncmp(p, "Bold", 4)) {
+ if (*(p+4))
+ ERROR("Invalid map record: %s (--> %s)", map_name, p);
+ opt->style = FONTMAP_STYLE_BOLD;
+ } else if (!strncmp(p, "Italic", 6)) {
+ if (*(p+6))
+ ERROR("Invalid map record: %s (--> %s)", map_name, p);
+ opt->style = FONTMAP_STYLE_ITALIC;
+ }
+ }
+
+ return font_name;
+}
+
+#if DPXTEST
+static void
+dump_fontmap_rec (const char *key, const fontmap_rec *mrec)
+{
+ fontmap_opt *opt = (fontmap_opt *) &mrec->opt;
+
+ if (mrec->map_name)
+ fprintf(stdout, " <!-- subfont");
+ else
+ fprintf(stdout, " <insert");
+ fprintf(stdout, " id=\"%s\"", key);
+ if (mrec->map_name)
+ fprintf(stdout, " map-name=\"%s\"", mrec->map_name);
+ if (mrec->enc_name)
+ fprintf(stdout, " enc-name=\"%s\"", mrec->enc_name);
+ if (mrec->font_name)
+ fprintf(stdout, " font-name=\"%s\"", mrec->font_name);
+ if (mrec->charmap.sfd_name && mrec->charmap.subfont_id) {
+ fprintf(stdout, " charmap=\"sfd:%s,%s\"",
+ mrec->charmap.sfd_name, mrec->charmap.subfont_id);
+ }
+ if (opt->slant != 0.0)
+ fprintf(stdout, " font-slant=\"%g\"", opt->slant);
+ if (opt->extend != 1.0)
+ fprintf(stdout, " font-extend=\"%g\"", opt->extend);
+ if (opt->charcoll)
+ fprintf(stdout, " glyph-order=\"%s\"", opt->charcoll);
+ if (opt->tounicode)
+ fprintf(stdout, " tounicode=\"%s\"", opt->tounicode);
+ if (opt->index != 0)
+ fprintf(stdout, " ttc-index=\"%d\"", opt->index);
+ if (opt->flags & FONTMAP_OPT_NOEMBED)
+ fprintf(stdout, " embedding=\"no\"");
+ if (opt->mapc >= 0) {
+ fprintf(stdout, " charmap=\"pad:");
+ if (opt->mapc > 0xffff)
+ fprintf(stdout, "%02x %02x", (opt->mapc >> 16) & 0xff, (opt->mapc >> 8) & 0xff);
+ else
+ fprintf(stdout, "%02x", (opt->mapc >> 8) & 0xff);
+ fprintf(stdout, "\"");
+ }
+ if (opt->flags & FONTMAP_OPT_VERT)
+ fprintf(stdout, " writing-mode=\"vertical\"");
+ if (opt->style != FONTMAP_STYLE_NONE) {
+ fprintf(stdout, " font-style=\"");
+ switch (opt->style) {
+ case FONTMAP_STYLE_BOLD:
+ fprintf(stdout, "bold");
+ break;
+ case FONTMAP_STYLE_ITALIC:
+ fprintf(stdout, "italic");
+ break;
+ case FONTMAP_STYLE_BOLDITALIC:
+ fprintf(stdout, "bolditalic");
+ break;
+ }
+ fprintf(stdout, "\"");
+ }
+ if (mrec->map_name)
+ fprintf(stdout, " / -->\n");
+ else
+ fprintf(stdout, " />\n");
+}
+
+void
+dump_fontmaps (void)
+{
+ struct ht_iter iter;
+ fontmap_rec *mrec;
+ char key[128], *kp;
+ int kl;
+
+ if (!fontmap)
+ return;
+
+ fprintf(stdout, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+ fprintf(stdout, "<!DOCTYPE fontmap SYSTEM \"fontmap.dtd\">\n");
+ fprintf(stdout, "<fontmap id=\"%s\">\n", "foo");
+ if (ht_set_iter(fontmap, &iter) == 0) {
+ do {
+ kp = ht_iter_getkey(&iter, &kl);
+ mrec = ht_iter_getval(&iter);
+ if (kl > 127)
+ continue;
+ memcpy(key, kp, kl); key[kl] = 0;
+ dump_fontmap_rec(key, mrec);
+ } while (!ht_iter_next(&iter));
+ }
+ ht_clear_iter(&iter);
+ fprintf(stdout, "</fontmap>\n");
+
+ return;
+}
+
+void
+test_fontmap_help (void)
+{
+ fprintf(stdout, "usage: fontmap [options] [mapfile...]\n");
+ fprintf(stdout, "-l, --lookup string\n");
+ fprintf(stdout, " Lookup fontmap entry for 'string' after loading mapfile(s).\n");
+}
+
+int
+test_fontmap_main (int argc, char *argv[])
+{
+ int i;
+ char *key = NULL;
+
+ for (;;) {
+ int c, optidx = 0;
+ static struct option long_options[] = {
+ {"lookup", 1, 0, 'l'},
+ {"help", 0, 0, 'h'},
+ {0, 0, 0, 0}
+ };
+ c = getopt_long(argc, argv, "l:h", long_options, &optidx);
+ if (c == -1)
+ break;
+
+ switch (c) {
+ case 'l':
+ key = optarg;
+ break;
+ case 'h':
+ test_fontmap_help();
+ return 0;
+ break;
+ default:
+ test_fontmap_help();
+ return -1;
+ break;
+ }
+ }
+
+ pdf_init_fontmaps();
+ for (i = optind; i < argc; i++)
+ pdf_load_fontmap_file(argv[i], FONTMAP_RMODE_REPLACE);
+
+ if (key == NULL)
+ dump_fontmaps();
+ else {
+ fontmap_rec *mrec;
+ mrec = pdf_lookup_fontmap_record(key);
+ if (mrec)
+ dump_fontmap_rec(key, mrec);
+ else {
+ WARN("Fontmap entry \"%s\" not found.", key);
+ }
+ }
+ pdf_close_fontmaps();
+
+ return 0;
+}
+#endif /* DPXTEST */
diff --git a/Build/source/texk/dvipdf-x/xsrc/fontmap.h b/Build/source/texk/dvipdf-x/xsrc/fontmap.h
new file mode 100644
index 00000000000..fee6f238fa5
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/fontmap.h
@@ -0,0 +1,109 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _FONTMAP_H_
+#define _FONTMAP_H_
+
+#define FONTMAP_RMODE_REPLACE 0
+#define FONTMAP_RMODE_APPEND '+'
+#define FONTMAP_RMODE_REMOVE '-'
+
+#define FONTMAP_OPT_NOEMBED (1 << 1)
+#define FONTMAP_OPT_VERT (1 << 2)
+
+#define FONTMAP_STYLE_NONE 0
+#define FONTMAP_STYLE_BOLD 1
+#define FONTMAP_STYLE_ITALIC 2
+#define FONTMAP_STYLE_BOLDITALIC 3
+
+#ifdef XETEX
+#include "ft2build.h"
+#include FT_FREETYPE_H
+#endif
+
+/* Options */
+typedef struct fontmap_opt {
+ /* Synthetic font */
+ double slant, extend, bold;
+ /* comaptibility and other flags */
+ long mapc, flags;
+
+ char *otl_tags; /* currently unused */
+ char *tounicode; /* not implemented yet */
+
+ double design_size; /* unused */
+
+ char *charcoll; /* Adobe-Japan1-4, etc. */
+ int index; /* TTC index */
+ int style; /* ,Bold, etc. */
+ int stemv; /* StemV value especially for CJK fonts */
+#ifdef XETEX
+ FT_Face ft_face;
+#endif
+} fontmap_opt;
+
+typedef struct fontmap_rec {
+ char *map_name;
+
+ char *font_name;
+ char *enc_name;
+
+ /* Subfont mapping: translate 8-bit charcode to 16-bit charcode
+ * via SFD.
+ */
+ struct {
+ char *sfd_name;
+ char *subfont_id;
+ } charmap;
+
+ fontmap_opt opt;
+} fontmap_rec;
+
+extern void pdf_fontmap_set_verbose (void);
+
+extern void pdf_init_fontmaps (void);
+#if 0
+extern void pdf_clear_fontmaps (void);
+#endif
+extern void pdf_close_fontmaps (void);
+
+extern void pdf_init_fontmap_record (fontmap_rec *mrec);
+extern void pdf_clear_fontmap_record (fontmap_rec *mrec);
+
+extern int pdf_load_fontmap_file (const char *filename, int mode);
+extern int pdf_read_fontmap_line (fontmap_rec *mrec, const char *mline, long mline_strlen, int format);
+
+extern int pdf_append_fontmap_record (const char *kp, const fontmap_rec *mrec);
+extern int pdf_remove_fontmap_record (const char *kp);
+extern int pdf_insert_fontmap_record (const char *kp, const fontmap_rec *mrec);
+extern fontmap_rec *pdf_lookup_fontmap_record (const char *kp);
+
+extern int is_pdfm_mapline (const char *mline);
+
+#ifdef XETEX
+extern int pdf_load_native_font (const char *ps_name,
+ int layout_dir, int extend, int slant, int embolden);
+#endif
+
+#endif /* _FONTMAP_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/jpegimage.c b/Build/source/texk/dvipdf-x/xsrc/jpegimage.c
new file mode 100644
index 00000000000..75d6607c2a0
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/jpegimage.c
@@ -0,0 +1,916 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/*
+ * JPEG SUPPORT
+ *
+ * Accroding to Libjpeg document:
+ *
+ * CAUTION: it appears that Adobe Photoshop writes inverted data in CMYK
+ * JPEG files: 0 represents 100% ink coverage, rather than 0% ink as you'd
+ * expect....
+ *
+ * To wrok with this problem, we must detect whether CMYK JPEG file is
+ * created by Photoshop. But there are no reliable way to determine this.
+ *
+ * According to Adobe Technical Note #5516,
+ * "Supporting the DCT Filters in PostScript Level 2", Section 18, p.27.
+ *
+ * DCTDecode ignores and skips any APPE marker segment does not begin with
+ * the `Adobe' 5-character string.
+ *
+ * PDF Reference Manual 4th ed., p.61-62.
+ *
+ * The JPEG filter implementation in Adobe Acrobat products does not
+ * support features of the JPEG standard that are irrelevant to images.
+ * In addition, certain choices have been made regarding reserved marker
+ * codes and other optional features of the standard. For details, see
+ * Adobe Technical Note #5116, Supporting the DCT Filters in PostScript
+ * Level 2.
+ */
+
+#include "system.h"
+#include "error.h"
+#include "mem.h"
+
+#include "mfileio.h"
+#include "numbers.h"
+
+#include "pdfobj.h"
+
+#include "jpegimage.h"
+#include "pdfcolor.h"
+
+#include "pdfximage.h"
+
+#define JPEG_DEBUG_STR "JPEG"
+#define JPEG_DEBUG 3
+
+#ifdef HAVE_LIBJPEG
+#include <jpeglib.h>
+#endif /* HAVE_LIBJPEG */
+
+/* JPEG Markers */
+typedef enum {
+ JM_SOF0 = 0xc0,
+ JM_SOF1 = 0xc1,
+ JM_SOF2 = 0xc2,
+ JM_SOF3 = 0xc3,
+ JM_SOF5 = 0xc5,
+ JM_DHT = 0xc4,
+ JM_SOF6 = 0xc6,
+ JM_SOF7 = 0xc7,
+ JM_SOF9 = 0xc9,
+ JM_SOF10 = 0xca,
+ JM_SOF11 = 0xcb,
+ JM_DAC = 0xcc,
+ JM_SOF13 = 0xcd,
+ JM_SOF14 = 0xce,
+ JM_SOF15 = 0xcf,
+
+ JM_RST0 = 0xd0,
+ JM_RST1 = 0xd1,
+ JM_RST2 = 0xd2,
+ JM_RST3 = 0xd3,
+ JM_RST4 = 0xd4,
+ JM_RST5 = 0xd5,
+ JM_RST6 = 0xd6,
+ JM_RST7 = 0xd7,
+
+ JM_SOI = 0xd8,
+ JM_EOI = 0xd9,
+ JM_SOS = 0xda,
+ JM_DQT = 0xdb,
+ JM_DNL = 0xdc,
+ JM_DRI = 0xdd,
+ JM_DHP = 0xde,
+ JM_EXP = 0xdf,
+
+ JM_APP0 = 0xe0,
+ JM_APP1 = 0xe1,
+ JM_APP2 = 0xe2,
+ JM_APP14 = 0xee,
+ JM_APP15 = 0xef,
+
+ JM_COM = 0xfe
+} JPEG_marker;
+
+typedef enum {
+ JS_APPn_JFIF,
+ JS_APPn_ADOBE,
+ JS_APPn_ICC
+} JPEG_APPn_sig;
+
+struct JPEG_APPn_JFIF /* APP0 */
+{
+ unsigned short version;
+ unsigned char units; /* 0: only aspect ratio
+ * 1: dots per inch
+ * 2: dots per cm
+ */
+ unsigned short Xdensity;
+ unsigned short Ydensity;
+ unsigned char Xthumbnail;
+ unsigned char Ythumbnail;
+ unsigned char *thumbnail; /* Thumbnail data. */
+};
+
+struct JPEG_APPn_ICC /* APP2 */
+{
+ unsigned char seq_id;
+ unsigned char num_chunks;
+ unsigned char *chunk;
+
+ /* Length of ICC profile data in this chunk. */
+ unsigned short length;
+};
+
+struct JPEG_APPn_Adobe /* APP14 */
+{
+ unsigned short version;
+ unsigned short flag0;
+ unsigned short flag1;
+ unsigned char transform; /* color transform code */
+};
+
+struct JPEG_ext
+{
+ JPEG_marker marker;
+ JPEG_APPn_sig app_sig;
+ void *app_data;
+};
+
+#define MAX_COUNT 1024
+struct JPEG_info
+{
+ unsigned short height;
+ unsigned short width;
+
+ unsigned char bits_per_component;
+ unsigned char num_components;
+
+ double xdpi;
+ double ydpi;
+
+ /* Application specific extensions */
+ int flags;
+ int num_appn, max_appn;
+ struct JPEG_ext *appn;
+
+ /* Skip chunks not necessary. */
+ char skipbits[MAX_COUNT / 8 + 1];
+};
+
+#define HAVE_APPn_JFIF (1 << 0)
+#define HAVE_APPn_ADOBE (1 << 1)
+#define HAVE_APPn_ICC (1 << 2)
+#define HAVE_APPn_Exif (1 << 3)
+
+static int JPEG_scan_file (struct JPEG_info *j_info, FILE *fp);
+static int JPEG_copy_stream (struct JPEG_info *j_info,
+ pdf_obj *stream, FILE *fp, int flags); /* flags unused yet */
+
+static void JPEG_info_init (struct JPEG_info *j_info);
+static void JPEG_info_clear (struct JPEG_info *j_info);
+static pdf_obj *JPEG_get_iccp (struct JPEG_info *j_info);
+
+int
+check_for_jpeg (FILE *fp)
+{
+ unsigned char jpeg_sig[2];
+
+ rewind(fp);
+ if (fread(jpeg_sig, sizeof(unsigned char), 2, fp) != 2)
+ return 0;
+ else if (jpeg_sig[0] != 0xff || jpeg_sig[1] != JM_SOI)
+ return 0;
+
+ return 1;
+}
+
+int
+jpeg_include_image (pdf_ximage *ximage, FILE *fp)
+{
+ pdf_obj *stream;
+ pdf_obj *stream_dict;
+ pdf_obj *colorspace;
+ int colortype;
+ ximage_info info;
+ struct JPEG_info j_info;
+
+ if (!check_for_jpeg(fp)) {
+ WARN("%s: Not a JPEG file?", JPEG_DEBUG_STR);
+ rewind(fp);
+ return -1;
+ }
+ /* File position is 2 here... */
+
+ pdf_ximage_init_image_info(&info);
+
+ JPEG_info_init(&j_info);
+
+ if (JPEG_scan_file(&j_info, fp) < 0) {
+ WARN("%s: Not a JPEG file?", JPEG_DEBUG_STR);
+ JPEG_info_clear(&j_info);
+ return -1;
+ }
+
+ switch (j_info.num_components) {
+ case 1:
+ colortype = PDF_COLORSPACE_TYPE_GRAY;
+ break;
+ case 3:
+ colortype = PDF_COLORSPACE_TYPE_RGB;
+ break;
+ case 4:
+ colortype = PDF_COLORSPACE_TYPE_CMYK;
+ break;
+ default:
+ WARN("%s: Unknown color space (num components: %d)",
+ JPEG_DEBUG_STR, info.num_components);
+ JPEG_info_clear(&j_info);
+ return -1;
+ }
+
+ /* JPEG image use DCTDecode. */
+ stream = pdf_new_stream (0);
+ stream_dict = pdf_stream_dict(stream);
+ pdf_add_dict(stream_dict,
+ pdf_new_name("Filter"), pdf_new_name("DCTDecode"));
+
+ colorspace = NULL;
+ if (j_info.flags & HAVE_APPn_ICC) {
+ pdf_obj *icc_stream, *intent;
+
+ icc_stream = JPEG_get_iccp(&j_info);
+
+ if (!icc_stream)
+ colorspace = NULL;
+ else {
+ int cspc_id;
+
+ if (iccp_check_colorspace(colortype,
+ pdf_stream_dataptr(icc_stream),
+ pdf_stream_length (icc_stream)) < 0)
+ colorspace = NULL;
+ else {
+ cspc_id = iccp_load_profile(NULL, /* noname */
+ pdf_stream_dataptr(icc_stream),
+ pdf_stream_length (icc_stream));
+ if (cspc_id < 0)
+ colorspace = NULL;
+ else {
+ colorspace = pdf_get_colorspace_reference(cspc_id);
+ intent = iccp_get_rendering_intent(pdf_stream_dataptr(icc_stream),
+ pdf_stream_length (icc_stream));
+ if (intent)
+ pdf_add_dict(stream_dict, pdf_new_name("Intent"), intent);
+ }
+ }
+ pdf_release_obj(icc_stream);
+ }
+ }
+
+ /* No ICC or invalid ICC profile. */
+ if (!colorspace) {
+ switch (colortype) {
+ case PDF_COLORSPACE_TYPE_GRAY:
+ colorspace = pdf_new_name("DeviceGray");
+ break;
+ case PDF_COLORSPACE_TYPE_RGB:
+ colorspace = pdf_new_name("DeviceRGB");
+ break;
+ case PDF_COLORSPACE_TYPE_CMYK:
+ colorspace = pdf_new_name("DeviceCMYK");
+ break;
+ }
+ }
+ pdf_add_dict(stream_dict, pdf_new_name("ColorSpace"), colorspace);
+
+#define IS_ADOBE_CMYK(j) (((j).flags & HAVE_APPn_ADOBE) && (j).num_components == 4)
+
+ if (IS_ADOBE_CMYK(j_info)) {
+ pdf_obj *decode;
+ int i;
+
+ WARN("Adobe CMYK JPEG: Inverted color assumed.");
+ decode = pdf_new_array();
+ for (i = 0; i < j_info.num_components; i++) {
+ pdf_add_array(decode, pdf_new_number(1.0));
+ pdf_add_array(decode, pdf_new_number(0.0));
+ }
+ pdf_add_dict(stream_dict, pdf_new_name("Decode"), decode);
+ }
+
+ /* Copy file */
+ JPEG_copy_stream(&j_info, stream, fp, 0);
+
+ info.width = j_info.width;
+ info.height = j_info.height;
+ info.bits_per_component = j_info.bits_per_component;
+ info.num_components = j_info.num_components;
+
+#define IS_Exif(j) ((j).flags & HAVE_APPn_Exif)
+#define IS_JFIF(j) ((j).flags & HAVE_APPn_JFIF)
+
+ if (IS_Exif(j_info)) { /* resolution data from EXIF is handled here,
+ takes precedence over JFIF */
+ info.xdensity = 72.0 / j_info.xdpi;
+ info.ydensity = 72.0 / j_info.ydpi;
+ }
+ else if (IS_JFIF(j_info)) {
+ int i;
+ for (i = 0; i < j_info.num_appn; i++) {
+ if (j_info.appn[i].marker == JM_APP0 && j_info.appn[i].app_sig == JS_APPn_JFIF)
+ break;
+ }
+ if (i < j_info.num_appn) {
+ struct JPEG_APPn_JFIF *app_data = (struct JPEG_APPn_JFIF *)j_info.appn[i].app_data;
+ switch (app_data->units) {
+ case 1: /* pixels per inch */
+ info.xdensity = 72.0 / app_data->Xdensity;
+ info.ydensity = 72.0 / app_data->Ydensity;
+ break;
+ case 2: /* pixels per centimeter */
+ info.xdensity = 72.0 / 2.54 / app_data->Xdensity;
+ info.ydensity = 72.0 / 2.54 / app_data->Ydensity;
+ break;
+ default:
+ break;
+ }
+ }
+ }
+
+ pdf_ximage_set_image(ximage, &info, stream);
+ JPEG_info_clear(&j_info);
+
+ return 0;
+}
+
+static void
+JPEG_info_init (struct JPEG_info *j_info)
+{
+ j_info->width = 0;
+ j_info->height = 0;
+ j_info->bits_per_component = 0;
+ j_info->num_components = 0;
+
+ j_info->xdpi = 0;
+ j_info->ydpi = 0;
+
+ j_info->flags = 0;
+ j_info->num_appn = 0;
+ j_info->max_appn = 0;
+ j_info->appn = NULL;
+
+ memset(j_info->skipbits, 0, MAX_COUNT / 8 + 1);
+}
+
+static void
+JPEG_release_APPn_data (JPEG_marker marker, JPEG_APPn_sig app_sig, void *app_data)
+{
+ if (marker == JM_APP0 &&
+ app_sig == JS_APPn_JFIF) {
+ struct JPEG_APPn_JFIF *data;
+
+ data = (struct JPEG_APPn_JFIF *) app_data;
+ if (data->thumbnail)
+ RELEASE(data->thumbnail);
+ data->thumbnail = NULL;
+
+ RELEASE(data);
+ } else if (marker == JM_APP2 &&
+ app_sig == JS_APPn_ICC) {
+ struct JPEG_APPn_ICC *data;
+
+ data = (struct JPEG_APPn_ICC *) app_data;
+ if (data->chunk)
+ RELEASE(data->chunk);
+ data->chunk = NULL;
+
+ RELEASE(data);
+ } else if (marker == JM_APP14 &&
+ app_sig == JS_APPn_ADOBE) {
+ struct JPEG_APPn_Adobe *data;
+
+ data = (struct JPEG_APPn_Adobe *) app_data;
+
+ RELEASE(data);
+ }
+}
+
+static void
+JPEG_info_clear (struct JPEG_info *j_info)
+{
+ if (j_info->num_appn > 0 &&
+ j_info->appn != NULL) {
+ int i;
+
+ for (i = 0; i < j_info->num_appn; i++)
+ JPEG_release_APPn_data(j_info->appn[i].marker,
+ j_info->appn[i].app_sig, j_info->appn[i].app_data);
+ RELEASE(j_info->appn);
+ }
+ j_info->appn = NULL;
+ j_info->num_appn = 0;
+ j_info->max_appn = 0;
+ j_info->flags = 0;
+}
+
+static pdf_obj *
+JPEG_get_iccp (struct JPEG_info *j_info)
+{
+ pdf_obj *icc_stream;
+ struct JPEG_APPn_ICC *icc;
+ int i, prev_id = 0, num_icc_seg = -1;
+
+ icc_stream = pdf_new_stream(STREAM_COMPRESS);
+ for (i = 0; i < j_info->num_appn; i++) {
+ if (j_info->appn[i].marker != JM_APP2 ||
+ j_info->appn[i].app_sig != JS_APPn_ICC)
+ continue;
+ icc = (struct JPEG_APPn_ICC *) j_info->appn[i].app_data;
+ if (num_icc_seg < 0 && prev_id == 0) {
+ num_icc_seg = icc->num_chunks;
+ /* ICC chunks are sorted? */
+ } else if (icc->seq_id != prev_id + 1 ||
+ num_icc_seg != icc->num_chunks ||
+ icc->seq_id > icc->num_chunks) {
+ WARN("Invalid JPEG ICC chunk: %d (p:%d, n:%d)",
+ icc->seq_id, prev_id, icc->num_chunks);
+ pdf_release_obj(icc_stream);
+ icc_stream = NULL;
+ break;
+ }
+ pdf_add_stream(icc_stream, icc->chunk, icc->length);
+ prev_id = icc->seq_id;
+ num_icc_seg = icc->num_chunks;
+ }
+
+ return icc_stream;
+}
+
+static JPEG_marker
+JPEG_get_marker (FILE *fp)
+{
+ int c;
+
+ c = fgetc(fp);
+ if (c != 255)
+ return -1;
+
+ for (;;) {
+ c = fgetc(fp);
+ if (c < 0)
+ return -1;
+ else if (c > 0 && c < 255) {
+ return c;
+ }
+ }
+
+ return -1;
+}
+
+static int
+add_APPn_marker (struct JPEG_info *j_info,
+ JPEG_marker marker, int app_sig, void *app_data)
+{
+ int n;
+
+ if (j_info->num_appn >= j_info->max_appn) {
+ j_info->max_appn += 16;
+ j_info->appn = RENEW(j_info->appn, j_info->max_appn, struct JPEG_ext);
+ }
+ n = j_info->num_appn;
+
+ j_info->appn[n].marker = marker;
+ j_info->appn[n].app_sig = app_sig;
+ j_info->appn[n].app_data = app_data;
+
+ j_info->num_appn += 1;
+
+ return n;
+}
+
+static unsigned short
+read_APP14_Adobe (struct JPEG_info *j_info, FILE *fp, unsigned short length)
+{
+ struct JPEG_APPn_Adobe *app_data;
+
+ app_data = NEW(1, struct JPEG_APPn_Adobe);
+ app_data->version = get_unsigned_pair(fp);
+ app_data->flag0 = get_unsigned_pair(fp);
+ app_data->flag1 = get_unsigned_pair(fp);
+ app_data->transform = get_unsigned_byte(fp);
+
+ add_APPn_marker(j_info, JM_APP14, JS_APPn_ADOBE, app_data);
+
+ return 7;
+}
+
+static unsigned long
+read_exif_bytes(unsigned char **p, int n, int b)
+{
+ unsigned long rval = 0;
+ unsigned char *pp = *p;
+ if (b) {
+ switch (n) {
+ case 4:
+ rval += *pp++; rval <<= 8;
+ rval += *pp++; rval <<= 8;
+ case 2:
+ rval += *pp++; rval <<= 8;
+ rval += *pp;
+ break;
+ }
+ }
+ else {
+ pp += n;
+ switch (n) {
+ case 4:
+ rval += *--pp; rval <<= 8;
+ rval += *--pp; rval <<= 8;
+ case 2:
+ rval += *--pp; rval <<= 8;
+ rval += *--pp;
+ break;
+ }
+ }
+ *p += n;
+ return rval;
+}
+
+static unsigned short
+read_APP1_Exif (struct JPEG_info *j_info, FILE *fp, unsigned short length)
+{
+ /* this doesn't save the data, just reads the tags we need */
+ /* based on info from http://www.exif.org/Exif2-2.PDF */
+ unsigned char *buffer = NEW(length, unsigned char);
+ unsigned char *p, *rp;
+ unsigned char *tiff_header;
+ char bigendian;
+ int i;
+ int num_fields, tag, type;
+ int value = 0, num = 0, den = 0; /* silence uninitialized warnings */
+ double xres = 72.0;
+ double yres = 72.0;
+ double res_unit = 1.0;
+ fread(buffer, length, 1, fp);
+ p = buffer;
+ while ((p < buffer + length) && (*p == 0))
+ ++p;
+ tiff_header = p;
+ if ((*p == 'M') && (*(p+1) == 'M'))
+ bigendian = 1;
+ else if ((*p == 'I') && (*(p+1) == 'I'))
+ bigendian = 0;
+ else
+ goto err;
+ p += 2;
+ i = read_exif_bytes(&p, 2, bigendian);
+ if (i != 42)
+ goto err;
+ i = read_exif_bytes(&p, 4, bigendian);
+ p = tiff_header + i;
+ num_fields = read_exif_bytes(&p, 2, bigendian);
+ while (num_fields-- > 0) {
+ tag = read_exif_bytes(&p, 2, bigendian);
+ type = read_exif_bytes(&p, 2, bigendian);
+ read_exif_bytes(&p, 4, bigendian);
+ switch (type) {
+ case 1: /* byte */
+ value = *p++;
+ p += 3;
+ break;
+ case 3: /* short */
+ value = read_exif_bytes(&p, 2, bigendian);
+ p += 2;
+ break;
+ case 4: /* long */
+ case 9: /* slong */
+ value = read_exif_bytes(&p, 4, bigendian);
+ break;
+ case 5: /* rational */
+ case 10: /* srational */
+ value = read_exif_bytes(&p, 4, bigendian);
+ rp = tiff_header + value;
+ num = read_exif_bytes(&rp, 4, bigendian);
+ den = read_exif_bytes(&rp, 4, bigendian);
+ break;
+ case 7: /* undefined */
+ value = *p++;
+ p += 3;
+ break;
+ case 2: /* ascii */
+ default:
+ p += 4;
+ break;
+ }
+ switch (tag) {
+ case 282: /* x res */
+ if (den != 0)
+ xres = num / den;
+ break;
+ case 283: /* y res */
+ if (den != 0)
+ yres = num / den;
+ break;
+ case 296: /* res unit */
+ switch (value) {
+ case 2:
+ res_unit = 1.0;
+ break;
+ case 3:
+ res_unit = 2.54;
+ break;
+ }
+ }
+ }
+
+ j_info->xdpi = xres * res_unit;
+ j_info->ydpi = yres * res_unit;
+
+err:
+ RELEASE(buffer);
+ return length;
+}
+
+static unsigned short
+read_APP0_JFIF (struct JPEG_info *j_info, FILE *fp, unsigned short length)
+{
+ struct JPEG_APPn_JFIF *app_data;
+ unsigned short thumb_data_len;
+
+ app_data = NEW(1, struct JPEG_APPn_JFIF);
+ app_data->version = get_unsigned_pair(fp);
+ app_data->units = get_unsigned_byte(fp);
+ app_data->Xdensity = get_unsigned_pair(fp);
+ app_data->Ydensity = get_unsigned_pair(fp);
+ app_data->Xthumbnail = get_unsigned_byte(fp);
+ app_data->Ythumbnail = get_unsigned_byte(fp);
+ thumb_data_len = 3 * app_data->Xthumbnail * app_data->Ythumbnail;
+ if (thumb_data_len > 0) {
+ app_data->thumbnail = NEW(thumb_data_len, unsigned char);
+ fread(app_data->thumbnail, 1, thumb_data_len, fp);
+ } else {
+ app_data->thumbnail = NULL;
+ }
+
+ add_APPn_marker(j_info, JM_APP0, JS_APPn_JFIF, app_data);
+
+ switch (app_data->units) {
+ case 1:
+ j_info->xdpi = app_data->Xdensity;
+ j_info->ydpi = app_data->Ydensity;
+ break;
+ case 2: /* density is in pixels per cm */
+ j_info->xdpi = app_data->Xdensity * 2.54;
+ j_info->ydpi = app_data->Ydensity * 2.54;
+ break;
+ default: /* FIXME: not sure what to do with this.... */
+ j_info->xdpi = 72.0;
+ j_info->ydpi = 72.0 * app_data->Ydensity / app_data->Xdensity;
+ break;
+ }
+
+ return (9 + thumb_data_len);
+}
+
+static unsigned short
+read_APP0_JFXX (struct JPEG_info *j_info, FILE *fp, unsigned short length)
+{
+ get_unsigned_byte(fp);
+ /* Extension Code:
+ *
+ * 0x10: Thumbnail coded using JPEG
+ * 0x11: Thumbnail stored using 1 byte/pixel
+ * 0x13: Thumbnail stored using 3 bytes/pixel
+ */
+ seek_relative(fp, length-1); /* Thunbnail image */
+
+ /* Ignore */
+
+ return length;
+}
+
+static unsigned short
+read_APP2_ICC (struct JPEG_info *j_info, FILE *fp, unsigned short length)
+{
+ struct JPEG_APPn_ICC *app_data;
+
+ app_data = NEW(1, struct JPEG_APPn_ICC);
+ app_data->seq_id = get_unsigned_byte(fp); /* Starting at 1 */
+ app_data->num_chunks = get_unsigned_byte(fp);
+ app_data->length = length - 2;
+ app_data->chunk = NEW(app_data->length, unsigned char);
+ fread(app_data->chunk, 1, app_data->length, fp);
+
+ add_APPn_marker(j_info, JM_APP2, JS_APPn_ICC, app_data);
+
+ return length;
+}
+
+static int
+JPEG_copy_stream (struct JPEG_info *j_info,
+ pdf_obj *stream, FILE *fp, int flags) /* flags unused yet */
+{
+ JPEG_marker marker;
+ long length, nb_read;
+ int found_SOFn, count;
+
+ rewind(fp);
+ count = 0;
+ found_SOFn = 0;
+ while (!found_SOFn &&
+ count < MAX_COUNT &&
+ (marker = JPEG_get_marker(fp)) >= 0) {
+ if (marker == JM_SOI ||
+ (marker >= JM_RST0 && marker <= JM_RST7)) {
+ work_buffer[0] = (char) 0xff;
+ work_buffer[1] = (char) marker;
+ pdf_add_stream(stream, work_buffer, 2);
+ count++;
+ continue;
+ }
+ length = get_unsigned_pair(fp) - 2;
+ switch (marker) {
+ case JM_SOF0: case JM_SOF1: case JM_SOF2: case JM_SOF3:
+ case JM_SOF5: case JM_SOF6: case JM_SOF7: case JM_SOF9:
+ case JM_SOF10: case JM_SOF11: case JM_SOF13: case JM_SOF14:
+ case JM_SOF15:
+ work_buffer[0] = (char) 0xff;
+ work_buffer[1] = (char) marker;
+ work_buffer[2] = ((length + 2) >> 8) & 0xff;
+ work_buffer[3] = (length + 2) & 0xff;
+ pdf_add_stream(stream, work_buffer, 4);
+ while (length > 0) {
+ nb_read = fread(work_buffer, sizeof(char),
+ MIN(length, WORK_BUFFER_SIZE), fp);
+ if (nb_read > 0)
+ pdf_add_stream(stream, work_buffer, nb_read);
+ length -= nb_read;
+ }
+ found_SOFn = 1;
+ break;
+ default:
+ if (j_info->skipbits[count / 8] & (1 << (7 - (count % 8)))) {
+ /* skip */
+ while (length > 0) {
+ nb_read = fread(work_buffer, sizeof(char),
+ MIN(length, WORK_BUFFER_SIZE), fp);
+ length -= nb_read;
+ }
+ } else {
+ work_buffer[0] = (char) 0xff;
+ work_buffer[1] = (char) marker;
+ work_buffer[2] = ((length + 2) >> 8) & 0xff;
+ work_buffer[3] = (length + 2) & 0xff;
+ pdf_add_stream(stream, work_buffer, 4);
+ while (length > 0) {
+ nb_read = fread(work_buffer, sizeof(char),
+ MIN(length, WORK_BUFFER_SIZE), fp);
+ if (nb_read > 0)
+ pdf_add_stream(stream, work_buffer, nb_read);
+ length -= nb_read;
+ }
+ }
+ }
+ count++;
+ }
+
+ while ((length = fread(work_buffer,
+ sizeof(char), WORK_BUFFER_SIZE, fp)) > 0) {
+ pdf_add_stream(stream, work_buffer, length);
+ }
+
+ return (found_SOFn ? 0 : -1);
+}
+
+static int
+JPEG_scan_file (struct JPEG_info *j_info, FILE *fp)
+{
+ JPEG_marker marker;
+ unsigned short length;
+ int found_SOFn, count;
+ char app_sig[128];
+
+ rewind(fp);
+ count = 0;
+ found_SOFn = 0;
+ while (!found_SOFn &&
+ (marker = JPEG_get_marker(fp)) >= 0) {
+ if (marker == JM_SOI ||
+ (marker >= JM_RST0 && marker <= JM_RST7)) {
+ count++;
+ continue;
+ }
+ length = get_unsigned_pair(fp) - 2;
+ switch (marker) {
+ case JM_SOF0: case JM_SOF1: case JM_SOF2: case JM_SOF3:
+ case JM_SOF5: case JM_SOF6: case JM_SOF7: case JM_SOF9:
+ case JM_SOF10: case JM_SOF11: case JM_SOF13: case JM_SOF14:
+ case JM_SOF15:
+ j_info->bits_per_component = get_unsigned_byte(fp);
+ j_info->height = get_unsigned_pair(fp);
+ j_info->width = get_unsigned_pair(fp);
+ j_info->num_components = get_unsigned_byte(fp);
+ found_SOFn = 1;
+ break;
+ case JM_APP0:
+ if (length > 5) {
+ if (fread(app_sig, sizeof(char), 5, fp) != 5)
+ return -1;
+ length -= 5;
+ if (!memcmp(app_sig, "JFIF\000", 5)) {
+ j_info->flags |= HAVE_APPn_JFIF;
+ length -= read_APP0_JFIF(j_info, fp, length);
+ } else if (!memcmp(app_sig, "JFXX", 5)) {
+ length -= read_APP0_JFXX(j_info, fp, length);
+ }
+ }
+ seek_relative(fp, length);
+ break;
+ case JM_APP1:
+ if (length > 5) {
+ if (fread(app_sig, sizeof(char), 5, fp) != 5)
+ return -1;
+ length -= 5;
+ if (!memcmp(app_sig, "Exif\000", 5)) {
+ j_info->flags |= HAVE_APPn_Exif;
+ length -= read_APP1_Exif(j_info, fp, length);
+ }
+ }
+ seek_relative(fp, length);
+ break;
+ case JM_APP2:
+ if (length >= 14) {
+ if (fread(app_sig, sizeof(char), 12, fp) != 12)
+ return -1;
+ length -= 12;
+ if (!memcmp(app_sig, "ICC_PROFILE\000", 12)) {
+ j_info->flags |= HAVE_APPn_ICC;
+ length -= read_APP2_ICC(j_info, fp, length);
+ if (count < MAX_COUNT) {
+ j_info->skipbits[count / 8] |= (1 << (7 - (count % 8)));
+ }
+ }
+ }
+ seek_relative(fp, length);
+ break;
+ case JM_APP14:
+ if (length > 5) {
+ if (fread(app_sig, sizeof(char), 5, fp) != 5)
+ return -1;
+ length -= 5;
+ if (!memcmp(app_sig, "Adobe", 5)) {
+ j_info->flags |= HAVE_APPn_ADOBE;
+ length -= read_APP14_Adobe(j_info, fp, length);
+ } else {
+ if (count < MAX_COUNT) {
+ j_info->skipbits[count/8] |= (1 << (7 - (count % 8)));
+ }
+ }
+ }
+ seek_relative(fp, length);
+ break;
+ default:
+ seek_relative(fp, length);
+ if (marker >= JM_APP0 &&
+ marker <= JM_APP15) {
+ if (count < MAX_COUNT) {
+ j_info->skipbits[count / 8] |= (1 << (7 - (count % 8)));
+ }
+ }
+ break;
+ }
+ count++;
+ }
+
+ return (found_SOFn ? 0 : -1);
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/jpegimage.h b/Build/source/texk/dvipdf-x/xsrc/jpegimage.h
new file mode 100644
index 00000000000..5a3c9d86a3d
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/jpegimage.h
@@ -0,0 +1,36 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _JPEGIMAGE_H_
+#define _JPEGIMAGE_H_
+
+#include "mfileio.h"
+#include "pdfximage.h"
+
+extern int check_for_jpeg (FILE *fp);
+extern int jpeg_include_image (pdf_ximage *ximage, FILE *fp);
+
+#endif /* _JPEGIMAGE_H_ */
+
+
diff --git a/Build/source/texk/dvipdf-x/xsrc/mpost.c b/Build/source/texk/dvipdf-x/xsrc/mpost.c
new file mode 100644
index 00000000000..dc56d7f4f47
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/mpost.c
@@ -0,0 +1,1671 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2007-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <ctype.h>
+#include <string.h>
+#include <math.h>
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+#include "mfileio.h"
+#include "numbers.h"
+
+#include "tfm.h"
+
+#include "pdfobj.h"
+#include "pdfparse.h"
+#include "pdfdev.h"
+#include "pdfdoc.h"
+
+#include "pdfcolor.h"
+#include "pdfdraw.h"
+
+#include "fontmap.h"
+#include "subfont.h"
+
+#include "pdfximage.h"
+
+#include "mpost.h"
+
+/*
+ * In PDF, current path is not a part of graphics state parameter.
+ * Hence, current path is not saved by the "q" operator and is not
+ * recovered by the "Q" operator. This means that the following PS
+ * code
+ *
+ * <path construction> gsave <path painting> grestore ...
+ *
+ * can't be translated to PDF code
+ *
+ * <path construction> q <path painting> Q ...
+ *
+ * . Only clipping path (which is graphics state parameter in PDF
+ * too) is treated in the same way. So, we write clipping path
+ * immediately and forget about it but remember current path.
+ */
+
+static int mp_parse_body (const char **start, const char *end, double x_user, double y_user);
+
+static struct mp_font
+{
+ char *font_name;
+ int font_id;
+ int tfm_id; /* Used for text width calculation */
+ int subfont_id;
+ double pt_size;
+} font_stack[PDF_GSAVE_MAX] = {
+ {NULL, -1, -1, -1, 0}
+};
+static int currentfont = -1;
+
+#define CURRENT_FONT() ((currentfont < 0) ? NULL : &font_stack[currentfont])
+
+/* Compatibility */
+#define MP_CMODE_MPOST 0
+#define MP_CMODE_DVIPSK 1
+#define MP_CMODE_PTEXVERT 2
+static int mp_cmode = MP_CMODE_MPOST;
+
+static int
+mp_setfont (const char *font_name, double pt_size)
+{
+ const char *name = font_name;
+ struct mp_font *font;
+ int subfont_id = -1;
+ fontmap_rec *mrec;
+
+ font = CURRENT_FONT();
+
+ if (font) {
+ if (!strcmp(font->font_name, font_name) &&
+ font->pt_size == pt_size)
+ return 0;
+ } else { /* No currentfont */
+/* ***TODO*** Here some problem exists! */
+ font = &font_stack[0];
+ font->font_name = NULL;
+ currentfont = 0;
+ }
+
+ mrec = pdf_lookup_fontmap_record(font_name);
+ if (mrec && mrec->charmap.sfd_name && mrec->charmap.subfont_id) {
+ subfont_id = sfd_load_record(mrec->charmap.sfd_name, mrec->charmap.subfont_id);
+ }
+
+ /* See comments in dvi_locate_font() in dvi.c. */
+ if (mrec && mrec->map_name) {
+ name = mrec->map_name;
+ } else {
+ name = font_name;
+ }
+
+ if (font->font_name)
+ RELEASE(font->font_name);
+ font->font_name = NEW(strlen(font_name) + 1, char);
+ strcpy(font->font_name, font_name);
+ font->subfont_id = subfont_id;
+ font->pt_size = pt_size;
+ font->tfm_id = tfm_open(font_name, 0); /* Need not exist in MP mode */
+ font->font_id = pdf_dev_locate_font(name,
+ (spt_t) (pt_size * dev_unit_dviunit()));
+
+ if (font->font_id < 0) {
+ ERROR("MPOST: No physical font assigned for \"%s\".", font_name);
+ return 1;
+ }
+
+ return 0;
+}
+
+static void
+save_font (void)
+{
+ struct mp_font *current, *next;
+
+ if (currentfont < 0) {
+ font_stack[0].font_name = NEW(strlen("Courier") + 1, char);
+ strcpy(font_stack[0].font_name, "Courier");
+ font_stack[0].pt_size = 1;
+ font_stack[0].tfm_id = 0;
+ font_stack[0].subfont_id = 0;
+ currentfont = 0;
+ }
+
+ current = &font_stack[currentfont++];
+ next = &font_stack[currentfont ];
+ next->font_name = NEW(strlen(current->font_name)+1, char);
+ strcpy(next->font_name, current->font_name);
+ next->pt_size = current->pt_size;
+
+ next->subfont_id = current->subfont_id;
+ next->tfm_id = current->tfm_id;
+}
+
+static void
+restore_font (void)
+{
+ struct mp_font *current;
+
+ current = CURRENT_FONT();
+ if (current) {
+ if (current->font_name)
+ RELEASE(current->font_name);
+ current->font_name = NULL;
+ } else {
+ ERROR("No currentfont...");
+ }
+
+ currentfont--;
+}
+
+static void
+clear_fonts (void)
+{
+ while (currentfont >= 0) {
+ if (font_stack[currentfont].font_name)
+ RELEASE(font_stack[currentfont].font_name);
+ currentfont--;
+ }
+}
+
+static int
+is_fontname (const char *token)
+{
+ fontmap_rec *mrec;
+
+ mrec = pdf_lookup_fontmap_record(token);
+ if (mrec)
+ return 1;
+
+ return tfm_exists(token);
+}
+
+int
+mps_scan_bbox (const char **pp, const char *endptr, pdf_rect *bbox)
+{
+ char *number;
+ double values[4];
+ int i;
+
+ /* skip_white() skips lines starting '%'... */
+ while (*pp < endptr && isspace(**pp))
+ (*pp)++;
+
+ /* Scan for bounding box record */
+ while (*pp < endptr && **pp == '%') {
+ if (*pp + 14 < endptr &&
+ !strncmp(*pp, "%%BoundingBox:", 14)) {
+
+ *pp += 14;
+
+ for (i = 0; i < 4; i++) {
+ skip_white(pp, endptr);
+ number = parse_number(pp, endptr);
+ if (!number) {
+ break;
+ }
+ values[i] = atof(number);
+ RELEASE(number);
+ }
+ if (i < 4) {
+ return -1;
+ } else {
+ bbox->llx = values[0];
+ bbox->lly = values[1];
+ bbox->urx = values[2];
+ bbox->ury = values[3];
+
+ return 0;
+ }
+ }
+ skip_line (pp, endptr);
+ while (*pp < endptr && isspace(**pp))
+ (*pp)++;
+ }
+
+ return -1;
+}
+
+static void
+skip_prolog (const char **start, const char *end)
+{
+ int found_prolog = 0;
+ const char *save;
+
+ save = *start;
+ while (*start < end) {
+ if (**start != '%')
+ skip_white(start, end);
+ if (*start >= end)
+ break;
+ if (!strncmp(*start, "%%EndProlog", 11)) {
+ found_prolog = 1;
+ skip_line(start, end);
+ break;
+ } else if (!strncmp(*start, "%%Page:", 7)) {
+ skip_line(start, end);
+ break;
+ }
+ skip_line(start, end);
+ }
+ if (!found_prolog) {
+ *start = save;
+ }
+
+ return;
+}
+
+/* PostScript Operators */
+
+#define ADD 1
+#define SUB 2
+#define MUL 3
+#define DIV 4
+#define NEG 5
+#define TRUNCATE 6
+
+#define CLEAR 10
+#define EXCH 11
+#define POP 12
+
+#define NEWPATH 31
+#define CLOSEPATH 32
+#define MOVETO 33
+#define RMOVETO 34
+#define CURVETO 35
+#define RCURVETO 36
+#define LINETO 37
+#define RLINETO 38
+#define ARC 39
+#define ARCN 40
+
+#define FILL 41
+#define STROKE 42
+#define SHOW 43
+
+#define CLIP 44
+#define EOCLIP 45
+
+#define SHOWPAGE 49
+
+#define GSAVE 50
+#define GRESTORE 51
+
+#define CONCAT 52
+#define SCALE 53
+#define TRANSLATE 54
+#define ROTATE 55
+
+#define SETLINEWIDTH 60
+#define SETDASH 61
+#define SETLINECAP 62
+#define SETLINEJOIN 63
+#define SETMITERLIMIT 64
+
+#define SETGRAY 70
+#define SETRGBCOLOR 71
+#define SETCMYKCOLOR 72
+
+#define CURRENTPOINT 80
+#define IDTRANSFORM 81
+#define DTRANSFORM 82
+
+#define FINDFONT 201
+#define SCALEFONT 202
+#define SETFONT 203
+#define CURRENTFONT 204
+
+#define STRINGWIDTH 210
+
+#define DEF 999
+
+#define FSHOW 1001
+#define STEXFIG 1002
+#define ETEXFIG 1003
+#define HLW 1004
+#define VLW 1005
+#define RD 1006
+#define B 1007
+
+static struct operators
+{
+ const char *token;
+ int opcode;
+} ps_operators[] = {
+ {"add", ADD},
+ {"mul", MUL},
+ {"div", DIV},
+ {"neg", NEG},
+ {"sub", SUB},
+ {"truncate", TRUNCATE},
+
+ {"clear", CLEAR},
+ {"exch", EXCH},
+ {"pop", POP},
+
+ {"clip", CLIP},
+ {"eoclip", EOCLIP},
+ {"closepath", CLOSEPATH},
+ {"concat", CONCAT},
+
+ {"newpath", NEWPATH},
+ {"moveto", MOVETO},
+ {"rmoveto", RMOVETO},
+ {"lineto", LINETO},
+ {"rlineto", RLINETO},
+ {"curveto", CURVETO},
+ {"rcurveto", RCURVETO},
+ {"arc", ARC},
+ {"arcn", ARCN},
+
+ {"stroke", STROKE},
+ {"fill", FILL},
+ {"show", SHOW},
+ {"showpage", SHOWPAGE},
+
+ {"gsave", GSAVE},
+ {"grestore", GRESTORE},
+ {"translate", TRANSLATE},
+ {"rotate", ROTATE},
+ {"scale", SCALE},
+
+ {"setlinecap", SETLINECAP},
+ {"setlinejoin", SETLINEJOIN},
+ {"setlinewidth", SETLINEWIDTH},
+ {"setmiterlimit", SETMITERLIMIT},
+ {"setdash", SETDASH},
+
+ {"setgray", SETGRAY},
+ {"setrgbcolor", SETRGBCOLOR},
+ {"setcmykcolor", SETCMYKCOLOR},
+
+ {"currentpoint", CURRENTPOINT}, /* This is here for rotate support
+ in graphics package-not MP support */
+ {"dtransform", DTRANSFORM},
+ {"idtransform", IDTRANSFORM},
+
+ {"findfont", FINDFONT},
+ {"scalefont", SCALEFONT},
+ {"setfont", SETFONT},
+ {"currentfont", CURRENTFONT},
+
+ {"stringwidth", STRINGWIDTH},
+
+ {"def", DEF} /* not implemented yet; just work with mptopdf */
+};
+
+static struct operators mps_operators[] = {
+ {"fshow", FSHOW}, /* exch findfont exch scalefont setfont show */
+ {"startTexFig", STEXFIG},
+ {"endTexFig", ETEXFIG},
+ {"hlw", HLW}, /* 0 dtransform exch truncate exch idtransform pop setlinewidth */
+ {"vlw", VLW}, /* 0 exch dtransform truncate idtransform pop setlinewidth pop */
+ {"l", LINETO},
+ {"r", RLINETO},
+ {"c", CURVETO},
+ {"m", MOVETO},
+ {"p", CLOSEPATH},
+ {"n", NEWPATH},
+ {"C", SETCMYKCOLOR},
+ {"G", SETGRAY},
+ {"R", SETRGBCOLOR},
+ {"lj", SETLINEJOIN},
+ {"ml", SETMITERLIMIT},
+ {"lc", SETLINECAP},
+ {"S", STROKE},
+ {"F", FILL},
+ {"q", GSAVE},
+ {"Q", GRESTORE},
+ {"s", SCALE},
+ {"t", CONCAT},
+ {"sd", SETDASH},
+ {"rd", RD}, /* [] 0 setdash */
+ {"P", SHOWPAGE},
+ {"B", B}, /* gsave fill grestore */
+ {"W", CLIP}
+};
+
+#define NUM_PS_OPERATORS (sizeof(ps_operators)/sizeof(ps_operators[0]))
+#define NUM_MPS_OPERATORS (sizeof(mps_operators)/sizeof(mps_operators[0]))
+static int
+get_opcode (const char *token)
+{
+ int i;
+
+ for (i = 0; i < NUM_PS_OPERATORS; i++) {
+ if (!strcmp(token, ps_operators[i].token)) {
+ return ps_operators[i].opcode;
+ }
+ }
+
+ for (i = 0; i < NUM_MPS_OPERATORS; i++) {
+ if (!strcmp(token, mps_operators[i].token)) {
+ return mps_operators[i].opcode;
+ }
+ }
+
+ return -1;
+}
+
+#define PS_STACK_SIZE 1024
+
+static pdf_obj *stack[PS_STACK_SIZE];
+static unsigned top_stack = 0;
+
+#define POP_STACK() ((top_stack > 0) ? stack[--top_stack] : NULL)
+#define PUSH_STACK(o,e) { \
+ if (top_stack < PS_STACK_SIZE) { \
+ stack[top_stack++] = (o); \
+ } else { \
+ WARN("PS stack overflow including MetaPost file or inline PS code"); \
+ *(e) = 1; \
+ } \
+}
+
+static int
+do_exch (void)
+{
+ pdf_obj *tmp;
+
+ if (top_stack < 2)
+ return -1;
+
+ tmp = stack[top_stack-1];
+ stack[top_stack-1] = stack[top_stack-2];
+ stack[top_stack-2] = tmp;
+
+ return 0;
+}
+
+static int
+do_clear (void)
+{
+ pdf_obj *tmp;
+
+ while (top_stack > 0) {
+ tmp = POP_STACK();
+ if (tmp)
+ pdf_release_obj(tmp);
+ }
+
+ return 0;
+}
+
+/* This should be set_bottom and clear (or
+ * have independent stack) to ensure stack
+ * depth do not go below real stack bottom.
+ */
+static void
+mps_stack_clear_to (int depth)
+{
+ pdf_obj *tmp;
+
+ while (top_stack > depth) {
+ tmp = POP_STACK();
+ if (tmp)
+ pdf_release_obj(tmp);
+ }
+
+ return;
+}
+
+static int
+pop_get_numbers (double *values, int count)
+{
+ pdf_obj *tmp;
+
+ while (count-- > 0) {
+ tmp = POP_STACK();
+ if (!tmp) {
+ WARN("mpost: Stack underflow.");
+ break;
+ } else if (!PDF_OBJ_NUMBERTYPE(tmp)) {
+ WARN("mpost: Not a number!");
+ pdf_release_obj(tmp);
+ break;
+ }
+ values[count] = pdf_number_value(tmp);
+ pdf_release_obj(tmp);
+ }
+
+ return (count + 1);
+}
+
+static int
+cvr_array (pdf_obj *array, double *values, int count)
+{
+ if (!PDF_OBJ_ARRAYTYPE(array)) {
+ WARN("mpost: Not an array!");
+ } else {
+ pdf_obj *tmp;
+
+ while (count-- > 0) {
+ tmp = pdf_get_array(array, count);
+ if (!PDF_OBJ_NUMBERTYPE(tmp)) {
+ WARN("mpost: Not a number!");
+ break;
+ }
+ values[count] = pdf_number_value(tmp);
+ }
+ }
+ if (array)
+ pdf_release_obj(array);
+
+ return (count + 1);
+}
+
+static int
+is_fontdict (pdf_obj *dict)
+{
+ pdf_obj *tmp;
+
+ if (!PDF_OBJ_DICTTYPE(dict))
+ return 0;
+
+ tmp = pdf_lookup_dict(dict, "Type");
+ if (!tmp || !PDF_OBJ_NAMETYPE(tmp) ||
+ strcmp(pdf_name_value(tmp), "Font")) {
+ return 0;
+ }
+
+ tmp = pdf_lookup_dict(dict, "FontName");
+ if (!tmp || !PDF_OBJ_NAMETYPE(tmp)) {
+ return 0;
+ }
+
+ tmp = pdf_lookup_dict(dict, "FontScale");
+ if (!tmp || !PDF_OBJ_NUMBERTYPE(tmp)) {
+ return 0;
+ }
+
+ return 1;
+}
+
+static int
+do_findfont (void)
+{
+ int error = 0;
+ pdf_obj *font_dict, *font_name;
+
+ font_name = POP_STACK();
+ if (!font_name)
+ return 1;
+ else if (PDF_OBJ_STRINGTYPE(font_name) ||
+ PDF_OBJ_NAMETYPE(font_name)) {
+ /* Do not check the existence...
+ * The reason for this is that we cannot locate PK font without
+ * font scale.
+ */
+ font_dict = pdf_new_dict();
+ pdf_add_dict(font_dict,
+ pdf_new_name("Type"), pdf_new_name("Font"));
+ if (PDF_OBJ_STRINGTYPE(font_name)) {
+ pdf_add_dict(font_dict,
+ pdf_new_name("FontName"),
+ pdf_new_name(pdf_string_value(font_name)));
+ pdf_release_obj(font_name);
+ } else {
+ pdf_add_dict(font_dict,
+ pdf_new_name("FontName"), font_name);
+ }
+ pdf_add_dict(font_dict,
+ pdf_new_name("FontScale"), pdf_new_number(1.0));
+
+ if (top_stack < PS_STACK_SIZE) {
+ stack[top_stack++] = font_dict;
+ } else {
+ WARN("PS stack overflow including MetaPost file or inline PS code");
+ pdf_release_obj(font_dict);
+ error = 1;
+ }
+ } else {
+ error = 1;
+ }
+
+ return error;
+}
+
+static int
+do_scalefont (void)
+{
+ int error = 0;
+ pdf_obj *font_dict;
+ pdf_obj *font_scale;
+ double scale;
+
+ error = pop_get_numbers(&scale, 1);
+ if (error)
+ return error;
+
+ font_dict = POP_STACK();
+ if (!font_dict)
+ error = 1;
+ else if (is_fontdict(font_dict)) {
+ font_scale = pdf_lookup_dict(font_dict, "FontScale");
+ pdf_set_number(font_scale, pdf_number_value(font_scale)*scale);
+ if (top_stack < PS_STACK_SIZE) {
+ stack[top_stack++] = font_dict;
+ } else {
+ WARN("PS stack overflow including MetaPost file or inline PS code");
+ pdf_release_obj(font_dict);
+ error = 1;
+ }
+ } else {
+ error = 1;
+ }
+
+ return error;
+}
+
+static int
+do_setfont (void)
+{
+ int error = 0;
+ char *font_name;
+ double font_scale;
+ pdf_obj *font_dict;
+
+ font_dict = POP_STACK();
+ if (!is_fontdict(font_dict))
+ error = 1;
+ else {
+ /* Subfont support prevent us from managing
+ * font in a single place...
+ */
+ font_name = pdf_name_value (pdf_lookup_dict(font_dict, "FontName"));
+ font_scale = pdf_number_value(pdf_lookup_dict(font_dict, "FontScale"));
+
+ error = mp_setfont(font_name, font_scale);
+ }
+ pdf_release_obj(font_dict);
+
+ return error;
+}
+
+/* Push dummy font dict onto PS stack */
+static int
+do_currentfont (void)
+{
+ int error = 0;
+ struct mp_font *font;
+ pdf_obj *font_dict;
+
+ font = CURRENT_FONT();
+ if (!font) {
+ WARN("Currentfont undefined...");
+ return 1;
+ } else {
+ font_dict = pdf_new_dict();
+ pdf_add_dict(font_dict,
+ pdf_new_name("Type"),
+ pdf_new_name("Font"));
+ pdf_add_dict(font_dict,
+ pdf_new_name("FontName"),
+ pdf_new_name(font->font_name));
+ pdf_add_dict(font_dict,
+ pdf_new_name("FontScale"),
+ pdf_new_number(font->pt_size));
+ if (top_stack < PS_STACK_SIZE) {
+ stack[top_stack++] = font_dict;
+ } else {
+ WARN("PS stack overflow...");
+ pdf_release_obj(font_dict);
+ error = 1;
+ }
+ }
+
+ return error;
+}
+
+static int
+do_show (void)
+{
+ struct mp_font *font;
+ pdf_coord cp;
+ pdf_obj *text_str;
+ int length;
+ unsigned char *strptr;
+ double text_width;
+
+ font = CURRENT_FONT();
+ if (!font) {
+ WARN("Currentfont not set."); /* Should not be error... */
+ return 1;
+ }
+
+ pdf_dev_currentpoint(&cp);
+
+ text_str = POP_STACK();
+ if (!PDF_OBJ_STRINGTYPE(text_str)) {
+ if (text_str)
+ pdf_release_obj(text_str);
+ return 1;
+ }
+ if (font->font_id < 0) {
+ WARN("mpost: not set."); /* Should not be error... */
+ pdf_release_obj(text_str);
+ return 1;
+ }
+
+ strptr = pdf_string_value (text_str);
+ length = pdf_string_length(text_str);
+
+ if (font->tfm_id < 0) {
+ WARN("mpost: TFM not found for \"%s\".", font->font_name);
+ WARN("mpost: Text width not calculated...");
+ }
+
+ text_width = 0.0;
+ if (font->subfont_id >= 0) {
+ unsigned short uch;
+ unsigned char *ustr;
+ int i;
+
+ ustr = NEW(length * 2, unsigned char);
+ for (i = 0; i < length; i++) {
+ uch = lookup_sfd_record(font->subfont_id, strptr[i]);
+ ustr[2*i ] = uch >> 8;
+ ustr[2*i+1] = uch & 0xff;
+ if (font->tfm_id >= 0) {
+ text_width += tfm_get_width(font->tfm_id, strptr[i]);
+ }
+ }
+ text_width *= font->pt_size;
+
+ pdf_dev_set_string((spt_t)(cp.x * dev_unit_dviunit()),
+ (spt_t)(cp.y * dev_unit_dviunit()),
+ ustr, length * 2,
+ (spt_t)(text_width*dev_unit_dviunit()),
+ font->font_id, 0);
+ RELEASE(ustr);
+ } else {
+#define FWBASE ((double) (1<<20))
+ if (font->tfm_id >= 0) {
+ text_width = (double) tfm_string_width(font->tfm_id, strptr, length)/FWBASE;
+ text_width *= font->pt_size;
+ }
+ pdf_dev_set_string((spt_t)(cp.x * dev_unit_dviunit()),
+ (spt_t)(cp.y * dev_unit_dviunit()),
+ strptr, length,
+ (spt_t)(text_width*dev_unit_dviunit()),
+ font->font_id, 0);
+ }
+
+ if (pdf_dev_get_font_wmode(font->font_id)) {
+ pdf_dev_rmoveto(0.0, -text_width);
+ } else {
+ pdf_dev_rmoveto(text_width, 0.0);
+ }
+
+ graphics_mode();
+ pdf_release_obj(text_str);
+
+ return 0;
+}
+
+static int
+do_mpost_bind_def (const char *ps_code, double x_user, double y_user)
+{
+ int error = 0;
+ const char *start, *end;
+
+ start = ps_code;
+ end = start + strlen(start);
+
+ error = mp_parse_body(&start, end, x_user, y_user);
+
+ return error;
+}
+
+static int
+do_texfig_operator (int opcode, double x_user, double y_user)
+{
+ static transform_info fig_p;
+ static int in_tfig = 0;
+ static int xobj_id = -1;
+ static int count = 0;
+ double values[6];
+ int error = 0;
+
+ switch (opcode) {
+ case STEXFIG:
+ error = pop_get_numbers(values, 6);
+ if (!error) {
+ double dvi2pts;
+ char resname[256];
+
+ transform_info_clear(&fig_p);
+ dvi2pts = 1.0/dev_unit_dviunit();
+
+ fig_p.width = values[0] * dvi2pts;
+ fig_p.height = values[1] * dvi2pts;
+ fig_p.bbox.llx = values[2] * dvi2pts;
+ fig_p.bbox.lly = -values[3] * dvi2pts;
+ fig_p.bbox.urx = values[4] * dvi2pts;
+ fig_p.bbox.ury = -values[5] * dvi2pts;
+ fig_p.flags |= INFO_HAS_USER_BBOX;
+
+ sprintf(resname, "__tf%d__", count);
+ xobj_id = pdf_doc_begin_grabbing(resname,
+ fig_p.bbox.llx, fig_p.bbox.ury, &fig_p.bbox);
+
+ in_tfig = 1;
+ count++;
+ }
+ break;
+ case ETEXFIG:
+ if (!in_tfig)
+ ERROR("endTexFig without valid startTexFig!.");
+
+ pdf_doc_end_grabbing(NULL);
+ pdf_dev_put_image(xobj_id, &fig_p, x_user, y_user);
+ in_tfig = 0;
+ break;
+ default:
+ error = 1;
+ }
+
+ return error;
+}
+
+/*
+ * buggy...
+ */
+
+/*
+ * CTM(Current Transformation Matrix) means the transformation of User Space
+ * to Device Space coordinates. Because DVIPDFMx does not know the resolution
+ * of Device Space, we assume that the resolution is 1/1000.
+ */
+#define DEVICE_RESOLUTION 1000
+static int
+ps_dev_CTM (pdf_tmatrix *M)
+{
+ pdf_dev_currentmatrix(M);
+ M->a *= DEVICE_RESOLUTION; M->b *= DEVICE_RESOLUTION;
+ M->c *= DEVICE_RESOLUTION; M->d *= DEVICE_RESOLUTION;
+ M->e *= DEVICE_RESOLUTION; M->f *= DEVICE_RESOLUTION;
+
+ return 0;
+}
+
+/*
+ * Again, the only piece that needs x_user and y_user is
+ * that piece dealing with texfig.
+ */
+static int
+do_operator (const char *token, double x_user, double y_user)
+{
+ int error = 0;
+ int opcode = 0;
+ double values[12];
+ pdf_obj *tmp = NULL;
+ pdf_tmatrix matrix;
+ pdf_coord cp;
+ pdf_color color;
+
+#define PUSH(o) { \
+ if (top_stack < PS_STACK_SIZE) { \
+ stack[top_stack++] = (o); \
+ } else { \
+ WARN("PS stack overflow including MetaPost file or inline PS code"); \
+ error=1; \
+ break;\
+ } \
+}
+
+ opcode = get_opcode(token);
+
+ switch (opcode) {
+
+ /*
+ * Arithmetic operators
+ */
+ case ADD:
+ error = pop_get_numbers(values, 2);
+ if (!error)
+ PUSH(pdf_new_number(values[0] + values[1]));
+ break;
+ case MUL:
+ error = pop_get_numbers(values, 2);
+ if (!error)
+ PUSH(pdf_new_number(values[0]*values[1]));
+ break;
+ case NEG:
+ error = pop_get_numbers(values, 1);
+ if (!error)
+ PUSH(pdf_new_number(-values[0]));
+ break;
+ case SUB:
+ error = pop_get_numbers(values, 2);
+ if (!error)
+ PUSH(pdf_new_number(values[0] - values[1]));
+ break;
+ case DIV:
+ error = pop_get_numbers(values, 2);
+ if (!error)
+ PUSH(pdf_new_number(values[0]/values[1]));
+ break;
+ case TRUNCATE: /* Round toward zero. */
+ error = pop_get_numbers(values, 1);
+ if (!error)
+ PUSH(pdf_new_number(((values[0] > 0) ? floor(values[0]) : ceil(values[0]))));
+ break;
+
+ /* Stack operation */
+ case CLEAR:
+ error = do_clear();
+ break;
+ case POP:
+ tmp = POP_STACK();
+ if (tmp)
+ pdf_release_obj(tmp);
+ break;
+ case EXCH:
+ error = do_exch();
+ break;
+
+ /* Path construction */
+ case MOVETO:
+ error = pop_get_numbers(values, 2);
+ if (!error)
+ error = pdf_dev_moveto(values[0], values[1]);
+ break;
+ case RMOVETO:
+ error = pop_get_numbers(values, 2);
+ if (!error)
+ error = pdf_dev_rmoveto(values[0], values[1]);
+ break;
+ case LINETO:
+ error = pop_get_numbers(values, 2);
+ if (!error)
+ error = pdf_dev_lineto(values[0], values[1]);
+ break;
+ case RLINETO:
+ error = pop_get_numbers(values, 2);
+ if (!error)
+ error = pdf_dev_rlineto(values[0], values[1]);
+ break;
+ case CURVETO:
+ error = pop_get_numbers(values, 6);
+ if (!error)
+ error = pdf_dev_curveto(values[0], values[1],
+ values[2], values[3],
+ values[4], values[5]);
+ break;
+ case RCURVETO:
+ error = pop_get_numbers(values, 6);
+ if (!error)
+ error = pdf_dev_rcurveto(values[0], values[1],
+ values[2], values[3],
+ values[4], values[5]);
+ break;
+ case CLOSEPATH:
+ error = pdf_dev_closepath();
+ break;
+ case ARC:
+ error = pop_get_numbers(values, 5);
+ if (!error)
+ error = pdf_dev_arc(values[0], values[1],
+ values[2], /* rad */
+ values[3], values[4]);
+ break;
+ case ARCN:
+ error = pop_get_numbers(values, 5);
+ if (!error)
+ error = pdf_dev_arcn(values[0], values[1],
+ values[2], /* rad */
+ values[3], values[4]);
+ break;
+
+ case NEWPATH:
+ pdf_dev_newpath();
+ break;
+ case STROKE:
+ /* fill rule not supported yet */
+ pdf_dev_flushpath('S', PDF_FILL_RULE_NONZERO);
+ break;
+ case FILL:
+ pdf_dev_flushpath('f', PDF_FILL_RULE_NONZERO);
+ break;
+
+ case CLIP:
+ error = pdf_dev_clip();
+ break;
+ case EOCLIP:
+ error = pdf_dev_eoclip();
+ break;
+
+ /* Graphics state operators: */
+ case GSAVE:
+ error = pdf_dev_gsave();
+ save_font();
+ break;
+ case GRESTORE:
+ error = pdf_dev_grestore();
+ restore_font();
+ break;
+
+ case CONCAT:
+ tmp = POP_STACK();
+ error = cvr_array(tmp, values, 6); /* This does pdf_release_obj() */
+ tmp = NULL;
+ if (error)
+ WARN("Missing array before \"concat\".");
+ else {
+ pdf_setmatrix(&matrix,
+ values[0], values[1],
+ values[2], values[3],
+ values[4], values[5]);
+ error = pdf_dev_concat(&matrix);
+ }
+ break;
+ case SCALE:
+ error = pop_get_numbers(values, 2);
+ if (!error) {
+ switch (mp_cmode) {
+#ifndef WITHOUT_ASCII_PTEX
+ case MP_CMODE_PTEXVERT:
+ pdf_setmatrix(&matrix,
+ values[1], 0.0,
+ 0.0 , values[0],
+ 0.0 , 0.0);
+ break;
+#endif /* !WITHOUT_ASCII_PTEX */
+ default:
+ pdf_setmatrix(&matrix,
+ values[0], 0.0,
+ 0.0 , values[1],
+ 0.0 , 0.0);
+ break;
+ }
+
+ error = pdf_dev_concat(&matrix);
+ }
+ break;
+ /* Positive angle means clock-wise direction in graphicx-dvips??? */
+ case ROTATE:
+ error = pop_get_numbers(values, 1);
+ if (!error) {
+ values[0] = values[0] * M_PI / 180;
+
+ switch (mp_cmode) {
+ case MP_CMODE_DVIPSK:
+ case MP_CMODE_MPOST: /* Really? */
+#ifndef WITHOUT_ASCII_PTEX
+ case MP_CMODE_PTEXVERT:
+#endif /* !WITHOUT_ASCII_PTEX */
+ pdf_setmatrix(&matrix,
+ cos(values[0]), -sin(values[0]),
+ sin(values[0]), cos(values[0]),
+ 0.0, 0.0);
+ break;
+ default:
+ pdf_setmatrix(&matrix,
+ cos(values[0]) , sin(values[0]),
+ -sin(values[0]), cos(values[0]),
+ 0.0, 0.0);
+ break;
+ }
+ error = pdf_dev_concat(&matrix);
+ }
+ break;
+ case TRANSLATE:
+ error = pop_get_numbers(values, 2);
+ if (!error) {
+ pdf_setmatrix(&matrix,
+ 1.0, 0.0,
+ 0.0, 1.0,
+ values[0], values[1]);
+ error = pdf_dev_concat(&matrix);
+ }
+ break;
+
+ case SETDASH:
+ error = pop_get_numbers(values, 1);
+ if (!error) {
+ pdf_obj *pattern, *dash;
+ int i, num_dashes;
+ double dash_values[PDF_DASH_SIZE_MAX];
+ double offset;
+
+ offset = values[0];
+ pattern = POP_STACK();
+ if (!PDF_OBJ_ARRAYTYPE(pattern)) {
+ if (pattern)
+ pdf_release_obj(pattern);
+ error = 1;
+ break;
+ }
+ num_dashes = pdf_array_length(pattern);
+ if (num_dashes > PDF_DASH_SIZE_MAX) {
+ WARN("Too many dashes...");
+ pdf_release_obj(pattern);
+ error = 1;
+ break;
+ }
+ for (i = 0;
+ i < num_dashes && !error ; i++) {
+ dash = pdf_get_array(pattern, i);
+ if (!PDF_OBJ_NUMBERTYPE(dash))
+ error = 1;
+ else {
+ dash_values[i] = pdf_number_value(dash);
+ }
+ }
+ pdf_release_obj(pattern);
+ if (!error) {
+ error = pdf_dev_setdash(num_dashes, dash_values, offset);
+ }
+ }
+ break;
+ case SETLINECAP:
+ error = pop_get_numbers(values, 1);
+ if (!error)
+ error = pdf_dev_setlinecap((int)values[0]);
+ break;
+ case SETLINEJOIN:
+ error = pop_get_numbers(values, 1);
+ if (!error)
+ error = pdf_dev_setlinejoin((int)values[0]);
+ break;
+ case SETLINEWIDTH:
+ error = pop_get_numbers(values, 1);
+ if (!error)
+ error = pdf_dev_setlinewidth(values[0]);
+ break;
+ case SETMITERLIMIT:
+ error = pop_get_numbers(values, 1);
+ if (!error)
+ error = pdf_dev_setmiterlimit(values[0]);
+ break;
+
+ case SETCMYKCOLOR:
+ error = pop_get_numbers(values, 4);
+ /* Not handled properly */
+ if (!error) {
+ pdf_color_cmykcolor(&color,
+ values[0], values[1],
+ values[2], values[3]);
+ pdf_dev_set_color(&color);
+ }
+ break;
+ case SETGRAY:
+ /* Not handled properly */
+ error = pop_get_numbers(values, 1);
+ if (!error) {
+ pdf_color_graycolor(&color, values[0]);
+ pdf_dev_set_color(&color);
+ }
+ break;
+ case SETRGBCOLOR:
+ error = pop_get_numbers(values, 3);
+ if (!error) {
+ pdf_color_rgbcolor(&color,
+ values[0], values[1], values[2]);
+ pdf_dev_set_color(&color);
+ }
+ break;
+
+ case SHOWPAGE: /* Let's ignore this for now */
+ break;
+
+ case CURRENTPOINT:
+ error = pdf_dev_currentpoint(&cp);
+ if (!error) {
+ PUSH(pdf_new_number(cp.x));
+ PUSH(pdf_new_number(cp.y));
+ }
+ break;
+
+ case DTRANSFORM:
+ {
+ int has_matrix = 0;
+
+ tmp = POP_STACK();
+ if (PDF_OBJ_ARRAYTYPE(tmp)) {
+ error = cvr_array(tmp, values, 6); /* This does pdf_release_obj() */
+ tmp = NULL;
+ if (error)
+ break;
+ pdf_setmatrix(&matrix,
+ values[0], values[1],
+ values[2], values[3],
+ values[4], values[5]);
+ tmp = POP_STACK();
+ has_matrix = 1;
+ }
+
+ if (!PDF_OBJ_NUMBERTYPE(tmp)) {
+ error = 1;
+ break;
+ }
+ cp.y = pdf_number_value(tmp);
+ pdf_release_obj(tmp);
+
+ tmp = POP_STACK();
+ if (!PDF_OBJ_NUMBERTYPE(tmp)) {
+ error = 1;
+ break;
+ }
+ cp.x = pdf_number_value(tmp);
+ pdf_release_obj(tmp);
+
+ if (!has_matrix) {
+ ps_dev_CTM(&matrix); /* Here, we need real PostScript CTM */
+ }
+ pdf_dev_dtransform(&cp, &matrix);
+ PUSH(pdf_new_number(cp.x));
+ PUSH(pdf_new_number(cp.y));
+ }
+ break;
+
+ case IDTRANSFORM:
+ {
+ int has_matrix = 0;
+
+ tmp = POP_STACK();
+ if (PDF_OBJ_ARRAYTYPE(tmp)) {
+ error = cvr_array(tmp, values, 6); /* This does pdf_release_obj() */
+ tmp = NULL;
+ if (error)
+ break;
+ pdf_setmatrix(&matrix,
+ values[0], values[1],
+ values[2], values[3],
+ values[4], values[5]);
+ tmp = POP_STACK();
+ has_matrix = 1;
+ }
+
+ if (!PDF_OBJ_NUMBERTYPE(tmp)) {
+ error = 1;
+ break;
+ }
+ cp.y = pdf_number_value(tmp);
+ pdf_release_obj(tmp);
+
+ tmp = POP_STACK();
+ if (!PDF_OBJ_NUMBERTYPE(tmp)) {
+ error = 1;
+ break;
+ }
+ cp.x = pdf_number_value(tmp);
+ pdf_release_obj(tmp);
+
+ if (!has_matrix) {
+ ps_dev_CTM(&matrix); /* Here, we need real PostScript CTM */
+ }
+ pdf_dev_idtransform(&cp, &matrix);
+ PUSH(pdf_new_number(cp.x));
+ PUSH(pdf_new_number(cp.y));
+ break;
+ }
+
+ case FINDFONT:
+ error = do_findfont();
+ break;
+ case SCALEFONT:
+ error = do_scalefont();
+ break;
+ case SETFONT:
+ error = do_setfont();
+ break;
+ case CURRENTFONT:
+ error = do_currentfont();
+ break;
+
+ case SHOW:
+ error = do_show();
+ break;
+
+ case STRINGWIDTH:
+ error = 1;
+ break;
+
+ /* Extensions */
+ case FSHOW:
+ error = do_mpost_bind_def("exch findfont exch scalefont setfont show", x_user, y_user);
+ break;
+ case STEXFIG:
+ case ETEXFIG:
+ error = do_texfig_operator(opcode, x_user, y_user);
+ break;
+ case HLW:
+ error = do_mpost_bind_def("0 dtransform exch truncate exch idtransform pop setlinewidth", x_user, y_user);
+ break;
+ case VLW:
+ error = do_mpost_bind_def("0 exch dtransform truncate idtransform setlinewidth pop", x_user, y_user);
+ break;
+ case RD:
+ error = do_mpost_bind_def("[] 0 setdash", x_user, y_user);
+ break;
+ case B:
+ error = do_mpost_bind_def("gsave fill grestore", x_user, y_user);
+ break;
+
+ case DEF:
+ tmp = POP_STACK();
+ tmp = POP_STACK();
+ /* do nothing; not implemented yet */
+ break;
+
+ default:
+ if (is_fontname(token)) {
+ PUSH(pdf_new_name(token));
+ } else {
+ WARN("Unknown token \"%s\"", token);
+ error = 1;
+ }
+ break;
+ }
+
+ return error;
+}
+
+/*
+ * The only sections that need to know x_user and y _user are those
+ * dealing with texfig.
+ */
+static int
+mp_parse_body (const char **start, const char *end, double x_user, double y_user)
+{
+ char *token;
+ pdf_obj *obj;
+ int error = 0;
+
+ skip_white(start, end);
+ while (*start < end && !error) {
+ if (isdigit(**start) ||
+ (*start < end - 1 &&
+ (**start == '+' || **start == '-' || **start == '.' ))) {
+ double value;
+ char *next;
+
+ value = strtod(*start, &next);
+ if (next < end && !strchr("<([{/%", *next) && !isspace(*next)) {
+ WARN("Unkown PostScript operator.");
+ dump(*start, next);
+ error = 1;
+ } else {
+ PUSH(pdf_new_number(value));
+ *start = next;
+ }
+ /*
+ * PDF parser can't handle PS operator inside arrays.
+ * This shouldn't use parse_pdf_array().
+ */
+ } else if (**start == '[' &&
+ (obj = parse_pdf_array(start, end, NULL))) {
+ PUSH(obj);
+ /* This cannot handle ASCII85 string. */
+ } else if (*start < end - 1 &&
+ (**start == '<' && *(*start+1) == '<') &&
+ (obj = parse_pdf_dict(start, end, NULL))) {
+ PUSH(obj);
+ } else if ((**start == '(' || **start == '<') &&
+ (obj = parse_pdf_string (start, end))) {
+ PUSH(obj);
+ } else if (**start == '/' &&
+ (obj = parse_pdf_name(start, end))) {
+ PUSH(obj);
+ } else {
+ token = parse_ident(start, end);
+ if (!token)
+ error = 1;
+ else {
+ error = do_operator(token, x_user, y_user);
+ RELEASE(token);
+ }
+ }
+ skip_white(start, end);
+ }
+
+ return error;
+}
+
+void
+mps_eop_cleanup (void)
+{
+ clear_fonts();
+ do_clear();
+}
+
+int
+mps_stack_depth (void)
+{
+ return top_stack;
+}
+
+int
+mps_exec_inline (const char **p, const char *endptr,
+ double x_user, double y_user)
+{
+ int error;
+ int dirmode, autorotate;
+
+ /* Compatibility for dvipsk. */
+ dirmode = pdf_dev_get_dirmode();
+ if (dirmode) {
+ mp_cmode = MP_CMODE_PTEXVERT;
+ } else {
+ mp_cmode = MP_CMODE_DVIPSK;
+ }
+
+ autorotate = pdf_dev_get_param(PDF_DEV_PARAM_AUTOROTATE);
+ pdf_dev_set_param(PDF_DEV_PARAM_AUTOROTATE, 0);
+ //pdf_color_push(); /* ... */
+
+ /* Comment in dvipdfm:
+ * Remember that x_user and y_user are off by 0.02 %
+ */
+ pdf_dev_moveto(x_user, y_user);
+ error = mp_parse_body(p, endptr, x_user, y_user);
+
+ //pdf_color_pop(); /* ... */
+ pdf_dev_set_param(PDF_DEV_PARAM_AUTOROTATE, autorotate);
+ pdf_dev_set_dirmode(dirmode);
+
+ return error;
+}
+
+/* mp inclusion is a bit of a hack. The routine
+ * starts a form at the lower left corner of
+ * the page and then calls begin_form_xobj telling
+ * it to record the image drawn there and bundle it
+ * up in an xojbect. This allows us to use the coordinates
+ * in the MP file directly. This appears to be the
+ * easiest way to be able to use the pdf_dev_set_string()
+ * command (with its scaled and extended fonts) without
+ * getting all confused about the coordinate system.
+ * After the xobject is created, the whole thing can
+ * be scaled any way the user wants
+ */
+
+/* Should implement save and restore. */
+int
+mps_include_page (const char *ident, FILE *fp)
+{
+ int form_id;
+ xform_info info;
+ int st_depth, gs_depth;
+ char *buffer;
+ const char *p, *endptr;
+ long length, nb_read;
+ int dirmode, autorotate, error;
+
+ rewind(fp);
+
+ length = file_size(fp);
+ if (length < 1) {
+ WARN("Can't read any byte in the MPS file.");
+ return -1;
+ }
+
+ buffer = NEW(length + 1, char);
+ buffer[length] = '\0';
+ p = buffer;
+ endptr = p + length;
+
+ while (length > 0) {
+ nb_read = fread(buffer, sizeof(char), length, fp);
+ if (nb_read < 0) {
+ RELEASE(buffer);
+ WARN("Reading file failed...");
+ return -1;
+ }
+ length -= nb_read;
+ }
+
+ error = mps_scan_bbox(&p, endptr, &(info.bbox));
+ if (error) {
+ WARN("Error occured while scanning MetaPost file headers: Could not find BoundingBox.");
+ RELEASE(buffer);
+ return -1;
+ }
+ skip_prolog(&p, endptr);
+
+ dirmode = pdf_dev_get_dirmode();
+ autorotate = pdf_dev_get_param(PDF_DEV_PARAM_AUTOROTATE);
+ pdf_dev_set_param(PDF_DEV_PARAM_AUTOROTATE, 0);
+ //pdf_color_push();
+
+ form_id = pdf_doc_begin_grabbing(ident, 0.0, 0.0, &(info.bbox));
+
+ mp_cmode = MP_CMODE_MPOST;
+ gs_depth = pdf_dev_current_depth();
+ st_depth = mps_stack_depth();
+ /* At this point the gstate must be initialized, since it starts a new
+ * XObject. Note that it increase gs_depth by 1. */
+ pdf_dev_push_gstate();
+
+ error = mp_parse_body(&p, endptr, 0.0, 0.0);
+ RELEASE(buffer);
+
+ if (error) {
+ WARN("Errors occured while interpreting MPS file.");
+ /* WARN("Leaving garbage in output PDF file."); */
+ form_id = -1;
+ }
+
+ /* It's time to pop the new gstate above. */
+ pdf_dev_pop_gstate();
+ mps_stack_clear_to (st_depth);
+ pdf_dev_grestore_to(gs_depth);
+
+ pdf_doc_end_grabbing(NULL);
+
+ //pdf_color_pop();
+ pdf_dev_set_param(PDF_DEV_PARAM_AUTOROTATE, autorotate);
+ pdf_dev_set_dirmode(dirmode);
+
+ return form_id;
+}
+
+int
+mps_do_page (FILE *image_file)
+{
+ int error = 0;
+ pdf_rect bbox;
+ char *buffer;
+ const char *start, *end;
+ long size;
+ int dir_mode;
+
+ rewind(image_file);
+ if ((size = file_size(image_file)) == 0) {
+ WARN("Can't read any byte in the MPS file.");
+ return -1;
+ }
+
+ buffer = NEW(size+1, char);
+ fread(buffer, sizeof(char), size, image_file);
+ buffer[size] = 0;
+ start = buffer;
+ end = buffer + size;
+
+ error = mps_scan_bbox(&start, end, &bbox);
+ if (error) {
+ WARN("Error occured while scanning MetaPost file headers: Could not find BoundingBox.");
+ RELEASE(buffer);
+ return -1;
+ }
+
+ mp_cmode = MP_CMODE_MPOST;
+
+ pdf_doc_begin_page (1.0, 0.0, 0.0); /* scale, xorig, yorig */
+ pdf_doc_set_mediabox(pdf_doc_current_page_number(), &bbox);
+
+ dir_mode = pdf_dev_get_dirmode();
+ pdf_dev_set_autorotate(0);
+
+ skip_prolog(&start, end);
+
+ error = mp_parse_body(&start, end, 0.0, 0.0);
+
+ if (error) {
+ WARN("Errors occured while interpreting MetaPost file.");
+ }
+
+ pdf_dev_set_autorotate(1);
+ pdf_dev_set_dirmode(dir_mode);
+
+ pdf_doc_end_page();
+
+ RELEASE(buffer);
+
+ /*
+ * The reason why we don't return XObject itself is
+ * PDF inclusion may not be made so.
+ */
+ return (error ? -1 : 0);
+}
+
+int
+check_for_mp (FILE *image_file)
+{
+ int try_count = 10;
+
+ rewind (image_file);
+ mfgets(work_buffer, WORK_BUFFER_SIZE, image_file);
+ if (strncmp(work_buffer, "%!PS", 4))
+ return 0;
+
+ while (try_count > 0) {
+ mfgets(work_buffer, WORK_BUFFER_SIZE, image_file);
+ if (!strncmp(work_buffer, "%%Creator:", 10)) {
+ if (strlen(work_buffer+10) >= 8 &&
+ strstr(work_buffer+10, "MetaPost"))
+ break;
+ }
+ try_count--;
+ }
+
+ return ((try_count > 0) ? 1 : 0);
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/pdfcolor.c b/Build/source/texk/dvipdf-x/xsrc/pdfcolor.c
new file mode 100644
index 00000000000..77c9c499ea5
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pdfcolor.c
@@ -0,0 +1,1530 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+/* No page independence here...
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+
+#include "dpxfile.h"
+
+#include "pdfdoc.h"
+#include "pdfdev.h"
+
+#include "pdfcolor.h"
+
+
+static int verbose = 0;
+void
+pdf_color_set_verbose (void)
+{
+ verbose++;
+}
+
+int
+pdf_color_rgbcolor (pdf_color *color, double r, double g, double b)
+{
+ ASSERT(color);
+
+ if (r < 0.0 || r > 1.0) {
+ WARN("Invalid color value specified: red=%g", r);
+ return -1;
+ }
+ if (g < 0.0 || g > 1.0) {
+ WARN("Invalid color value specified: green=%g", g);
+ return -1;
+ }
+ if (b < 0.0 || b > 1.0) {
+ WARN("Invalid color value specified: blue=%g", b);
+ return -1;
+ }
+ color->values[0] = r;
+ color->values[1] = g;
+ color->values[2] = b;
+
+ color->num_components = 3;
+
+ return 0;
+}
+
+int
+pdf_color_cmykcolor (pdf_color *color,
+ double c, double m, double y, double k)
+{
+ ASSERT(color);
+
+ if (c < 0.0 || c > 1.0) {
+ WARN("Invalid color value specified: cyan=%g", c);
+ return -1;
+ }
+ if (m < 0.0 || m > 1.0) {
+ WARN("Invalid color value specified: magenta=%g", m);
+ return -1;
+ }
+ if (y < 0.0 || y > 1.0) {
+ WARN("Invalid color value specified: yellow=%g", y);
+ return -1;
+ }
+ if (k < 0.0 || k > 1.0) {
+ WARN("Invalid color value specified: black=%g", k);
+ return -1;
+ }
+
+ color->values[0] = c;
+ color->values[1] = m;
+ color->values[2] = y;
+ color->values[3] = k;
+
+ color->num_components = 4;
+
+ return 0;
+}
+
+int
+pdf_color_graycolor (pdf_color *color, double g)
+{
+ ASSERT(color);
+
+ if (g < 0.0 || g > 1.0) {
+ WARN("Invalid color value specified: gray=%g", g);
+ return -1;
+ }
+
+ color->values[0] = g;
+
+ color->num_components = 1;
+
+ return 0;
+}
+
+
+void
+pdf_color_copycolor (pdf_color *color1, const pdf_color *color2)
+{
+ ASSERT(color1 && color2);
+
+ memcpy(color1, color2, sizeof(pdf_color));
+}
+
+int
+pdf_color_is_white (pdf_color *color)
+{
+ int is_white = 0;
+
+ ASSERT(color);
+
+ switch (color->num_components) {
+ case 1:
+ if (color->values[0] == 1.0)
+ is_white = 1;
+ break;
+ case 4:
+ if (color->values[0] == 0.0 &&
+ color->values[1] == 0.0 &&
+ color->values[2] == 0.0 &&
+ color->values[3] == 0.0) {
+ is_white = 1;
+ }
+ break;
+ case 3:
+ if (color->values[0] == 1.0 &&
+ color->values[1] == 1.0 &&
+ color->values[2] == 1.0) {
+ is_white = 1;
+ }
+ break;
+ default:
+ is_white = 0;
+ break;
+ }
+
+ return is_white;
+}
+
+pdf_color current_fill = {
+ 1,
+ {0.0, 0.0, 0.0, 0.0}
+};
+
+pdf_color current_stroke = {
+ 1,
+ {0.0, 0.0, 0.0, 0.0}
+};
+
+#if 0
+/*
+ * This routine is not a real color matching.
+ */
+static int
+compare_color (const pdf_color *color1, const pdf_color *color2)
+{
+ if (color1->num_components != color2->num_components)
+ return -1;
+
+ switch (color1->num_components) {
+ case 4:
+ if (color1->values[0] == color2->values[0] &&
+ color1->values[1] == color2->values[1] &&
+ color1->values[2] == color2->values[2] &&
+ color1->values[3] == color2->values[3])
+ return 0;
+ break;
+ case 3:
+ if (color1->values[0] == color2->values[0] &&
+ color1->values[1] == color2->values[1] &&
+ color1->values[2] == color2->values[2])
+ return 0;
+ break;
+ case 1:
+ if (color1->values[0] == color2->values[0])
+ return 0;
+ break;
+ }
+
+ return -1;
+}
+#endif
+
+int
+pdf_color_is_valid (pdf_color *color)
+{
+ int i, num_components;
+
+ num_components = color->num_components;
+ if (num_components != 1 &&
+ num_components != 3 &&
+ num_components != 4) {
+ ERROR("Only RGB/CMYK/Gray currently supported.");
+ return 0;
+ }
+
+ for (i = 0; i < num_components; i++) {
+ if (color->values[i] < 0.0 || color->values[i] > 1.0) {
+ WARN("Invalid color value: %g", color->values[i]);
+ return 0;
+ }
+ }
+ return 1;
+}
+
+/* Dvipdfm special */
+pdf_color default_color = {
+ 1,
+ {0.0, 0.0, 0.0, 0.0}
+};
+
+void
+pdf_color_set_default (const pdf_color *color)
+{
+ pdf_color_copycolor(&default_color, color);
+}
+
+#define DEV_COLOR_STACK_MAX 128
+
+static struct {
+ int current;
+ pdf_color stroke[DEV_COLOR_STACK_MAX];
+ pdf_color fill[DEV_COLOR_STACK_MAX];
+} color_stack = {
+ 0,
+};
+
+void
+pdf_color_clear_stack (void)
+{
+ if (color_stack.current > 0) {
+ WARN("You've mistakenly made a global color change within nested colors.");
+ }
+ color_stack.current = 0;
+ pdf_color_copycolor(&color_stack.stroke[color_stack.current], &default_color);
+ pdf_color_copycolor(&color_stack.fill[color_stack.current], &default_color);
+ return;
+}
+
+void
+pdf_color_push (pdf_color *sc, pdf_color *fc)
+{
+ if (color_stack.current >= DEV_COLOR_STACK_MAX-1) {
+ WARN("Color stack overflow. Just ignore.");
+ } else {
+ color_stack.current++;
+ pdf_color_copycolor(&color_stack.stroke[color_stack.current], sc);
+ pdf_color_copycolor(&color_stack.fill[color_stack.current], fc);
+ pdf_dev_reset_color();
+ }
+ return;
+}
+
+void
+pdf_color_pop (void)
+{
+ if (color_stack.current <= 0) {
+ WARN("Color stack underflow. Just ignore.");
+ } else {
+ color_stack.current--;
+ pdf_dev_reset_color();
+ }
+ return;
+}
+
+void
+pdf_color_get_current (pdf_color **sc, pdf_color **fc)
+{
+ *sc = &color_stack.stroke[color_stack.current];
+ *fc = &color_stack.fill[color_stack.current];
+ return;
+}
+
+/* BUG (20060330): color change does not effect on the next page.
+ * The problem is due to the part of grestore because it restores
+ * the color values in the state of gsave which are not correct
+ * if the color values are changed inside of a page.
+ */
+void
+pdf_dev_preserve_color (void)
+{
+ if (color_stack.current > 0) {
+ current_stroke = color_stack.stroke[color_stack.current];
+ current_fill = color_stack.fill[color_stack.current];
+ }
+}
+
+/***************************** COLOR SPACE *****************************/
+
+static int pdf_colorspace_defineresource (const char *ident,
+ int subtype,
+ void *cdata, pdf_obj *resource);
+
+static int pdf_colorspace_findresource (const char *ident,
+ int subtype, const void *cdata);
+
+#if 0
+struct calgray_cdata
+{
+ double white_point[3]; /* required, second component must
+ * be equal to 1.0
+ */
+ double black_point[3]; /* optional, default: [0 0 0] */
+ double gamma; /* optional, default: 1.0 */
+};
+
+struct calrgb_cdata
+{
+ double white_point[3]; /* required, second component must
+ * be equal to 1.0
+ */
+ double black_point[3]; /* optional, default: [0 0 0] */
+ double gamma[3]; /* optional, default: [1 1 1] */
+ double matrix[9]; /* optional, default: identity
+ * [1 0 0 0 1 0 0 0 1]
+ */
+};
+
+static void
+release_calrgb (void *cdata)
+{
+ struct calrgb_cdata *calrgb;
+
+ if (cdata) {
+ calrgb = (struct calrgb_cdata *) cdata;
+ RELEASE(calrgb);
+ }
+}
+
+static int
+compare_calrgb (const char *ident1, const void *cdata1,
+ const char *ident2, const void *cdata2)
+{
+ struct calrgb_cdata *calrgb1;
+ struct calrgb_cdata *calrgb2;
+
+ if (ident1 && ident2 &&
+ !strcmp(ident1, ident2)) {
+ return 0;
+ }
+}
+
+static void
+init_calrgb (struct calrgb_cdata *calrgb)
+{
+ ASSERT(calrgb);
+
+ calrgb->white_point[0] = 1.0;
+ calrgb->white_point[1] = 1.0;
+ calrgb->white_point[2] = 1.0;
+
+ calrgb->black_point[0] = 0.0;
+ calrgb->black_point[1] = 0.0;
+ calrgb->black_point[2] = 0.0;
+
+ calrgb->gamma[0] = 1.0;
+ calrgb->gamma[1] = 1.0;
+ calrgb->gamma[2] = 1.0;
+
+ calrgb->matrix[0] = 1.0;
+ calrgb->matrix[1] = 0.0;
+ calrgb->matrix[2] = 0.0;
+
+ calrgb->matrix[3] = 0.0;
+ calrgb->matrix[4] = 1.0;
+ calrgb->matrix[5] = 0.0;
+
+ calrgb->matrix[6] = 0.0;
+ calrgb->matrix[7] = 0.0;
+ calrgb->matrix[8] = 1.0;
+}
+
+static int
+valid_calrgb (struct calrgb_cdata *calrgb)
+{
+ if (calrgb->white_point[1] != 1.0 ||
+ calrgb->white_point[0] <= 0.0 ||
+ calrgb->white_point[2] <= 0.0)
+ return 0;
+
+ if (calrgb->black_point[0] < 0.0 ||
+ calrgb->black_point[1] < 0.0 ||
+ calrgb->black_point[2] < 0.0)
+ return 0;
+
+ if (calrgb->gamma[0] < 0.0 ||
+ calrgb->gamma[1] < 0.0 ||
+ calrgb->gamma[2] < 0.0)
+ return 0;
+
+ /* matrix should be invertible? */
+
+ return 1;
+}
+
+static pdf_obj *
+pdf_color_make_calrgb_resource (struct calrgb_cdata *calrgb)
+{
+ pdf_obj *colorspace;
+ pdf_obj *calparams, *tmp_array;
+
+ ASSERT(calrgb);
+
+ if (!valid_calrgb(calrgb))
+ return NULL;
+
+ colorspace = pdf_new_array();
+ calparams = pdf_new_dict();
+
+ tmp_array = pdf_new_array();
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->white_point[0], 0.001)));
+ pdf_add_array(tmp_array, pdf_new_number(1.0));
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->white_point[2], 0.001)));
+ pdf_add_dict(calparams, pdf_new_name("WhitePoint"), tmp_array);
+
+ if (calrgb->black_point[0] != 0.0 ||
+ calrgb->black_point[1] != 0.0 ||
+ calrgb->black_point[2] != 0.0) {
+ tmp_array = pdf_new_array();
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->black_point[0], 0.001)));
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->black_point[1], 0.001)));
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->black_point[2], 0.001)));
+ pdf_add_dict(calparams, pdf_new_name("BlackPoint"), tmp_array);
+ }
+
+ if (calrgb->gamma[0] != 1.0 ||
+ calrgb->gamma[1] != 1.0 ||
+ calrgb->gamma[2] != 1.0) {
+ tmp_array = pdf_new_array();
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->gamma[0], 0.001)));
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->gamma[1], 0.001)));
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->gamma[2], 0.001)));
+ pdf_add_dict(calparams, pdf_new_name("Gamma"), tmp_array);
+ }
+
+ if (calrgb->matrix[0] != 1.0 ||
+ calrgb->matrix[1] != 0.0 ||
+ calrgb->matrix[2] != 0.0 ||
+ calrgb->matrix[3] != 0.0 ||
+ calrgb->matrix[4] != 1.0 ||
+ calrgb->matrix[5] != 0.0 ||
+ calrgb->matrix[6] != 0.0 ||
+ calrgb->matrix[7] != 0.0 ||
+ calrgb->matrix[8] != 1.0) {
+ tmp_array = pdf_new_array();
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->matrix[0], 0.001)));
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->matrix[1], 0.001)));
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->matrix[2], 0.001)));
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->matrix[3], 0.001)));
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->matrix[4], 0.001)));
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->matrix[5], 0.001)));
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->matrix[6], 0.001)));
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->matrix[7], 0.001)));
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(calrgb->matrix[8], 0.001)));
+ pdf_add_dict(calparams, pdf_new_name("Matrix"), tmp_array);
+ }
+
+ pdf_add_array(colorspace, pdf_new_name("CalRGB"));
+ pdf_add_array(colorspace, calparams);
+
+ return colorspace;
+}
+#endif
+
+static unsigned char nullbytes16[16] = {
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+};
+
+static struct
+{
+ int major;
+ int minor;
+} icc_versions[] = {
+ {0, 0}, /* PDF-1.0, we don't support them */
+ {0, 0}, /* PDF-1.1, we don't support them */
+ {0, 0}, /* PDF-1.2, we don't support them */
+ {0x02, 0x10}, /* PDF-1.3 */
+ {0x02, 0x20}, /* PDF-1.4 */
+ {0x04, 0x00} /* PDF-1.5 */
+};
+
+static int
+iccp_version_supported (int major, int minor)
+{
+ int pdf_ver;
+
+ pdf_ver = pdf_get_version();
+ if (pdf_ver < 6) {
+ if (icc_versions[pdf_ver].major < major)
+ return 0;
+ else if (icc_versions[pdf_ver].major == major &&
+ icc_versions[pdf_ver].minor < minor)
+ return 0;
+ else {
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+typedef unsigned long iccSig;
+static iccSig
+str2iccSig (const void *s)
+{
+ const char *p;
+
+ p = (const char *) s;
+
+ return (iccSig) ((p[0]<<24)|(p[1]<<16)|(p[2]<<8)|p[3]);
+}
+
+typedef struct
+{
+ long X, Y, Z; /* s15Fixed16Numeber */
+} iccXYZNumber;
+
+typedef struct
+{
+ long size;
+ iccSig CMMType;
+ long version;
+ iccSig devClass;
+ iccSig colorSpace;
+ iccSig PCS; /* Profile Connection Space */
+ char creationDate[12];
+ iccSig acsp;
+ iccSig platform;
+ char flags[4];
+ iccSig devMnfct;
+ iccSig devModel;
+ char devAttr[8];
+ long intent;
+ iccXYZNumber illuminant;
+ iccSig creator;
+ unsigned char ID[16]; /* MD5 checksum with Rendering intent,
+ * Header attrs, Profile ID fields are
+ * set to zeros.
+ */
+ /* 28 bytes reserved - must be set to zeros */
+} iccHeader;
+
+#define iccNullSig 0
+static void
+iccp_init_iccHeader (iccHeader *icch)
+{
+ ASSERT(icch);
+
+ icch->size = 0;
+ icch->CMMType = iccNullSig;
+ icch->version = 0xFFFFFF;
+ icch->devClass = iccNullSig;
+ icch->colorSpace = iccNullSig;
+ icch->PCS = iccNullSig;
+ memset(icch->creationDate, 0, 12);
+ icch->acsp = str2iccSig("ascp");
+ icch->platform = iccNullSig;
+ memset(icch->flags, 0, 4);
+ icch->devMnfct = iccNullSig;
+ icch->devModel = iccNullSig;
+ memset(icch->devAttr, 0, 8);
+ icch->intent = 0;
+ icch->illuminant.X = 0;
+ icch->illuminant.Y = 0;
+ icch->illuminant.Z = 0;
+ icch->creator = iccNullSig;
+ memset(icch->ID, 0, 16);
+}
+
+#define ICC_INTENT_TYPE(n) ((int) (((n) >> 16) & 0xff))
+#define ICC_INTENT_PERCEPTUAL 0
+#define ICC_INTENT_RELATIVE 1
+#define ICC_INTENT_SATURATION 2
+#define ICC_INTENT_ABSOLUTE 3
+
+/*
+ * In ICC profile stream dicrionary, there is /Range whose values must
+ * "match the information in the profile". But where is those values in?
+ *
+ * How should I treat rendering intent?
+ */
+struct iccbased_cdata
+{
+ long sig; /* 'i' 'c' 'c' 'b' */
+
+ unsigned char checksum[16]; /* 16 bytes MD5 Checksum */
+ int colorspace; /* input colorspace:
+ * RGB, Gray, CMYK, (Lab?)
+ */
+ int alternate; /* alternate colorspace (id), unused */
+};
+
+#define check_sig(d,p,q,r,s) ((d) && (d)->sig == ((p)<<24|(q)<<16|(r)<<8|(s)))
+
+static void
+init_iccbased_cdata (struct iccbased_cdata *cdata)
+{
+ ASSERT(cdata);
+
+ cdata->sig = ('i' << 24|'c' << 16|'c' << 8|'b');
+ memset(cdata->checksum, 0, 16);
+ cdata->colorspace = PDF_COLORSPACE_TYPE_INVALID;
+ cdata->alternate = -1;
+
+ return;
+}
+
+static void
+release_iccbased_cdata (struct iccbased_cdata *cdata)
+{
+ ASSERT(check_sig(cdata, 'i', 'c', 'c', 'b'));
+
+ RELEASE(cdata);
+}
+
+static int
+get_num_components_iccbased (const struct iccbased_cdata *cdata)
+{
+ int num_components = 0;
+
+ ASSERT(check_sig(cdata, 'i', 'c', 'c', 'b'));
+
+ switch (cdata->colorspace) {
+ case PDF_COLORSPACE_TYPE_RGB:
+ num_components = 3;
+ break;
+ case PDF_COLORSPACE_TYPE_CMYK:
+ num_components = 4;
+ break;
+ case PDF_COLORSPACE_TYPE_GRAY:
+ num_components = 1;
+ break;
+ case PDF_COLORSPACE_TYPE_CIELAB:
+ num_components = 3;
+ break;
+ }
+
+ return num_components;
+}
+
+static int
+compare_iccbased (const char *ident1, const struct iccbased_cdata *cdata1,
+ const char *ident2, const struct iccbased_cdata *cdata2)
+{
+ if (cdata1 && cdata2) {
+
+ ASSERT(check_sig(cdata1, 'i', 'c', 'c', 'b'));
+ ASSERT(check_sig(cdata2, 'i', 'c', 'c', 'b'));
+
+ if (memcmp(cdata1->checksum, nullbytes16, 16) &&
+ memcmp(cdata2->checksum, nullbytes16, 16)) {
+ return memcmp(cdata1->checksum, cdata2->checksum, 16);
+ }
+ if (cdata1->colorspace != cdata2->colorspace) {
+ return (cdata1->colorspace - cdata2->colorspace);
+ }
+
+ /* Continue if checksum unknown and colorspace is same. */
+ }
+
+ if (ident1 && ident2)
+ return strcmp(ident1, ident2);
+
+ /* No way to compare */
+ return -1;
+}
+
+int
+iccp_check_colorspace (int colortype, const void *profile, long proflen)
+{
+ iccSig colorspace;
+ const unsigned char *p;
+
+ if (!profile || proflen < 128)
+ return -1;
+
+ p = (const unsigned char *) profile;
+
+ colorspace = str2iccSig(p + 16);
+
+ switch (colortype) {
+ case PDF_COLORSPACE_TYPE_CALRGB:
+ case PDF_COLORSPACE_TYPE_RGB:
+ if (colorspace != str2iccSig("RGB ")) {
+ return -1;
+ }
+ break;
+ case PDF_COLORSPACE_TYPE_CALGRAY:
+ case PDF_COLORSPACE_TYPE_GRAY:
+ if (colorspace != str2iccSig("GRAY")) {
+ return -1;
+ }
+ break;
+ case PDF_COLORSPACE_TYPE_CMYK:
+ if (colorspace != str2iccSig("CMYK")) {
+ return -1;
+ }
+ break;
+ default:
+ return -1;
+ break;
+ }
+
+ return 0;
+}
+
+pdf_obj *
+iccp_get_rendering_intent (const void *profile, long proflen)
+{
+ pdf_obj *ri = NULL;
+ const unsigned char *p;
+ long intent;
+
+ if (!profile || proflen < 128)
+ return NULL;
+
+ p = (const unsigned char *) profile;
+
+ intent = (p[64] << 24)|(p[65] << 16)|(p[66] << 8)|p[67];
+ switch (ICC_INTENT_TYPE(intent)) {
+ case ICC_INTENT_SATURATION:
+ ri = pdf_new_name("Saturation");
+ break;
+ case ICC_INTENT_PERCEPTUAL:
+ ri = pdf_new_name("Perceptual");
+ break;
+ case ICC_INTENT_ABSOLUTE:
+ ri = pdf_new_name("AbsoluteColorimetric");
+ break;
+ case ICC_INTENT_RELATIVE:
+ ri = pdf_new_name("RelativeColorimetric");
+ break;
+ default:
+ WARN("Invalid rendering intent type: %d", ICC_INTENT_TYPE(intent));
+ ri = NULL;
+ }
+
+ return ri;
+}
+
+#define sget_signed_long(p) ((long) ((p)[0] << 24|(p)[1] << 16|(p)[2] << 8|(p)[3]))
+#define sget_signed_short(p) ((short) ((p)[0] << 8|(p)[1]))
+#define get_iccSig(p) ((iccSig) ((p)[0] << 24|(p)[1] << 16|(p)[2] << 8|(p)[3]))
+
+static int
+iccp_unpack_header (iccHeader *icch,
+ const void *profile, long proflen, int check_size)
+{
+ const unsigned char *p, *endptr;
+
+ if (check_size) {
+ if (!profile || proflen < 128 ||
+ proflen % 4 != 0) {
+ WARN("Profile size: %ld", proflen);
+ return -1;
+ }
+ }
+
+ p = (const unsigned char *) profile;
+ endptr = p + 128;
+
+ icch->size = sget_signed_long(p);
+ if (check_size) {
+ if (icch->size != proflen) {
+ WARN("ICC Profile size: %ld(header) != %ld", icch->size, proflen);
+ return -1;
+ }
+ }
+ p += 4;
+
+ icch->CMMType = str2iccSig(p);
+ p += 4;
+ icch->version = sget_signed_long(p);
+ p += 4;
+ icch->devClass = str2iccSig(p);
+ p += 4;
+ icch->colorSpace = str2iccSig(p);
+ p += 4;
+ icch->PCS = str2iccSig(p);
+ p += 4;
+ memcpy(icch->creationDate, p, 12);
+ p += 12;
+ icch->acsp = str2iccSig(p); /* acsp */
+ if (icch->acsp != str2iccSig("acsp")) {
+ WARN("Invalid ICC profile: not \"acsp\" - %c%c%c%c ",
+ p[0], p[1], p[2], p[3]);
+ return -1;
+ }
+ p += 4;
+ icch->platform = str2iccSig(p);
+ p += 4;
+ memcpy(icch->flags, p, 4);
+ p += 4;
+ icch->devMnfct = str2iccSig(p);
+ p += 4;
+ icch->devModel = str2iccSig(p);
+ p += 4;
+ memcpy(icch->devAttr, p, 8);
+ p += 8;
+ icch->intent = (p[0] << 24)|(p[1] << 16)|(p[2] << 8)|p[3];
+ p += 4;
+ icch->illuminant.X = sget_signed_long(p);
+ p += 4;
+ icch->illuminant.Y = sget_signed_long(p);
+ p += 4;
+ icch->illuminant.Z = sget_signed_long(p);
+ p += 4;
+ icch->creator = str2iccSig(p);
+ p += 4;
+ memcpy(icch->ID, p, 16);
+ p += 16;
+
+ /* 28 bytes reserved - must be set to zeros */
+ for (; p < endptr; p++) {
+ if (*p != '\0') {
+ WARN("Reserved pad not zero: %02x (at offset %ld in ICC profile header.)",
+ *p, 128 - ((long) (endptr - p)));
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
+/* MD5 checksum with Rendering intent,
+ * Header attrs, Profile ID fields are
+ * set to zeros.
+ */
+#define ICC_HEAD_SECT1_START 0
+#define ICC_HEAD_SECT1_LENGTH 56
+/* 8 bytes devAttr, 4 bytes intent */
+#define ICC_HEAD_SECT2_START 68
+#define ICC_HEAD_SECT2_LENGTH 16
+/* 16 bytes ID (checksum) */
+#define ICC_HEAD_SECT3_START 100
+#define ICC_HEAD_SECT3_LENGTH 28
+
+#include "dpxcrypt.h"
+static void
+iccp_get_checksum (unsigned char *checksum, const void *profile, long proflen)
+{
+ const unsigned char *p;
+ MD5_CONTEXT md5;
+
+ p = (const unsigned char *) profile;
+
+ MD5_init (&md5);
+ MD5_write(&md5, p + ICC_HEAD_SECT1_START, ICC_HEAD_SECT1_LENGTH);
+ MD5_write(&md5, nullbytes16, 12);
+ MD5_write(&md5, p + ICC_HEAD_SECT2_START, ICC_HEAD_SECT2_LENGTH);
+ MD5_write(&md5, nullbytes16, 16);
+ MD5_write(&md5, p + ICC_HEAD_SECT3_START, ICC_HEAD_SECT3_LENGTH);
+
+ /* body */
+ MD5_write(&md5, p + 128, proflen - 128);
+
+ MD5_final(checksum, &md5);
+}
+
+static void
+print_iccp_header (iccHeader *icch, unsigned char *checksum)
+{
+ int i;
+
+ ASSERT(icch);
+
+#define print_iccSig(s,t) if ((s) == 0) {\
+ MESG("pdf_color>> %s:\t(null)\n", (t)); \
+ } else if (!isprint(((s) >> 24) & 0xff) || \
+ !isprint(((s) >> 16) & 0xff) || \
+ !isprint(((s) >> 8) & 0xff) || \
+ !isprint((s) & 0xff)) { \
+ MESG("pdf_color>> %s:\t(invalid)\n", (t)); \
+ } else { \
+ MESG("pdf_color>> %s:\t%c%c%c%c\n", (t), \
+ ((s) >> 24) & 0xff, ((s) >> 16) & 0xff, \
+ ((s) >> 8) & 0xff, (s) & 0xff); \
+}
+
+ MESG("\n");
+ MESG("pdf_color>> ICC Profile Info\n");
+ MESG("pdf_color>> Profile Size:\t%ld bytes\n", icch->size);
+ print_iccSig(icch->CMMType, "CMM Type");
+ MESG("pdf_color>> Profile Version:\t%d.%01d.%01d\n",
+ (icch->version >> 24) & 0xff,
+ (icch->version >> 20) & 0x0f,
+ (icch->version >> 16) & 0x0f);
+ print_iccSig(icch->devClass, "Device Class");
+ print_iccSig(icch->colorSpace, "Color Space");
+ print_iccSig(icch->PCS, "Connection Space");
+ MESG("pdf_color>> Creation Date:\t");
+ for (i = 0; i < 12; i += 2) {
+ if (i == 0)
+ MESG("%04u",
+ sget_unsigned_pair((unsigned char *) icch->creationDate));
+ else {
+ MESG(":%02u",
+ sget_unsigned_pair((unsigned char *) (&icch->creationDate[i])));
+ }
+ }
+ MESG("\n");
+ print_iccSig(icch->platform, "Primary Platform");
+ MESG("pdf_color>> Profile Flags:\t%02x:%02x:%02x:%02x\n",
+ icch->flags[0], icch->flags[1], icch->flags[2], icch->flags[3]);
+ print_iccSig(icch->devMnfct, "Device Mnfct");
+ print_iccSig(icch->devModel, "Device Model");
+ MESG("pdf_color>> Device Attr:\t");
+ for (i = 0; i < 8; i++) {
+ if (i == 0)
+ MESG("%02x", icch->devAttr[i]);
+ else
+ MESG(":%02x", icch->devAttr[i]);
+ }
+ MESG("\n");
+ MESG("pdf_color>> Rendering Intent:\t");
+ switch (ICC_INTENT_TYPE(icch->intent)) {
+ case ICC_INTENT_SATURATION:
+ MESG("Saturation");
+ break;
+ case ICC_INTENT_PERCEPTUAL:
+ MESG("Perceptual");
+ break;
+ case ICC_INTENT_ABSOLUTE:
+ MESG("Absolute Colorimetric");
+ break;
+ case ICC_INTENT_RELATIVE:
+ MESG("Relative Colorimetric");
+ break;
+ default:
+ MESG("(invalid)");
+ break;
+ }
+ MESG("\n");
+ print_iccSig(icch->creator, "Creator");
+ MESG("pdf_color>> Illuminant (XYZ):\t");
+ MESG("%.3f %.3f %.3f\n",
+ (double) icch->illuminant.X / 0x10000,
+ (double) icch->illuminant.Y / 0x10000,
+ (double) icch->illuminant.Z / 0x10000);
+ MESG("pdf_color>> Checksum:\t");
+ if (!memcmp(icch->ID, nullbytes16, 16)) {
+ MESG("(null)");
+ } else {
+ for (i = 0; i < 16; i++) {
+ if (i == 0)
+ MESG("%02x", icch->ID[i]);
+ else
+ MESG(":%02x", icch->ID[i]);
+ }
+ }
+ MESG("\n");
+ if (checksum) {
+ MESG("pdf_color>> Calculated:\t");
+ for (i = 0; i < 16; i++) {
+ if (i == 0)
+ MESG("%02x", checksum[i]);
+ else
+ MESG(":%02x", checksum[i]);
+ }
+ MESG("\n");
+ }
+
+ return;
+}
+
+
+static int
+iccp_devClass_allowed (int dev_class)
+{
+ int colormode;
+
+ colormode = pdf_dev_get_param(PDF_DEV_PARAM_COLORMODE);
+
+ switch (colormode) {
+#if 0
+ case PDF_DEV_COLORMODE_PDFX1:
+ break;
+ case PDF_DEV_COLORMODE_PDFX3:
+ if (dev_class != str2iccSig("prtr")) {
+ return 0;
+ }
+ break;
+#endif
+ default:
+ if (dev_class != str2iccSig("scnr") &&
+ dev_class != str2iccSig("mntr") &&
+ dev_class != str2iccSig("prtr") &&
+ dev_class != str2iccSig("spac")) {
+ return 0;
+ }
+ break;
+ }
+
+
+ return 1;
+}
+
+int
+iccp_load_profile (const char *ident,
+ const void *profile, long proflen)
+{
+ int cspc_id;
+ pdf_obj *resource;
+ pdf_obj *stream;
+ pdf_obj *stream_dict;
+ iccHeader icch;
+ int colorspace;
+ unsigned char checksum[16];
+ struct iccbased_cdata *cdata;
+
+ iccp_init_iccHeader(&icch);
+ if (iccp_unpack_header(&icch, profile, proflen, 1) < 0) { /* check size */
+ WARN("Invalid ICC profile header in \"%s\"", ident);
+ print_iccp_header(&icch, NULL);
+ return -1;
+ }
+
+ if (!iccp_version_supported((icch.version >> 24) & 0xff,
+ (icch.version >> 16) & 0xff)) {
+ WARN("ICC profile format spec. version %d.%01d.%01d"
+ " not supported in current PDF version setting.",
+ (icch.version >> 24) & 0xff,
+ (icch.version >> 20) & 0x0f,
+ (icch.version >> 16) & 0x0f);
+ WARN("ICC profile not embedded.");
+ print_iccp_header(&icch, NULL);
+ return -1;
+ }
+
+ if (!iccp_devClass_allowed(icch.devClass)) {
+ WARN("Unsupported ICC Profile Device Class:");
+ print_iccp_header(&icch, NULL);
+ return -1;
+ }
+
+ if (icch.colorSpace == str2iccSig("RGB ")) {
+ colorspace = PDF_COLORSPACE_TYPE_RGB;
+ } else if (icch.colorSpace == str2iccSig("GRAY")) {
+ colorspace = PDF_COLORSPACE_TYPE_GRAY;
+ } else if (icch.colorSpace == str2iccSig("CMYK")) {
+ colorspace = PDF_COLORSPACE_TYPE_CMYK;
+ } else {
+ WARN("Unsupported input color space.");
+ print_iccp_header(&icch, NULL);
+ return -1;
+ }
+
+ iccp_get_checksum(checksum, profile, proflen);
+ if (memcmp(icch.ID, nullbytes16, 16) &&
+ memcmp(icch.ID, checksum, 16)) {
+ WARN("Invalid ICC profile: Inconsistent checksum.");
+ print_iccp_header(&icch, checksum);
+ return -1;
+ }
+
+ cdata = NEW(1, struct iccbased_cdata);
+ init_iccbased_cdata(cdata);
+ cdata->colorspace = colorspace;
+ memcpy(cdata->checksum, checksum, 16);
+
+ cspc_id = pdf_colorspace_findresource(ident,
+ PDF_COLORSPACE_TYPE_ICCBASED, cdata);
+ if (cspc_id >= 0) {
+ if (verbose)
+ MESG("(ICCP:[id=%d])", cspc_id);
+ release_iccbased_cdata(cdata);
+ return cspc_id;
+ }
+ if (verbose > 1) {
+ print_iccp_header(&icch, checksum);
+ }
+
+ resource = pdf_new_array();
+
+ stream = pdf_new_stream(STREAM_COMPRESS);
+ pdf_add_array(resource, pdf_new_name("ICCBased"));
+ pdf_add_array(resource, pdf_ref_obj (stream));
+
+ stream_dict = pdf_stream_dict(stream);
+ pdf_add_dict(stream_dict, pdf_new_name("N"),
+ pdf_new_number(get_num_components_iccbased(cdata)));
+
+ pdf_add_stream (stream, profile, proflen);
+ pdf_release_obj(stream);
+
+ cspc_id = pdf_colorspace_defineresource(ident,
+ PDF_COLORSPACE_TYPE_ICCBASED,
+ cdata, resource);
+
+ return cspc_id;
+}
+
+#define WBUF_SIZE 4096
+static unsigned char wbuf[WBUF_SIZE];
+
+static pdf_obj *
+iccp_load_file_stream (unsigned char *checksum, long length, FILE *fp)
+{
+ pdf_obj *stream;
+ MD5_CONTEXT md5;
+ long nb_read;
+
+ rewind(fp);
+
+ if (fread(wbuf, 1, 128, fp) != 128) {
+ return NULL;
+ }
+ length -= 128;
+
+ stream = pdf_new_stream(STREAM_COMPRESS);
+
+ MD5_init (&md5);
+ MD5_write(&md5, wbuf + ICC_HEAD_SECT1_START, ICC_HEAD_SECT1_LENGTH);
+ MD5_write(&md5, nullbytes16, 12);
+ MD5_write(&md5, wbuf + ICC_HEAD_SECT2_START, ICC_HEAD_SECT2_LENGTH);
+ MD5_write(&md5, nullbytes16, 16);
+ MD5_write(&md5, wbuf + ICC_HEAD_SECT3_START, ICC_HEAD_SECT3_LENGTH);
+
+ pdf_add_stream(stream, wbuf, 128);
+
+ /* body */
+ while (length > 0) {
+ nb_read = fread(wbuf, 1, MIN(length, WBUF_SIZE), fp);
+ MD5_write(&md5, wbuf, nb_read);
+ pdf_add_stream(stream, wbuf, nb_read);
+ length -= nb_read;
+ }
+
+ MD5_final(checksum, &md5);
+
+
+ return stream;
+}
+
+int
+pdf_colorspace_load_ICCBased (const char *ident, const char *filename)
+{
+ int cspc_id;
+ FILE *fp;
+ pdf_obj *resource;
+ pdf_obj *stream;
+ pdf_obj *stream_dict;
+ iccHeader icch;
+ int colorspace;
+ long size;
+ unsigned char checksum[16];
+ struct iccbased_cdata *cdata;
+
+
+ fp = DPXFOPEN(filename, DPX_RES_TYPE_ICCPROFILE);
+ if (!fp)
+ return -1;
+
+ size = file_size(fp);
+ if (size < 128) {
+ MFCLOSE(fp);
+ return -1;
+ }
+ if (fread(wbuf, 1, 128, fp) != 128) {
+ DPXFCLOSE(fp);
+ return -1;
+ }
+
+ iccp_init_iccHeader(&icch);
+ if (iccp_unpack_header(&icch, wbuf, 128, 0) < 0) {
+ WARN("Invalid ICC profile header in \"%s\"", ident);
+ print_iccp_header(&icch, NULL);
+ DPXFCLOSE(fp);
+ return -1;
+ }
+ if (icch.size > size) {
+ WARN("File size smaller than recorded in header: %ld %ld",
+ icch.size, size);
+ DPXFCLOSE(fp);
+ return -1;
+ }
+
+ if (!iccp_version_supported((icch.version >> 24) & 0xff,
+ (icch.version >> 16) & 0xff)) {
+ WARN("ICC profile format spec. version %d.%01d.%01d"
+ " not supported in current PDF version setting.",
+ (icch.version >> 24) & 0xff,
+ (icch.version >> 20) & 0x0f,
+ (icch.version >> 16) & 0x0f);
+ WARN("ICC profile not embedded.");
+ print_iccp_header(&icch, NULL);
+ DPXFCLOSE(fp);
+ return -1;
+ }
+
+ if (!iccp_devClass_allowed(icch.devClass)) {
+ WARN("Unsupported ICC Profile Device Class:");
+ print_iccp_header(&icch, NULL);
+ DPXFCLOSE(fp);
+ return -1;
+ }
+
+ if (icch.colorSpace == str2iccSig("RGB ")) {
+ colorspace = PDF_COLORSPACE_TYPE_RGB;
+ } else if (icch.colorSpace == str2iccSig("GRAY")) {
+ colorspace = PDF_COLORSPACE_TYPE_GRAY;
+ } else if (icch.colorSpace == str2iccSig("CMYK")) {
+ colorspace = PDF_COLORSPACE_TYPE_CMYK;
+ } else {
+ WARN("Unsupported input color space.");
+ print_iccp_header(&icch, NULL);
+ DPXFCLOSE(fp);
+ return -1;
+ }
+
+ stream = iccp_load_file_stream(checksum, icch.size, fp);
+ DPXFCLOSE(fp);
+
+ if (!stream) {
+ WARN("Loading ICC Profile failed...: %s", filename);
+ return -1;
+ }
+
+ if (memcmp(icch.ID, nullbytes16, 16) &&
+ memcmp(icch.ID, checksum, 16)) {
+ WARN("Invalid ICC profile: Inconsistent checksum.");
+ print_iccp_header(&icch, NULL);
+ pdf_release_obj(stream);
+ return -1;
+ }
+
+ cdata = NEW(1, struct iccbased_cdata);
+ init_iccbased_cdata(cdata);
+ cdata->colorspace = colorspace;
+ memcpy(cdata->checksum, checksum, 16);
+
+ cspc_id = pdf_colorspace_findresource(ident,
+ PDF_COLORSPACE_TYPE_ICCBASED, cdata);
+ if (cspc_id >= 0) {
+ if (verbose)
+ MESG("(ICCP:[id=%d])", cspc_id);
+ release_iccbased_cdata(cdata);
+ pdf_release_obj(stream);
+ return cspc_id;
+ }
+ if (verbose > 1) {
+ print_iccp_header(&icch, checksum);
+ }
+
+ resource = pdf_new_array();
+
+ pdf_add_array(resource, pdf_new_name("ICCBased"));
+ pdf_add_array(resource, pdf_ref_obj (stream));
+
+ stream_dict = pdf_stream_dict(stream);
+ pdf_add_dict(stream_dict, pdf_new_name("N"),
+ pdf_new_number(get_num_components_iccbased(cdata)));
+ pdf_release_obj(stream);
+
+ cspc_id = pdf_colorspace_defineresource(ident,
+ PDF_COLORSPACE_TYPE_ICCBASED,
+ cdata, resource);
+
+ return cspc_id;
+}
+
+typedef struct {
+ char *ident;
+ int subtype;
+
+ pdf_obj *resource;
+ pdf_obj *reference;
+
+ void *cdata;
+} pdf_colorspace;
+
+static struct {
+ int count;
+ int capacity;
+ pdf_colorspace *colorspaces;
+} cspc_cache = {
+ 0, 0, NULL
+};
+
+int
+pdf_colorspace_findresource (const char *ident,
+ int type, const void *cdata)
+{
+ pdf_colorspace *colorspace;
+ int cspc_id, cmp = -1;
+
+ for (cspc_id = 0;
+ cmp && cspc_id < cspc_cache.count; cspc_id++) {
+ colorspace = &cspc_cache.colorspaces[cspc_id];
+ if (colorspace->subtype != type)
+ continue;
+
+ switch (colorspace->subtype) {
+ case PDF_COLORSPACE_TYPE_ICCBASED:
+ cmp = compare_iccbased(ident, cdata,
+ colorspace->ident, colorspace->cdata);
+ break;
+ }
+ if (!cmp)
+ return cspc_id;
+ }
+
+ return -1; /* not found */
+}
+
+static void
+pdf_init_colorspace_struct (pdf_colorspace *colorspace)
+{
+ ASSERT(colorspace);
+
+ colorspace->ident = NULL;
+ colorspace->subtype = PDF_COLORSPACE_TYPE_INVALID;
+
+ colorspace->resource = NULL;
+ colorspace->reference = NULL;
+ colorspace->cdata = NULL;
+
+ return;
+}
+
+static void
+pdf_clean_colorspace_struct (pdf_colorspace *colorspace)
+{
+ ASSERT(colorspace);
+
+ if (colorspace->ident)
+ RELEASE(colorspace->ident);
+ if (colorspace->resource)
+ pdf_release_obj(colorspace->resource);
+ if (colorspace->reference)
+ pdf_release_obj(colorspace->reference);
+ colorspace->resource = NULL;
+ colorspace->reference = NULL;
+
+ if (colorspace->cdata) {
+ switch (colorspace->subtype) {
+ case PDF_COLORSPACE_TYPE_ICCBASED:
+ release_iccbased_cdata(colorspace->cdata);
+ break;
+ }
+ }
+ colorspace->cdata = NULL;
+ colorspace->subtype = PDF_COLORSPACE_TYPE_INVALID;
+
+ return;
+}
+
+static void
+pdf_flush_colorspace (pdf_colorspace *colorspace)
+{
+ ASSERT(colorspace);
+
+ if (colorspace->resource)
+ pdf_release_obj(colorspace->resource);
+ if (colorspace->reference)
+ pdf_release_obj(colorspace->reference);
+
+ colorspace->resource = NULL;
+ colorspace->reference = NULL;
+}
+
+int
+pdf_colorspace_defineresource (const char *ident,
+ int subtype, void *cdata, pdf_obj *resource)
+{
+ int cspc_id;
+ pdf_colorspace *colorspace;
+
+ if (cspc_cache.count >= cspc_cache.capacity) {
+ cspc_cache.capacity += 16;
+ cspc_cache.colorspaces = RENEW(cspc_cache.colorspaces,
+ cspc_cache.capacity, pdf_colorspace);
+ }
+ cspc_id = cspc_cache.count;
+ colorspace = &cspc_cache.colorspaces[cspc_id];
+
+ pdf_init_colorspace_struct(colorspace);
+ if (ident) {
+ colorspace->ident = NEW(strlen(ident) + 1, char);
+ strcpy(colorspace->ident, ident);
+ }
+ colorspace->subtype = subtype;
+ colorspace->cdata = cdata;
+ colorspace->resource = resource;
+
+ if (verbose) {
+ MESG("(ColorSpace:%s", ident);
+ if (verbose > 1) {
+ switch (subtype) {
+ case PDF_COLORSPACE_TYPE_ICCBASED:
+ MESG("[ICCBased]");
+ break;
+ case PDF_COLORSPACE_TYPE_CALRGB:
+ MESG("[CalRGB]");
+ break;
+ case PDF_COLORSPACE_TYPE_CALGRAY:
+ MESG("[CalGray]");
+ break;
+ }
+ }
+ MESG(")");
+ }
+
+ cspc_cache.count++;
+
+ return cspc_id;
+}
+
+pdf_obj *
+pdf_get_colorspace_reference (int cspc_id)
+{
+ pdf_colorspace *colorspace;
+
+ colorspace = &cspc_cache.colorspaces[cspc_id];
+ if (!colorspace->reference) {
+ colorspace->reference = pdf_ref_obj(colorspace->resource);
+ pdf_release_obj(colorspace->resource); /* .... */
+ colorspace->resource = NULL;
+ }
+
+ return pdf_link_obj(colorspace->reference);
+}
+
+#if 0
+int
+pdf_get_colorspace_num_components (int cspc_id)
+{
+ pdf_colorspace *colorspace;
+ int num_components;
+
+ colorspace = &cspc_cache.colorspaces[cspc_id];
+
+ switch (colorspace->subtype) {
+ case PDF_COLORSPACE_TYPE_ICCBASED:
+ num_components = get_num_components_iccbased(colorspace->cdata);
+ break;
+ case PDF_COLORSPACE_TYPE_DEVICEGRAY:
+ num_components = 1;
+ break;
+ case PDF_COLORSPACE_TYPE_DEVICERGB:
+ num_components = 3;
+ break;
+ case PDF_COLORSPACE_TYPE_DEVICECMYK:
+ num_components = 4;
+ break;
+ case PDF_COLORSPACE_TYPE_CALRGB:
+ num_components = 3;
+ break;
+ case PDF_COLORSPACE_TYPE_CALGRAY:
+ num_components = 1;
+ break;
+ default:
+ num_components = 0;
+ break;
+ }
+
+ return num_components;
+}
+
+int
+pdf_get_colorspace_subtype (int cspc_id)
+{
+ pdf_colorspace *colorspace;
+
+ colorspace = &cspc_cache.colorspaces[cspc_id];
+
+ return colorspace->subtype;
+}
+#endif /* 0 */
+
+void
+pdf_init_colors (void)
+{
+ cspc_cache.count = 0;
+ cspc_cache.capacity = 0;
+ cspc_cache.colorspaces = NULL;
+}
+
+void
+pdf_close_colors (void)
+{
+ int i;
+
+ for (i = 0; i < cspc_cache.count; i++) {
+ pdf_colorspace *colorspace;
+
+ colorspace = &cspc_cache.colorspaces[i];
+ pdf_flush_colorspace(colorspace);
+ pdf_clean_colorspace_struct(colorspace);
+ }
+ RELEASE(cspc_cache.colorspaces);
+ cspc_cache.colorspaces = NULL;
+ cspc_cache.count = cspc_cache.capacity = 0;
+
+}
+
+#define PDF_COLORSPACE_FAMILY_DEVICE 0
+#define PDF_COLORSPACE_FAMILY_CIEBASED 1
+#define PDF_COLORSPACE_FAMILY_SPECIAL 2
diff --git a/Build/source/texk/dvipdf-x/xsrc/pdfcolor.h b/Build/source/texk/dvipdf-x/xsrc/pdfcolor.h
new file mode 100644
index 00000000000..1d5e0f19116
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pdfcolor.h
@@ -0,0 +1,102 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _PDF_COLOR_H_
+#define _PDF_COLOR_H_
+
+#include "pdfobj.h"
+
+#define PDF_COLORSPACE_TYPE_DEVICECMYK -4
+#define PDF_COLORSPACE_TYPE_DEVICERGB -3
+#define PDF_COLORSPACE_TYPE_DEVICEGRAY -1
+#define PDF_COLORSPACE_TYPE_INVALID 0
+#define PDF_COLORSPACE_TYPE_CALGRAY 1
+#define PDF_COLORSPACE_TYPE_CIELAB 2
+#define PDF_COLORSPACE_TYPE_CALRGB 3
+#define PDF_COLORSPACE_TYPE_ICCBASED 4
+
+#define PDF_COLORSPACE_TYPE_CMYK PDF_COLORSPACE_TYPE_DEVICECMYK
+#define PDF_COLORSPACE_TYPE_RGB PDF_COLORSPACE_TYPE_DEVICERGB
+#define PDF_COLORSPACE_TYPE_GRAY PDF_COLORSPACE_TYPE_DEVICEGRAY
+
+
+#define PDF_COLOR_COMPONENT_MAX 4
+
+typedef struct
+{
+ int num_components;
+ double values[PDF_COLOR_COMPONENT_MAX];
+} pdf_color;
+
+extern void pdf_color_set_verbose (void);
+
+extern int pdf_color_rgbcolor (pdf_color *color,
+ double r, double g, double b);
+extern int pdf_color_cmykcolor (pdf_color *color,
+ double c, double m, double y, double k);
+extern int pdf_color_graycolor (pdf_color *color, double g);
+extern void pdf_color_copycolor (pdf_color *color1, const pdf_color *color2);
+
+extern int pdf_color_is_white (pdf_color *color);
+extern int pdf_color_is_valid (pdf_color *color);
+
+/* Not check size */
+extern pdf_obj *iccp_get_rendering_intent (const void *profile, long proflen);
+extern int iccp_check_colorspace (int colortype,
+ const void *profile, long proflen);
+
+/* returns colorspace ID */
+extern int iccp_load_profile (const char *ident,
+ const void *profile, long proflen);
+
+extern void pdf_init_colors (void);
+extern void pdf_close_colors (void);
+
+extern pdf_obj *pdf_get_colorspace_reference (int cspc_id);
+
+#if 0
+extern int pdf_get_colorspace_num_components (int cspc_id);
+extern int pdf_get_colorspace_subtype (int cspc_id);
+#endif
+
+/* Not working */
+extern int pdf_colorspace_load_ICCBased (const char *ident,
+ const char *profile_filename);
+
+/* Color special
+ * See remark in spc_color.c.
+ */
+extern void pdf_color_set_default (const pdf_color *color);
+extern void pdf_color_push (pdf_color *sc, pdf_color *fc);
+extern void pdf_color_pop (void);
+
+/* Color stack
+ */
+extern void pdf_color_clear_stack (void);
+extern void pdf_color_get_current (pdf_color **sc, pdf_color **fc);
+
+/* Reinstall color */
+extern void pdf_dev_preserve_color(void);
+
+#endif /* _PDF_COLOR_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/pdfdev.c b/Build/source/texk/dvipdf-x/xsrc/pdfdev.c
new file mode 100644
index 00000000000..41e6630c26e
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pdfdev.c
@@ -0,0 +1,2000 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <string.h>
+#include <ctype.h>
+#include <math.h>
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+
+#include "mfileio.h"
+#include "numbers.h"
+
+#include "pdfdoc.h"
+#include "pdfobj.h"
+
+#include "pdffont.h"
+#include "fontmap.h"
+#include "cmap.h"
+#include "pdfximage.h"
+
+#include "pdfdraw.h"
+#include "pdfcolor.h"
+
+#include "pdflimits.h"
+
+#include "dvi.h"
+
+#include "pdfdev.h"
+
+static int verbose = 0;
+
+void
+pdf_dev_set_verbose (void)
+{
+ verbose++;
+}
+
+/* Not working yet... */
+double
+pdf_dev_scale (void)
+{
+ return 1.0;
+}
+
+/*
+ * Unit conversion, formatting and others.
+ */
+
+#define TEX_ONE_HUNDRED_BP 6578176
+static struct {
+ double dvi2pts;
+ long min_bp_val; /* Shortest resolvable distance in the output PDF. */
+ int precision; /* Number of decimal digits (in fractional part) kept. */
+} dev_unit = {
+ 0.0,
+ 658,
+ 2
+};
+
+
+double
+dev_unit_dviunit (void)
+{
+ return (1.0/dev_unit.dvi2pts);
+}
+
+#define DEV_PRECISION_MAX 8
+static unsigned long ten_pow[10] = {
+ 1ul, 10ul, 100ul, 1000ul, 10000ul, 100000ul, 1000000ul, 10000000ul, 100000000ul, 1000000000ul
+};
+
+static double ten_pow_inv[10] = {
+ 1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001, 0.00000001, 0.000000001
+};
+
+#define bpt2spt(b) ( (spt_t) round( (b) / dev_unit.dvi2pts ) )
+#define spt2bpt(s) ( (s) * dev_unit.dvi2pts )
+#define dround_at(v,p) (ROUND( (v), ten_pow_inv[(p)] ))
+
+static int
+p_itoa (long value, char *buf)
+{
+ int sign, ndigits;
+ char *p = buf;
+
+ if (value < 0) {
+ *p++ = '-';
+ value = -value;
+ sign = 1;
+ } else {
+ sign = 0;
+ }
+
+ ndigits = 0;
+ /* Generate at least one digit in reverse order */
+ do {
+ p[ndigits++] = (value % 10) + '0';
+ value /= 10;
+ } while (value != 0);
+
+ /* Reverse the digits */
+ {
+ int i;
+
+ for (i = 0; i < ndigits / 2 ; i++) {
+ char tmp = p[i];
+ p[i] = p[ndigits-i-1];
+ p[ndigits-i-1] = tmp;
+ }
+ }
+ p[ndigits] = '\0';
+
+ return (sign ? ndigits + 1 : ndigits);
+}
+
+/* ... */
+static int
+p_dtoa (double value, int prec, char *buf)
+{
+ int n;
+ char *p, *q;
+
+ n = sprintf(buf, "%.*f", prec, value);
+ /* find decimal-point */
+ for (p = buf + n - 1; p > buf && *p != '.'; p--);
+ if (p > buf) {
+ /* chop trailing zeros */
+ for (q = buf + n - 1; q > p && *q == '0'; q--) {
+ *q = '\0'; n--;
+ }
+ /* If a decimal point appears, at least one digit appears
+ * before it.
+ */
+ if (q == p) {
+ *q = '\0'; n--;
+ }
+ }
+ /* -0 --> 0 */
+ if (n == 2 && buf[0] == '-' && buf[1] == '0') {
+ buf[0] = '0'; buf[1] = '\0'; n = 1;
+ }
+
+ return n;
+}
+
+static int
+dev_sprint_bp (char *buf, spt_t value, spt_t *error)
+{
+ double value_in_bp;
+ double error_in_bp;
+ int prec = dev_unit.precision;
+
+ value_in_bp = spt2bpt(value);
+ if (error) {
+ error_in_bp = value_in_bp - dround_at(value_in_bp, prec);
+ *error = bpt2spt(error_in_bp);
+ }
+
+ return p_dtoa(value_in_bp, prec, buf);
+}
+
+/* They are affected by precision (set at device initialization). */
+int
+pdf_sprint_matrix (char *buf, const pdf_tmatrix *M)
+{
+ int len;
+ int prec2 = MIN(dev_unit.precision + 2, DEV_PRECISION_MAX);
+ int prec0 = MAX(dev_unit.precision, 2);
+
+ len = p_dtoa(M->a, prec2, buf);
+ buf[len++] = ' ';
+ len += p_dtoa(M->b, prec2, buf+len);
+ buf[len++] = ' ';
+ len += p_dtoa(M->c, prec2, buf+len);
+ buf[len++] = ' ';
+ len += p_dtoa(M->d, prec2, buf+len);
+ buf[len++] = ' ';
+ len += p_dtoa(M->e, prec0, buf+len);
+ buf[len++] = ' ';
+ len += p_dtoa(M->f, prec0, buf+len);
+ buf[len] = '\0'; /* xxx_sprint_xxx NULL terminates strings. */
+
+ return len;
+}
+
+int
+pdf_sprint_rect (char *buf, const pdf_rect *rect)
+{
+ int len;
+
+ len = p_dtoa(rect->llx, dev_unit.precision, buf);
+ buf[len++] = ' ';
+ len += p_dtoa(rect->lly, dev_unit.precision, buf+len);
+ buf[len++] = ' ';
+ len += p_dtoa(rect->urx, dev_unit.precision, buf+len);
+ buf[len++] = ' ';
+ len += p_dtoa(rect->ury, dev_unit.precision, buf+len);
+ buf[len] = '\0'; /* xxx_sprint_xxx NULL terminates strings. */
+
+ return len;
+}
+
+int
+pdf_sprint_coord (char *buf, const pdf_coord *p)
+{
+ int len;
+
+ len = p_dtoa(p->x, dev_unit.precision, buf);
+ buf[len++] = ' ';
+ len += p_dtoa(p->y, dev_unit.precision, buf+len);
+ buf[len] = '\0'; /* xxx_sprint_xxx NULL terminates strings. */
+
+ return len;
+}
+
+int
+pdf_sprint_length (char *buf, double value)
+{
+ int len;
+
+ len = p_dtoa(value, dev_unit.precision, buf);
+ buf[len] = '\0'; /* xxx_sprint_xxx NULL terminates strings. */
+
+ return len;
+}
+
+
+int
+pdf_sprint_number (char *buf, double value)
+{
+ int len;
+
+ len = p_dtoa(value, DEV_PRECISION_MAX, buf);
+ buf[len] = '\0'; /* xxx_sprint_xxx NULL terminates strings. */
+
+ return len;
+}
+
+
+static struct
+{
+ /* Text composition (direction) mode is ignored (always same
+ * as font's writing mode) if autorotate is unset (value zero).
+ */
+ int autorotate;
+
+ /*
+ * Ignore color migrated to here. This is device's capacity.
+ * colormode 0 for ignore colors
+ */
+ int colormode;
+
+} dev_param = {
+ 1, /* autorotate */
+ 1, /* colormode */
+};
+
+/*
+ * Text handling routines.
+ */
+
+/* Motion state:
+ * GRAPHICS_MODE Initial state (not within BT/ET block nor in string)
+ * TEXT_MODE Text section is started via BT operator but not
+ * in string.
+ * STRING_MODE In string. A string or array of strings are currently
+ * in process. May started '[', '<' or '('.
+ */
+#define GRAPHICS_MODE 1
+#define TEXT_MODE 2
+#define STRING_MODE 3
+
+static int motion_state = GRAPHICS_MODE;
+
+#define FORMAT_BUF_SIZE 4096
+static char format_buffer[FORMAT_BUF_SIZE];
+
+/*
+ * In PDF, vertical text positioning is always applied when current font
+ * is vertical font. While ASCII pTeX manages current writing direction
+ * and font's WMode separately.
+ *
+ * 00/11 WMODE_HH/VV h(v) font, h(v) direction.
+ * 01 WMODE_HV -90 deg. rotated
+ * 10 WMODE_VH +90 deg. rotated
+ *
+ * In MetaPost PostScript file processing (mp_mode = 1), only HH/VV mode
+ * is applied.
+ */
+#define TEXT_WMODE_HH 0
+#define TEXT_WMODE_HV 1
+#define TEXT_WMODE_VH 2
+#define TEXT_WMODE_VV 3
+
+#define ANGLE_CHANGES(m1,m2) ((abs((m1)-(m2)) % 3) == 0 ? 0 : 1)
+#define ROTATE_TEXT(m) ((m) != TEXT_WMODE_HH && (m) != TEXT_WMODE_VV)
+
+static struct {
+
+ /* Current font.
+ * This is index within dev_fonts.
+ */
+ int font_id;
+
+ /* Dvipdfmx does compression of text by doing text positioning
+ * in relative motion and uses string array [(foo) -250 (bar)]
+ * with kerning (negative kern is used for white space as suited
+ * for TeX). This is offset within current string.
+ */
+ spt_t offset;
+
+ /* This is reference point of strings.
+ * It may include error correction induced by rounding.
+ */
+ spt_t ref_x;
+ spt_t ref_y;
+
+ /* Using text raise and leading is highly recommended for
+ * text extraction to work properly. But not implemented yet.
+ * We can't do consice output for \TeX without this.
+ */
+ spt_t raise; /* unused */
+ spt_t leading; /* unused */
+
+ /* This is not always text matrix but rather font matrix.
+ * We do not use horizontal scaling in PDF text state parameter
+ * since they always apply scaling in fixed direction regardless
+ * of writing mode.
+ */
+ struct {
+ double slant;
+ double extend;
+ int rotate; /* TEXT_WMODE_XX */
+ } matrix;
+
+ /* Fake bold parameter:
+ * If bold_param is positive, use text rendering mode
+ * fill-then-stroke with stroking line width specified
+ * by bold_param.
+ */
+ double bold_param;
+
+ /* Text composition (direction) mode. */
+ int dir_mode;
+
+ /* internal */
+
+ /* Flag indicating text matrix to be forcibly reset.
+ * Enabled if synthetic font features (slant, extend, etc)
+ * are used for current font or when text rotation mode
+ * changes.
+ */
+ int force_reset;
+
+ /* This information is duplicated from dev[font_id].format.
+ * Set to 1 if font is composite (Type0) font.
+ */
+ int is_mb;
+} text_state = {
+ -1, /* font */
+ 0, /* offset */
+ 0, 0, /* ref_x, ref_y */
+ 0, 0, /* raise, leading */
+ {0.0, 1.0, 0},
+
+ 0.0, /* Experimental boldness param */
+
+ 0, /* dir_mode */
+
+ /* internal */
+ 0, /* force_reset */
+ 0 /* is_mb */
+};
+
+#define PDF_FONTTYPE_SIMPLE 1
+#define PDF_FONTTYPE_BITMAP 2
+#define PDF_FONTTYPE_COMPOSITE 3
+
+struct dev_font {
+ /* Needs to be big enough to hold name "Fxxx"
+ * where xxx is number of largest font
+ */
+ char short_name[7]; /* Resource name */
+ int used_on_this_page;
+
+ char *tex_name; /* String identifier of this font */
+ spt_t sptsize; /* Point size */
+
+ /* Returned values from font/encoding layer:
+ *
+ * The font_id and enc_id is font and encoding (CMap) identifier
+ * used in pdf_font or encoding/cmap layer.
+ * The PDF object "resource" is an indirect reference object
+ * pointing font resource of this font. The used_chars is somewhat
+ * misleading, this is actually used_glyphs in CIDFont for Type0
+ * and is 65536/8 bytes binary data with each bits representing
+ * whether the glyph is in-use or not. It is 256 char array for
+ * simple font.
+ */
+ int font_id;
+ int enc_id;
+#ifdef XETEX
+ unsigned short *ft_to_gid;
+#endif
+
+ /* if >= 0, index of a dev_font that really has the resource and used_chars */
+ int real_font_index;
+
+ pdf_obj *resource;
+ char *used_chars;
+
+ /* Font format:
+ * simple, composite or bitmap.
+ */
+ int format;
+
+ /* Writing mode:
+ * Non-zero for vertical. Duplicated from CMap.
+ */
+ int wmode;
+
+ /* Syntetic Font:
+ *
+ * We use text matrix for creating extended or slanted font,
+ * but not with font's FontMatrix since TrueType and Type0
+ * font don't support them.
+ */
+ double extend;
+ double slant;
+ double bold; /* Boldness prameter */
+
+ /* Compatibility */
+ int mapc; /* Nasty workaround for Omega */
+
+ /* There are no font metric format supporting four-bytes
+ * charcter code. So we should provide an option to specify
+ * UCS group and plane.
+ */
+ int ucs_group;
+ int ucs_plane;
+
+ int is_unicode;
+};
+static struct dev_font *dev_fonts = NULL;
+
+static int num_dev_fonts = 0;
+static int max_dev_fonts = 0;
+static int num_phys_fonts = 0;
+
+#define CURRENTFONT() ((text_state.font_id < 0) ? NULL : &(dev_fonts[text_state.font_id]))
+#define GET_FONT(n) (&(dev_fonts[(n)]))
+
+
+static void
+dev_set_text_matrix (spt_t xpos, spt_t ypos, double slant, double extend, int rotate)
+{
+ pdf_tmatrix tm;
+ int len = 0;
+
+ /* slant is negated for vertical font so that right-side
+ * is always lower. */
+ switch (rotate) {
+ case TEXT_WMODE_VH:
+ /* Vertical font */
+ tm.a = slant ; tm.b = 1.0;
+ tm.c = -extend; tm.d = 0.0 ;
+ break;
+ case TEXT_WMODE_HV:
+ /* Horizontal font */
+ tm.a = 0.0; tm.b = -extend;
+ tm.c = 1.0; tm.d = -slant ;
+ break;
+ case TEXT_WMODE_HH:
+ /* Horizontal font */
+ tm.a = extend; tm.b = 0.0;
+ tm.c = slant ; tm.d = 1.0;
+ break;
+ case TEXT_WMODE_VV:
+ /* Vertical font */
+ tm.a = 1.0; tm.b = -slant;
+ tm.c = 0.0; tm.d = extend;
+ break;
+ }
+ tm.e = xpos * dev_unit.dvi2pts;
+ tm.f = ypos * dev_unit.dvi2pts;
+
+ format_buffer[len++] = ' ';
+ len += pdf_sprint_matrix(format_buffer+len, &tm);
+ format_buffer[len++] = ' ';
+ format_buffer[len++] = 'T';
+ format_buffer[len++] = 'm';
+
+ pdf_doc_add_page_content(format_buffer, len);
+
+ text_state.ref_x = xpos;
+ text_state.ref_y = ypos;
+ text_state.matrix.slant = slant;
+ text_state.matrix.extend = extend;
+ text_state.matrix.rotate = rotate;
+}
+
+/*
+ * reset_text_state() outputs a BT and does any necessary coordinate
+ * transformations to get ready to ship out text.
+ */
+
+static void
+reset_text_state (void)
+{
+ /*
+ * We need to reset the line matrix to handle slanted fonts.
+ */
+ pdf_doc_add_page_content(" BT", 3);
+ /*
+ * text_state.matrix is identity at top of page.
+ * This sometimes write unnecessary "Tm"s when transition from
+ * GRAPHICS_MODE to TEXT_MODE occurs.
+ */
+ if (text_state.force_reset ||
+ text_state.matrix.slant != 0.0 ||
+ text_state.matrix.extend != 1.0 ||
+ ROTATE_TEXT(text_state.matrix.rotate)) {
+ dev_set_text_matrix(0, 0,
+ text_state.matrix.slant,
+ text_state.matrix.extend,
+ text_state.matrix.rotate);
+ }
+ text_state.ref_x = 0;
+ text_state.ref_y = 0;
+ text_state.offset = 0;
+ text_state.force_reset = 0;
+}
+
+static void
+text_mode (void)
+{
+ switch (motion_state) {
+ case TEXT_MODE:
+ break;
+ case STRING_MODE:
+ pdf_doc_add_page_content(text_state.is_mb ? ">]TJ" : ")]TJ", 4);
+ break;
+ case GRAPHICS_MODE:
+ reset_text_state();
+ break;
+ }
+ motion_state = TEXT_MODE;
+ text_state.offset = 0;
+}
+
+void
+graphics_mode (void)
+{
+ switch (motion_state) {
+ case GRAPHICS_MODE:
+ break;
+ case STRING_MODE:
+ pdf_doc_add_page_content(text_state.is_mb ? ">]TJ" : ")]TJ", 4);
+ /* continue */
+ case TEXT_MODE:
+ pdf_doc_add_page_content(" ET", 3);
+ text_state.force_reset = 0;
+ text_state.font_id = -1;
+ break;
+ }
+ motion_state = GRAPHICS_MODE;
+}
+
+static void
+start_string (spt_t xpos, spt_t ypos, double slant, double extend, int rotate)
+{
+ spt_t delx, dely, error_delx, error_dely;
+ spt_t desired_delx, desired_dely;
+ int len = 0;
+
+ delx = xpos - text_state.ref_x;
+ dely = ypos - text_state.ref_y;
+ /*
+ * Precompensating for line transformation matrix.
+ *
+ * Line transformation matrix L for horizontal font in horizontal
+ * mode and it's inverse I is
+ *
+ * | e 0| | 1/e 0|
+ * L_hh = | | , I_hh = | |
+ * | s 1| |-s/e 1|
+ *
+ * For vertical font in vertical mode,
+ *
+ * | 1 -s| | 1 s/e|
+ * L_vv = | | , I_vv = | |
+ * | 0 e| | 0 1/e|
+ *
+ * For vertical font in horizontal mode,
+ *
+ * | s 1| | 0 1|
+ * L_vh = | | = L_vv x | |
+ * |-e 0| |-1 0|
+ *
+ * | 0 -1|
+ * I_vh = | | x I_vv
+ * | 1 0|
+ *
+ * For horizontal font in vertical mode,
+ *
+ * | 0 -e| | 0 -1|
+ * L_hv = | | = L_hh x | |
+ * | 1 -s| | 1 0|
+ *
+ * | 0 1|
+ * I_hv = | | x I_hh
+ * |-1 0|
+ *
+ */
+ switch (rotate) {
+ case TEXT_WMODE_VH:
+ /* Vertical font in horizontal mode: rot = +90
+ * | 0 -1/e|
+ * d_user = d x I_vh = d x | |
+ * | 1 s/e|
+ */
+ desired_delx = dely;
+ desired_dely = (spt_t) (-(delx - dely*slant)/extend);
+
+ /* error_del is in device space
+ *
+ * | 0 1|
+ * e = e_user x | | = (-e_user_y, e_user_x)
+ * |-1 0|
+ *
+ * We must care about rotation here but not extend/slant...
+ * The extend and slant actually is font matrix.
+ */
+ format_buffer[len++] = ' ';
+ len += dev_sprint_bp(format_buffer+len, desired_delx, &error_dely);
+ format_buffer[len++] = ' ';
+ len += dev_sprint_bp(format_buffer+len, desired_dely, &error_delx);
+ error_delx = -error_delx;
+ break;
+ case TEXT_WMODE_HV:
+ /* Horizontal font in vertical mode: rot = -90
+ *
+ * |-s/e 1|
+ * d_user = d x I_hv = d x | |
+ * |-1/e 0|
+ */
+ desired_delx = (spt_t)(-(dely + delx*slant)/extend);
+ desired_dely = delx;
+
+ /*
+ * e = (e_user_y, -e_user_x)
+ */
+ format_buffer[len++] = ' ';
+ len += dev_sprint_bp(format_buffer+len, desired_delx, &error_dely);
+ format_buffer[len++] = ' ';
+ len += dev_sprint_bp(format_buffer+len, desired_dely, &error_delx);
+ error_dely = -error_dely;
+ break;
+ case TEXT_WMODE_HH:
+ /* Horizontal font in horizontal mode:
+ * | 1/e 0|
+ * d_user = d x I_hh = d x | |
+ * |-s/e 1|
+ */
+ desired_delx = (spt_t)((delx - dely*slant)/extend);
+ desired_dely = dely;
+
+ format_buffer[len++] = ' ';
+ len += dev_sprint_bp(format_buffer+len, desired_delx, &error_delx);
+ format_buffer[len++] = ' ';
+ len += dev_sprint_bp(format_buffer+len, desired_dely, &error_dely);
+ break;
+ case TEXT_WMODE_VV:
+ /* Vertical font in vertical mode:
+ * | 1 s/e|
+ * d_user = d x I_vv = d x | |
+ * | 0 1/e|
+ */
+ desired_delx = delx;
+ desired_dely = (spt_t)((dely + delx*slant)/extend);
+
+ format_buffer[len++] = ' ';
+ len += dev_sprint_bp(format_buffer+len, desired_delx, &error_delx);
+ format_buffer[len++] = ' ';
+ len += dev_sprint_bp(format_buffer+len, desired_dely, &error_dely);
+ break;
+ }
+ pdf_doc_add_page_content(format_buffer, len);
+ /*
+ * dvipdfm wrongly using "TD" in place of "Td".
+ * The TD operator set leading, but we are not using T* etc.
+ */
+ pdf_doc_add_page_content(text_state.is_mb ? " Td[<" : " Td[(", 5);
+
+ /* Error correction */
+ text_state.ref_x = xpos - error_delx;
+ text_state.ref_y = ypos - error_dely;
+
+ text_state.offset = 0;
+}
+
+static void
+string_mode (spt_t xpos, spt_t ypos, double slant, double extend, int rotate)
+{
+ switch (motion_state) {
+ case STRING_MODE:
+ break;
+ case GRAPHICS_MODE:
+ reset_text_state();
+ /* continue */
+ case TEXT_MODE:
+ if (text_state.force_reset) {
+ dev_set_text_matrix(xpos, ypos, slant, extend, rotate);
+ pdf_doc_add_page_content(text_state.is_mb ? "[<" : "[(", 2);
+ text_state.force_reset = 0;
+ } else {
+ start_string(xpos, ypos, slant, extend, rotate);
+ }
+ break;
+ }
+ motion_state = STRING_MODE;
+}
+
+/*
+ * The purpose of the following routine is to force a Tf only
+ * when it's actually necessary. This became a problem when the
+ * VF code was added. The VF spec says to instantiate the
+ * first font contained in the VF file before drawing a virtual
+ * character. However, that font may not be used for
+ * many characters (e.g. small caps fonts). For this reason,
+ * dev_select_font() should not force a "physical" font selection.
+ * This routine prevents a PDF Tf font selection until there's
+ * really a character in that font.
+ */
+
+static int
+dev_set_font (int font_id)
+{
+ struct dev_font *font;
+ struct dev_font *real_font;
+ int text_rotate;
+ double font_scale;
+ int len;
+ int vert_dir, vert_font;
+
+ /* text_mode() must come before text_state.is_mb is changed. */
+ text_mode();
+
+ font = GET_FONT(font_id);
+ ASSERT(font); /* Caller should check font_id. */
+
+ if (font->real_font_index >= 0)
+ real_font = GET_FONT(font->real_font_index);
+ else
+ real_font = font;
+
+ text_state.is_mb = (font->format == PDF_FONTTYPE_COMPOSITE) ? 1 : 0;
+
+ vert_font = font->wmode ? 1 : 0;
+ if (dev_param.autorotate) {
+ vert_dir = text_state.dir_mode ? 1 : 0;
+ } else {
+ vert_dir = vert_font;
+ }
+ text_rotate = (vert_font << 1)|vert_dir;
+
+ if (font->slant != text_state.matrix.slant ||
+ font->extend != text_state.matrix.extend ||
+ ANGLE_CHANGES(text_rotate, text_state.matrix.rotate)) {
+ text_state.force_reset = 1;
+ }
+ text_state.matrix.slant = font->slant;
+ text_state.matrix.extend = font->extend;
+ text_state.matrix.rotate = text_rotate;
+
+ if (!real_font->resource) {
+ real_font->resource = pdf_get_font_reference(real_font->font_id);
+ real_font->used_chars = pdf_get_font_usedchars(real_font->font_id);
+ }
+
+ if (!real_font->used_on_this_page) {
+ pdf_doc_add_page_resource("Font",
+ real_font->short_name,
+ pdf_link_obj(real_font->resource));
+ real_font->used_on_this_page = 1;
+ }
+
+ font_scale = (double) font->sptsize * dev_unit.dvi2pts;
+ len = sprintf(format_buffer, " /%s", real_font->short_name); /* space not necessary. */
+ format_buffer[len++] = ' ';
+ len += p_dtoa(font_scale, MIN(dev_unit.precision+1, DEV_PRECISION_MAX), format_buffer+len);
+ format_buffer[len++] = ' ';
+ format_buffer[len++] = 'T';
+ format_buffer[len++] = 'f';
+ pdf_doc_add_page_content(format_buffer, len);
+
+ if (font->bold > 0.0 || font->bold != text_state.bold_param) {
+ if (font->bold <= 0.0)
+ len = sprintf(format_buffer, " 0 Tr");
+ else
+ len = sprintf(format_buffer, " 2 Tr %.6f w", font->bold); /* _FIXME_ */
+ pdf_doc_add_page_content(format_buffer, len);
+ }
+ text_state.bold_param = font->bold;
+
+ text_state.font_id = font_id;
+
+ return 0;
+}
+
+
+/* Access text state parameters.
+ */
+#if 0
+int
+pdf_dev_currentfont (void)
+{
+ return text_state.font_id;
+}
+
+double
+pdf_dev_get_font_ptsize (int font_id)
+{
+ struct dev_font *font;
+
+ font = GET_FONT(font_id);
+ if (font) {
+ return font->sptsize * dev_unit.dvi2pts;
+ }
+
+ return 1.0;
+}
+#endif /* 0 */
+
+int
+pdf_dev_get_font_wmode (int font_id)
+{
+ struct dev_font *font;
+
+ font = GET_FONT(font_id);
+ if (font) {
+ return font->wmode;
+ }
+
+ return 0;
+}
+
+static unsigned char sbuf0[FORMAT_BUF_SIZE];
+static unsigned char sbuf1[FORMAT_BUF_SIZE];
+
+static int
+handle_multibyte_string (struct dev_font *font,
+ const unsigned char **str_ptr, int *str_len, int ctype)
+{
+ const unsigned char *p;
+ int i, length;
+
+ p = *str_ptr;
+ length = *str_len;
+
+#ifdef XETEX
+ if (ctype == -1) { /* freetype glyph indexes */
+ if (font->ft_to_gid) {
+ /* convert freetype glyph indexes to physical GID */
+ const unsigned char *inbuf = p;
+ unsigned char *outbuf = sbuf0;
+ for (i = 0; i < length; i += 2) {
+ unsigned int gid;
+ gid = *inbuf++ << 8;
+ gid += *inbuf++;
+ gid = font->ft_to_gid[gid];
+ *outbuf++ = gid >> 8;
+ *outbuf++ = gid & 0xff;
+ }
+ p = sbuf0;
+ length = outbuf - sbuf0;
+ }
+ }
+ else
+#endif
+ /* _FIXME_ */
+ if (font->is_unicode) { /* UCS-4 */
+ if (ctype == 1) {
+ if (length * 4 >= FORMAT_BUF_SIZE) {
+ WARN("Too long string...");
+ return -1;
+ }
+ for (i = 0; i < length; i++) {
+ sbuf1[i*4 ] = font->ucs_group;
+ sbuf1[i*4+1] = font->ucs_plane;
+ sbuf1[i*4+2] = '\0';
+ sbuf1[i*4+3] = p[i];
+ }
+ length *= 4;
+ } else if (ctype == 2) {
+ int len = 0;
+
+ if (length * 2 >= FORMAT_BUF_SIZE) {
+ WARN("Too long string...");
+ return -1;
+ }
+ for (i = 0; i < length; i += 2, len += 4) {
+ sbuf1[len ] = font->ucs_group;
+ if ((p[i] & 0xf8) == 0xd8) {
+ int c;
+ /* Check for valid surrogate pair. */
+ if ((p[i] & 0xfc) != 0xd8 || i + 2 >= length || (p[i+2] & 0xfc) != 0xdc) {
+ WARN("Invalid surrogate p[%d]=%02X...", i, p[i]);
+ return -1;
+ }
+ c = (((p[i] & 0x03) << 10) | (p[i+1] << 2) | (p[i+2] & 0x03)) + 0x100;
+ sbuf1[len+1] = (c >> 8) & 0xff;
+ sbuf1[len+2] = c & 0xff;
+ i += 2;
+ } else {
+ sbuf1[len+1] = font->ucs_plane;
+ sbuf1[len+2] = p[i];
+ }
+ sbuf1[len+3] = p[i+1];
+ }
+ length = len;
+ }
+ p = sbuf1;
+ } else if (ctype == 1 && font->mapc >= 0) {
+ /* Omega workaround...
+ * Translate single-byte chars to double byte code space.
+ */
+ if (length * 2 >= FORMAT_BUF_SIZE) {
+ WARN("Too long string...");
+ return -1;
+ }
+ for (i = 0; i < length; i++) {
+ sbuf1[i*2 ] = (font->mapc & 0xff);
+ sbuf1[i*2+1] = p[i];
+ }
+ length *= 2;
+ p = sbuf1;
+ }
+
+ /*
+ * Font is double-byte font. Output is assumed to be 16-bit fixed length
+ * encoding.
+ * TODO: A character decomposed to multiple characters.
+ */
+ if (ctype != -1 && font->enc_id >= 0) {
+ const unsigned char *inbuf;
+ unsigned char *outbuf;
+ long inbytesleft, outbytesleft;
+ CMap *cmap;
+
+ cmap = CMap_cache_get(font->enc_id);
+ inbuf = p;
+ outbuf = sbuf0;
+ inbytesleft = length;
+ outbytesleft = FORMAT_BUF_SIZE;
+
+ CMap_decode(cmap,
+ &inbuf, &inbytesleft, &outbuf, &outbytesleft);
+ if (inbytesleft != 0) {
+ WARN("CMap conversion failed. (%d bytes remains)", inbytesleft);
+ return -1;
+ }
+ length = FORMAT_BUF_SIZE - outbytesleft;
+ p = sbuf0;
+ }
+
+ *str_ptr = p;
+ *str_len = length;
+ return 0;
+}
+
+
+static pdf_coord *dev_coords = NULL;
+static int num_dev_coords = 0;
+static int max_dev_coords = 0;
+
+void pdf_dev_get_coord(double *xpos, double *ypos)
+{
+ if (num_dev_coords > 0) {
+ *xpos = dev_coords[num_dev_coords-1].x;
+ *ypos = dev_coords[num_dev_coords-1].y;
+ } else {
+ *xpos = *ypos = 0.0;
+ }
+}
+
+void pdf_dev_push_coord(double xpos, double ypos)
+{
+ if (num_dev_coords >= max_dev_coords) {
+ max_dev_coords += 4;
+ dev_coords = RENEW(dev_coords, max_dev_coords, pdf_coord);
+ }
+ dev_coords[num_dev_coords].x = xpos;
+ dev_coords[num_dev_coords].y = ypos;
+ num_dev_coords++;
+}
+
+void pdf_dev_pop_coord(void)
+{
+ if (num_dev_coords > 0) num_dev_coords--;
+}
+
+/*
+ * ctype:
+#ifdef XETEX
+ * -1 input string contains 2-byte Freetype glyph index values
+#endif
+ * 0 byte-width of char can be variable and input string
+ * is properly encoded.
+ * n Single character cosumes n bytes in input string.
+ *
+ * _FIXME_
+ * -->
+ * selectfont(font_name, point_size) and show_string(pos, string)
+ */
+void
+pdf_dev_set_string (spt_t xpos, spt_t ypos,
+ const void *instr_ptr, int instr_len,
+ spt_t width,
+ int font_id, int ctype)
+{
+ struct dev_font *font;
+ struct dev_font *real_font;
+ const unsigned char *str_ptr; /* Pointer to the reencoded string. */
+ int length, i, len = 0;
+ spt_t kern, delh, delv;
+ spt_t text_xorigin;
+ spt_t text_yorigin;
+
+ if (font_id < 0 || font_id >= num_dev_fonts) {
+ ERROR("Invalid font: %d (%d)", font_id, num_dev_fonts);
+ return;
+ }
+ if (font_id != text_state.font_id) {
+ dev_set_font(font_id);
+ }
+
+ font = CURRENTFONT();
+ if (!font) {
+ ERROR("Currentfont not set.");
+ return;
+ }
+
+ if (font->real_font_index >= 0)
+ real_font = GET_FONT(font->real_font_index);
+ else
+ real_font = font;
+
+ text_xorigin = text_state.ref_x;
+ text_yorigin = text_state.ref_y;
+
+ str_ptr = instr_ptr;
+ length = instr_len;
+
+ if (font->format == PDF_FONTTYPE_COMPOSITE) {
+ if (handle_multibyte_string(font, &str_ptr, &length, ctype) < 0) {
+ ERROR("Error in converting input string...");
+ return;
+ }
+ if (real_font->used_chars != NULL) {
+ for (i = 0; i < length; i += 2)
+ add_to_used_chars2(real_font->used_chars,
+ (unsigned short) (str_ptr[i] << 8)|str_ptr[i+1]);
+ }
+ } else {
+ if (real_font->used_chars != NULL) {
+ for (i = 0; i < length; i++)
+ real_font->used_chars[str_ptr[i]] = 1;
+ }
+ }
+
+ if (num_dev_coords > 0) {
+ xpos -= bpt2spt(dev_coords[num_dev_coords-1].x);
+ ypos -= bpt2spt(dev_coords[num_dev_coords-1].y);
+ }
+
+ /*
+ * Kern is in units of character units, i.e., 1000 = 1 em.
+ *
+ * Positive kern means kerning (reduce excess white space).
+ *
+ * The following formula is of the form a*x/b where a, x, and b are signed long
+ * integers. Since in integer arithmetic (a*x) could overflow and a*(x/b) would
+ * not be accurate, we use floating point arithmetic rather than trying to do
+ * this all with integer arithmetic.
+ *
+ * 1000.0 / (font->extend * font->sptsize) is caluculated each times...
+ * Is accuracy really a matter? Character widths are always rounded to integer
+ * (in 1000 units per em) but dvipdfmx does not take into account of this...
+ */
+
+ if (text_state.dir_mode) {
+ /* Top-to-bottom */
+ delh = ypos - text_yorigin + text_state.offset;
+ delv = xpos - text_xorigin;
+ } else {
+ /* Left-to-right */
+ delh = text_xorigin + text_state.offset - xpos;
+ delv = ypos - text_yorigin;
+ }
+
+ /* White-space more than 3em is not considered as a part of single text.
+ * So we will break string mode in that case.
+ * Dvipdfmx spend most of time processing strings with kern = 0 (but far
+ * more times in font handling).
+ * You may want to use pre-calculated value for WORD_SPACE_MAX.
+ * More text compression may be possible by replacing kern with space char
+ * when -kern is equal to space char width.
+ */
+#define WORD_SPACE_MAX(f) (spt_t) (3.0 * (f)->extend * (f)->sptsize)
+
+ if (text_state.force_reset ||
+ labs(delv) > dev_unit.min_bp_val ||
+ labs(delh) > WORD_SPACE_MAX(font)) {
+ text_mode();
+ kern = 0;
+ } else {
+ kern = (spt_t) (1000.0 / font->extend * delh / font->sptsize);
+ }
+
+ /* Inaccucary introduced by rounding of character width appears within
+ * single text block. There are point_size/1000 rounding error per character.
+ * If you really care about accuracy, you should compensate this here too.
+ */
+ if (motion_state != STRING_MODE)
+ string_mode(xpos, ypos,
+ font->slant, font->extend, text_state.matrix.rotate);
+ else if (kern != 0) {
+ /*
+ * Same issues as earlier. Use floating point for simplicity.
+ * This routine needs to be fast, so we don't call sprintf() or strcpy().
+ */
+ text_state.offset -=
+ (spt_t) (kern * font->extend * (font->sptsize / 1000.0));
+ format_buffer[len++] = text_state.is_mb ? '>' : ')';
+ if (font->wmode)
+ len += p_itoa(-kern, format_buffer + len);
+ else {
+ len += p_itoa( kern, format_buffer + len);
+ }
+ format_buffer[len++] = text_state.is_mb ? '<' : '(';
+ pdf_doc_add_page_content(format_buffer, len);
+ len = 0;
+ }
+
+ if (text_state.is_mb) {
+ if (FORMAT_BUF_SIZE - len < 2 * length)
+ ERROR("Buffer overflow...");
+ for (i = 0; i < length; i++) {
+ int first, second;
+
+ first = (str_ptr[i] >> 4) & 0x0f;
+ second = str_ptr[i] & 0x0f;
+ format_buffer[len++] = ((first >= 10) ? first + 'W' : first + '0');
+ format_buffer[len++] = ((second >= 10) ? second + 'W' : second + '0');
+ }
+ } else {
+ len += pdfobj_escape_str(format_buffer + len,
+ FORMAT_BUF_SIZE - len, str_ptr, length);
+ }
+ /* I think if you really care about speed, you should avoid memcopy here. */
+ pdf_doc_add_page_content(format_buffer, len);
+
+ text_state.offset += width;
+}
+
+void
+pdf_init_device (double dvi2pts, int precision, int black_and_white)
+{
+ if (precision < 0 ||
+ precision > DEV_PRECISION_MAX)
+ WARN("Number of decimal digits out of range [0-%d].",
+ DEV_PRECISION_MAX);
+
+ if (precision < 0) {
+ dev_unit.precision = 0;
+ } else if (precision > DEV_PRECISION_MAX) {
+ dev_unit.precision = DEV_PRECISION_MAX;
+ } else {
+ dev_unit.precision = precision;
+ }
+ dev_unit.dvi2pts = dvi2pts;
+ dev_unit.min_bp_val = (long) ROUND(1.0/(ten_pow[dev_unit.precision]*dvi2pts), 1);
+ if (dev_unit.min_bp_val < 0)
+ dev_unit.min_bp_val = -dev_unit.min_bp_val;
+
+ dev_param.colormode = (black_and_white ? 0 : 1);
+
+ graphics_mode();
+ pdf_color_clear_stack();
+ pdf_dev_init_gstates();
+
+ num_dev_fonts = max_dev_fonts = 0;
+ dev_fonts = NULL;
+ num_dev_coords = max_dev_coords = 0;
+ dev_coords = NULL;
+}
+
+void
+pdf_close_device (void)
+{
+ if (dev_fonts) {
+ int i;
+
+ for (i = 0; i < num_dev_fonts; i++) {
+ if (dev_fonts[i].tex_name)
+ RELEASE(dev_fonts[i].tex_name);
+ if (dev_fonts[i].resource)
+ pdf_release_obj(dev_fonts[i].resource);
+ dev_fonts[i].tex_name = NULL;
+ dev_fonts[i].resource = NULL;
+ }
+ RELEASE(dev_fonts);
+ }
+ if (dev_coords) RELEASE(dev_coords);
+ pdf_dev_clear_gstates();
+}
+
+/*
+ * BOP, EOP, and FONT section.
+ * BOP and EOP manipulate some of the same data structures
+ * as the font stuff.
+ */
+void
+pdf_dev_reset_fonts (void)
+{
+ int i;
+
+ for (i = 0; i < num_dev_fonts; i++) {
+ dev_fonts[i].used_on_this_page = 0;
+ }
+
+ text_state.font_id = -1;
+
+ text_state.matrix.slant = 0.0;
+ text_state.matrix.extend = 1.0;
+ text_state.matrix.rotate = TEXT_WMODE_HH;
+
+ text_state.bold_param = 0.0;
+
+ text_state.is_mb = 0;
+}
+
+void
+pdf_dev_reset_color(void)
+{
+ pdf_color *sc, *fc;
+
+ if (pdf_dev_get_param(PDF_DEV_PARAM_COLORMODE)) {
+ pdf_color_get_current(&sc, &fc);
+ pdf_dev_set_strokingcolor(sc);
+ pdf_dev_set_nonstrokingcolor(fc);
+ }
+ return;
+}
+
+static int
+color_to_string (pdf_color *color, char *buffer)
+{
+ int i, len = 0;
+
+ for (i = 0; i < color->num_components; i++) {
+ len += sprintf(format_buffer+len, " %g", ROUND(color->values[i], 0.001));
+ }
+ return len;
+}
+
+void
+pdf_dev_set_color (pdf_color *color)
+{
+ int len;
+
+ if (!pdf_dev_get_param(PDF_DEV_PARAM_COLORMODE)) {
+ WARN("Ignore color option was set. Just ignore.");
+ return;
+ } else if (!(color && pdf_color_is_valid(color))) {
+ WARN("No valid color is specified. Just ignore.");
+ return;
+ }
+
+ graphics_mode();
+ len = color_to_string(color, format_buffer);
+ format_buffer[len++] = ' ';
+ switch (color->num_components) {
+ case 3:
+ format_buffer[len++] = 'R';
+ format_buffer[len++] = 'G';
+ break;
+ case 4:
+ format_buffer[len++] = 'K';
+ break;
+ case 1:
+ format_buffer[len++] = 'G';
+ break;
+ default: /* already verified the given color */
+ break;
+ }
+ strncpy(format_buffer+len, format_buffer, len);
+ len = len << 1;
+ switch (color->num_components) {
+ case 3:
+ format_buffer[len-2] = 'r';
+ format_buffer[len-1] = 'g';
+ break;
+ case 4:
+ format_buffer[len-1] = 'k';
+ break;
+ case 1:
+ format_buffer[len-1] = 'g';
+ break;
+ default: /* already verified the given color */
+ break;
+ }
+ pdf_doc_add_page_content(format_buffer, len);
+ return;
+}
+
+void
+pdf_dev_set_strokingcolor (pdf_color *color)
+{
+ int len;
+
+ if (!pdf_dev_get_param(PDF_DEV_PARAM_COLORMODE)) {
+ WARN("Ignore color option was set. Just ignore.");
+ return;
+ } else if (!(color && pdf_color_is_valid(color))) {
+ WARN("No valid color is specified. Just ignore.");
+ return;
+ }
+
+ graphics_mode();
+ len = color_to_string(color, format_buffer);
+ format_buffer[len++] = ' ';
+ switch (color->num_components) {
+ case 3:
+ format_buffer[len++] = 'R';
+ format_buffer[len++] = 'G';
+ break;
+ case 4:
+ format_buffer[len++] = 'K';
+ break;
+ case 1:
+ format_buffer[len++] = 'G';
+ break;
+ default: /* already verified the given color */
+ break;
+ }
+ pdf_doc_add_page_content(format_buffer, len);
+ return;
+}
+
+void
+pdf_dev_set_nonstrokingcolor (pdf_color *color)
+{
+ int len;
+
+ if (!pdf_dev_get_param(PDF_DEV_PARAM_COLORMODE)) {
+ WARN("Ignore color option was set. Just ignore.");
+ return;
+ } else if (!(color && pdf_color_is_valid(color))) {
+ WARN("No valid color is specified. Just ignore.");
+ return;
+ }
+
+ graphics_mode();
+ len = color_to_string(color, format_buffer);
+ format_buffer[len++] = ' ';
+ switch (color->num_components) {
+ case 3:
+ format_buffer[len++] = 'r';
+ format_buffer[len++] = 'g';
+ break;
+ case 4:
+ format_buffer[len++] = 'k';
+ break;
+ case 1:
+ format_buffer[len++] = 'g';
+ break;
+ default: /* already verified the given color */
+ break;
+ }
+ pdf_doc_add_page_content(format_buffer, len);
+ return;
+}
+
+/* Not working */
+void
+pdf_dev_set_origin (double phys_x, double phys_y)
+{
+ pdf_tmatrix M0, M1;
+
+ pdf_dev_currentmatrix(&M0);
+ pdf_dev_currentmatrix(&M1);
+ pdf_invertmatrix(&M1);
+ M0.e = phys_x; M0.f = phys_y;
+ pdf_concatmatrix(&M1, &M0);
+
+ pdf_dev_concat(&M1);
+}
+
+void
+pdf_dev_bop (const pdf_tmatrix *M)
+{
+ graphics_mode();
+
+ text_state.force_reset = 0;
+
+ pdf_dev_gsave();
+ pdf_dev_concat(M);
+
+ pdf_dev_reset_fonts();
+ pdf_dev_reset_color();
+}
+
+void
+pdf_dev_eop (void)
+{
+ int depth;
+
+ graphics_mode();
+
+ depth = pdf_dev_current_depth();
+ if (depth != 1) {
+ WARN("Unbalenced q/Q nesting...: %d", depth);
+ pdf_dev_grestore_to(0);
+ } else {
+ pdf_dev_grestore();
+ }
+}
+
+static void
+print_fontmap (const char *font_name, fontmap_rec *mrec)
+{
+ if (!mrec)
+ return;
+
+ MESG("\n");
+
+ MESG("fontmap: %s -> %s", font_name, mrec->font_name);
+ if (mrec->enc_name)
+ MESG("(%s)", mrec->enc_name);
+ if (mrec->opt.extend != 1.0)
+ MESG("[extend:%g]", mrec->opt.extend);
+ if (mrec->opt.slant != 0.0)
+ MESG("[slant:%g]", mrec->opt.slant);
+ if (mrec->opt.bold != 0.0)
+ MESG("[bold:%g]", mrec->opt.bold);
+ if (mrec->opt.flags & FONTMAP_OPT_NOEMBED)
+ MESG("[noemb]");
+ if (mrec->opt.mapc >= 0)
+ MESG("[map:<%02x>]", mrec->opt.mapc);
+ if (mrec->opt.charcoll)
+ MESG("[csi:%s]", mrec->opt.charcoll);
+ if (mrec->opt.index)
+ MESG("[index:%d]", mrec->opt.index);
+
+ switch (mrec->opt.style) {
+ case FONTMAP_STYLE_BOLD:
+ MESG("[style:bold]");
+ break;
+ case FONTMAP_STYLE_ITALIC:
+ MESG("[style:italic]");
+ break;
+ case FONTMAP_STYLE_BOLDITALIC:
+ MESG("[style:bolditalic]");
+ break;
+ }
+ MESG("\n");
+
+}
+
+/* _FIXME_
+ * Font is identified with font_name and point_size as in DVI here.
+ * However, except for PDF_FONTTYPE_BITMAP, we can share the
+ * short_name, resource and used_chars between multiple instances
+ * of the same font at different sizes.
+ */
+int
+pdf_dev_locate_font (const char *font_name, spt_t ptsize)
+{
+ int i;
+ fontmap_rec *mrec;
+ struct dev_font *font;
+
+ if (!font_name)
+ return -1;
+
+ if (ptsize == 0) {
+ ERROR("pdf_dev_locate_font() called with the zero ptsize.");
+ return -1;
+ }
+
+ for (i = 0; i < num_dev_fonts; i++) {
+ if (strcmp(font_name, dev_fonts[i].tex_name) == 0) {
+ if (ptsize == dev_fonts[i].sptsize)
+ return i; /* found a dev_font that matches the request */
+ if (dev_fonts[i].format != PDF_FONTTYPE_BITMAP)
+ break; /* new dev_font will share pdf resource with /i/ */
+ }
+ }
+
+ /*
+ * Make sure we have room for a new one, even though we may not
+ * actually create one.
+ */
+ if (num_dev_fonts >= max_dev_fonts) {
+ max_dev_fonts += 16;
+ dev_fonts = RENEW(dev_fonts, max_dev_fonts, struct dev_font);
+ }
+
+ font = &dev_fonts[num_dev_fonts];
+
+ /* New font */
+ mrec = pdf_lookup_fontmap_record(font_name);
+
+ if (verbose > 1)
+ print_fontmap(font_name, mrec);
+
+ font->font_id = pdf_font_findresource(font_name, ptsize * dev_unit.dvi2pts, mrec);
+ if (font->font_id < 0)
+ return -1;
+
+ /* We found device font here. */
+ if (i < num_dev_fonts) {
+ font->real_font_index = i;
+ strcpy(font->short_name, dev_fonts[i].short_name);
+ }
+ else {
+ font->real_font_index = -1;
+ font->short_name[0] = 'F';
+ p_itoa(num_phys_fonts + 1, &font->short_name[1]); /* NULL terminated here */
+ num_phys_fonts++;
+ }
+
+ font->used_on_this_page = 0;
+
+ font->tex_name = NEW(strlen(font_name) + 1, char);
+ strcpy(font->tex_name, font_name);
+ font->sptsize = ptsize;
+
+ switch (pdf_get_font_subtype(font->font_id)) {
+ case PDF_FONT_FONTTYPE_TYPE3:
+ font->format = PDF_FONTTYPE_BITMAP;
+ break;
+ case PDF_FONT_FONTTYPE_TYPE0:
+ font->format = PDF_FONTTYPE_COMPOSITE;
+ break;
+ default:
+ font->format = PDF_FONTTYPE_SIMPLE;
+ break;
+ }
+
+ font->wmode = pdf_get_font_wmode (font->font_id);
+ font->enc_id = pdf_get_font_encoding(font->font_id);
+#ifdef XETEX
+ font->ft_to_gid = pdf_get_font_ft_to_gid(font->font_id);
+#endif
+
+ font->resource = NULL; /* Don't ref obj until font is actually used. */
+ font->used_chars = NULL;
+
+ font->extend = 1.0;
+ font->slant = 0.0;
+ font->bold = 0.0;
+ font->mapc = -1;
+ font->is_unicode = 0;
+ font->ucs_group = 0;
+ font->ucs_plane = 0;
+
+ if (mrec) {
+ font->extend = mrec->opt.extend;
+ font->slant = mrec->opt.slant;
+ font->bold = mrec->opt.bold;
+ if (mrec->opt.mapc >= 0)
+ font->mapc = (mrec->opt.mapc >> 8) & 0xff;
+ else {
+ font->mapc = -1;
+ }
+ if (mrec->enc_name &&
+ !strcmp(mrec->enc_name, "unicode")) {
+ font->is_unicode = 1;
+ if (mrec->opt.mapc >= 0) {
+ font->ucs_group = (mrec->opt.mapc >> 24) & 0xff;
+ font->ucs_plane = (mrec->opt.mapc >> 16) & 0xff;
+ } else {
+ font->ucs_group = 0;
+ font->ucs_plane = 0;
+ }
+ } else {
+ font->is_unicode = 0;
+ }
+ }
+
+ return num_dev_fonts++;
+}
+
+
+/* This does not remember current stroking width. */
+static int
+dev_sprint_line (char *buf, spt_t width,
+ spt_t p0_x, spt_t p0_y, spt_t p1_x, spt_t p1_y)
+{
+ int len = 0;
+ double w;
+
+ w = width * dev_unit.dvi2pts;
+
+ len += p_dtoa(w, MIN(dev_unit.precision+1, DEV_PRECISION_MAX), buf+len);
+ buf[len++] = ' ';
+ buf[len++] = 'w';
+ buf[len++] = ' ';
+ len += dev_sprint_bp(buf+len, p0_x, NULL);
+ buf[len++] = ' ';
+ len += dev_sprint_bp(buf+len, p0_y, NULL);
+ buf[len++] = ' ';
+ buf[len++] = 'm';
+ buf[len++] = ' ';
+ len += dev_sprint_bp(buf+len, p1_x, NULL);
+ buf[len++] = ' ';
+ len += dev_sprint_bp(buf+len, p1_y, NULL);
+ buf[len++] = ' ';
+ buf[len++] = 'l';
+ buf[len++] = ' ';
+ buf[len++] = 'S';
+
+ return len;
+}
+
+/* Not optimized. */
+#define PDF_LINE_THICKNESS_MAX 5.0
+void
+pdf_dev_set_rule (spt_t xpos, spt_t ypos, spt_t width, spt_t height)
+{
+ int len = 0;
+ double width_in_bp;
+
+ if (num_dev_coords > 0) {
+ xpos -= bpt2spt(dev_coords[num_dev_coords-1].x);
+ ypos -= bpt2spt(dev_coords[num_dev_coords-1].y);
+ }
+
+ graphics_mode();
+
+ format_buffer[len++] = ' ';
+ format_buffer[len++] = 'q';
+ format_buffer[len++] = ' ';
+ /* Don't use too thick line. */
+ width_in_bp = ((width < height) ? width : height) * dev_unit.dvi2pts;
+ if (width_in_bp < 0.0 || /* Shouldn't happen */
+ width_in_bp > PDF_LINE_THICKNESS_MAX) {
+ pdf_rect rect;
+
+ rect.llx = dev_unit.dvi2pts * xpos;
+ rect.lly = dev_unit.dvi2pts * ypos;
+ rect.urx = dev_unit.dvi2pts * width;
+ rect.ury = dev_unit.dvi2pts * height;
+ len += pdf_sprint_rect(format_buffer+len, &rect);
+ format_buffer[len++] = ' ';
+ format_buffer[len++] = 'r';
+ format_buffer[len++] = 'e';
+ format_buffer[len++] = ' ';
+ format_buffer[len++] = 'f';
+ } else {
+ if (width > height) {
+ /* NOTE:
+ * A line width of 0 denotes the thinnest line that can be rendered at
+ * device resolution. See, PDF Reference Manual 4th ed., sec. 4.3.2,
+ * "Details of Graphics State Parameters", p. 185.
+ */
+ if (height < dev_unit.min_bp_val) {
+ WARN("Too thin line: height=%ld (%g bp)", height, width_in_bp);
+ WARN("Please consider using \"-d\" option.");
+ }
+ len += dev_sprint_line(format_buffer+len,
+ height,
+ xpos,
+ ypos + height/2,
+ xpos + width,
+ ypos + height/2);
+ } else {
+ if (width < dev_unit.min_bp_val) {
+ WARN("Too thin line: width=%ld (%g bp)", width, width_in_bp);
+ WARN("Please consider using \"-d\" option.");
+ }
+ len += dev_sprint_line(format_buffer+len,
+ width,
+ xpos + width/2,
+ ypos,
+ xpos + width/2,
+ ypos + height);
+ }
+ }
+ format_buffer[len++] = ' ';
+ format_buffer[len++] = 'Q';
+ pdf_doc_add_page_content(format_buffer, len);
+}
+
+/* Rectangle in device space coordinate. */
+void
+pdf_dev_set_rect (pdf_rect *rect,
+ spt_t x_user, spt_t y_user,
+ spt_t width, spt_t height, spt_t depth)
+{
+ double dev_x, dev_y;
+ pdf_coord p0, p1, p2, p3;
+ double min_x, min_y, max_x, max_y;
+
+ dev_x = x_user * dev_unit.dvi2pts;
+ dev_y = y_user * dev_unit.dvi2pts;
+ if (text_state.dir_mode) {
+ p0.x = dev_x - dev_unit.dvi2pts * depth;
+ p0.y = dev_y - dev_unit.dvi2pts * width;
+ p1.x = dev_x + dev_unit.dvi2pts * height;
+ p1.y = p0.y;
+ p2.x = p1.x;
+ p2.y = dev_y;
+ p3.x = p0.x;
+ p3.y = p2.y;
+ } else {
+ p0.x = dev_x;
+ p0.y = dev_y - dev_unit.dvi2pts * depth;
+ p1.x = dev_x + dev_unit.dvi2pts * width;
+ p1.y = p0.y;
+ p2.x = p1.x;
+ p2.y = dev_y + dev_unit.dvi2pts * height;
+ p3.x = p0.x;
+ p3.y = p2.y;
+ }
+
+ pdf_dev_transform(&p0, NULL); /* currentmatrix */
+ pdf_dev_transform(&p1, NULL);
+ pdf_dev_transform(&p2, NULL);
+ pdf_dev_transform(&p3, NULL);
+
+ min_x = MIN(p0.x , p1.x);
+ min_x = MIN(min_x, p2.x);
+ min_x = MIN(min_x, p3.x);
+
+ max_x = MAX(p0.x , p1.x);
+ max_x = MAX(max_x, p2.x);
+ max_x = MAX(max_x, p3.x);
+
+ min_y = MIN(p0.y , p1.y);
+ min_y = MIN(min_y, p2.y);
+ min_y = MIN(min_y, p3.y);
+
+ max_y = MAX(p0.y , p1.y);
+ max_y = MAX(max_y, p2.y);
+ max_y = MAX(max_y, p3.y);
+
+ rect->llx = min_x;
+ rect->lly = min_y;
+ rect->urx = max_x;
+ rect->ury = max_y;
+
+ return;
+}
+
+int
+pdf_dev_get_dirmode (void)
+{
+ return text_state.dir_mode;
+}
+
+void
+pdf_dev_set_dirmode (int text_dir)
+{
+ struct dev_font *font;
+ int text_rotate;
+ int vert_dir, vert_font;
+
+ font = CURRENTFONT();
+
+ vert_font = (font && font->wmode) ? 1 : 0;
+ if (dev_param.autorotate) {
+ vert_dir = text_dir ? 1 : 0;
+ } else {
+ vert_dir = vert_font;
+ }
+ text_rotate = (vert_font << 1)|vert_dir;
+
+ if (font &&
+ ANGLE_CHANGES(text_rotate, text_state.matrix.rotate)) {
+ text_state.force_reset = 1;
+ }
+
+ text_state.matrix.rotate = text_rotate;
+ text_state.dir_mode = text_dir;
+}
+
+static void
+dev_set_param_autorotate (int auto_rotate)
+{
+ struct dev_font *font;
+ int text_rotate, vert_font, vert_dir;
+
+ font = CURRENTFONT();
+
+ vert_font = (font && font->wmode) ? 1 : 0;
+ if (auto_rotate) {
+ vert_dir = text_state.dir_mode ? 1 : 0;
+ } else {
+ vert_dir = vert_font;
+ }
+ text_rotate = (vert_font << 1)|vert_dir;
+
+ if (ANGLE_CHANGES(text_rotate, text_state.matrix.rotate)) {
+ text_state.force_reset = 1;
+ }
+ text_state.matrix.rotate = text_rotate;
+ dev_param.autorotate = auto_rotate;
+}
+
+int
+pdf_dev_get_param (int param_type)
+{
+ int value = 0;
+
+ switch (param_type) {
+ case PDF_DEV_PARAM_AUTOROTATE:
+ value = dev_param.autorotate;
+ break;
+ case PDF_DEV_PARAM_COLORMODE:
+ value = dev_param.colormode;
+ break;
+ default:
+ ERROR("Unknown device parameter: %d", param_type);
+ }
+
+ return value;
+}
+
+void
+pdf_dev_set_param (int param_type, int value)
+{
+ switch (param_type) {
+ case PDF_DEV_PARAM_AUTOROTATE:
+ dev_set_param_autorotate(value);
+ break;
+ case PDF_DEV_PARAM_COLORMODE:
+ dev_param.colormode = value; /* 0 for B&W */
+ break;
+ default:
+ ERROR("Unknown device parameter: %d", param_type);
+ }
+
+ return;
+}
+
+
+int
+pdf_dev_put_image (int id,
+ transform_info *p,
+ double ref_x,
+ double ref_y)
+{
+ char *res_name;
+ pdf_tmatrix M;
+ pdf_rect r;
+ int len = 0;
+
+ if (num_dev_coords > 0) {
+ ref_x -= dev_coords[num_dev_coords-1].x;
+ ref_y -= dev_coords[num_dev_coords-1].y;
+ }
+
+ pdf_copymatrix(&M, &(p->matrix));
+ M.e += ref_x; M.f += ref_y;
+ /* Just rotate by -90, but not tested yet. Any problem if M has scaling? */
+ if (dev_param.autorotate &&
+ text_state.dir_mode) {
+ double tmp;
+ tmp = -M.a; M.a = M.b; M.b = tmp;
+ tmp = -M.c; M.c = M.d; M.d = tmp;
+ }
+
+ graphics_mode();
+ pdf_dev_gsave();
+
+ pdf_dev_concat(&M);
+
+ pdf_ximage_scale_image(id, &M, &r, p);
+ pdf_dev_concat(&M);
+
+ /* Clip */
+ if (p->flags & INFO_DO_CLIP) {
+#if 0
+ pdf_dev_newpath();
+ pdf_dev_moveto(r.llx, r.lly);
+ pdf_dev_lineto(r.urx, r.lly);
+ pdf_dev_lineto(r.urx, r.ury);
+ pdf_dev_lineto(r.llx, r.ury);
+ pdf_dev_closepath();
+ pdf_dev_clip();
+ pdf_dev_newpath();
+#else
+ pdf_dev_rectclip(r.llx, r.lly, r.urx - r.llx, r.ury - r.lly);
+#endif
+ }
+
+ res_name = pdf_ximage_get_resname(id);
+ len = sprintf(work_buffer, " /%s Do", res_name);
+ pdf_doc_add_page_content(work_buffer, len);
+
+ pdf_dev_grestore();
+
+ pdf_doc_add_page_resource("XObject",
+ res_name,
+ pdf_ximage_get_reference(id));
+
+ if (dvi_is_tracking_boxes()) {
+ pdf_tmatrix P;
+ int i;
+ pdf_rect rect;
+ pdf_coord corner[4];
+
+ pdf_dev_set_rect(&rect, 65536 * ref_x, 65536 * ref_y,
+ 65536 * (r.urx - r.llx), 65536 * (r.ury - r.lly), 0);
+
+ corner[0].x = rect.llx; corner[0].y = rect.lly;
+ corner[1].x = rect.llx; corner[1].y = rect.ury;
+ corner[2].x = rect.urx; corner[2].y = rect.ury;
+ corner[3].x = rect.urx; corner[3].y = rect.lly;
+
+ pdf_copymatrix(&P, &(p->matrix));
+ for (i = 0; i < 4; ++i) {
+ corner[i].x -= rect.llx;
+ corner[i].y -= rect.lly;
+ pdf_dev_transform(&(corner[i]), &P);
+ corner[i].x += rect.llx;
+ corner[i].y += rect.lly;
+ }
+
+ rect.llx = corner[0].x;
+ rect.lly = corner[0].y;
+ rect.urx = corner[0].x;
+ rect.ury = corner[0].y;
+ for (i = 0; i < 4; ++i) {
+ if (corner[i].x < rect.llx)
+ rect.llx = corner[i].x;
+ if (corner[i].x > rect.urx)
+ rect.urx = corner[i].x;
+ if (corner[i].y < rect.lly)
+ rect.lly = corner[i].y;
+ if (corner[i].y > rect.ury)
+ rect.ury = corner[i].y;
+ }
+
+ pdf_doc_expand_box(&rect);
+ }
+
+ return 0;
+}
+
+
+void
+transform_info_clear (transform_info *info)
+{
+ /* Physical dimensions */
+ info->width = 0.0;
+ info->height = 0.0;
+ info->depth = 0.0;
+
+ info->bbox.llx = 0.0;
+ info->bbox.lly = 0.0;
+ info->bbox.urx = 0.0;
+ info->bbox.ury = 0.0;
+
+ /* Transformation matrix */
+ pdf_setmatrix(&(info->matrix), 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
+
+ info->flags = 0;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/pdfdev.h b/Build/source/texk/dvipdf-x/xsrc/pdfdev.h
new file mode 100644
index 00000000000..25bac2ecd47
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pdfdev.h
@@ -0,0 +1,231 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _PDFDEV_H_
+#define _PDFDEV_H_
+
+#include "numbers.h"
+#include "pdfobj.h"
+#include "pdfcolor.h"
+
+typedef signed long spt_t;
+
+typedef struct pdf_tmatrix
+{
+ double a, b, c, d, e, f;
+} pdf_tmatrix;
+
+typedef struct pdf_rect
+{
+ double llx, lly, urx, ury;
+} pdf_rect;
+
+typedef struct pdf_coord
+{
+ double x, y;
+} pdf_coord;
+
+/* The name transform_info is misleading.
+ * I'll put this here for a moment...
+ */
+typedef struct
+{
+ /* Physical dimensions
+ *
+ * If those values are given, images will be scaled
+ * and/or shifted to fit within a box described by
+ * those values.
+ */
+ double width;
+ double height;
+ double depth;
+
+ pdf_tmatrix matrix; /* transform matrix */
+ pdf_rect bbox; /* user_bbox */
+
+ int flags;
+} transform_info;
+#define INFO_HAS_USER_BBOX (1 << 0)
+#define INFO_HAS_WIDTH (1 << 1)
+#define INFO_HAS_HEIGHT (1 << 2)
+#define INFO_DO_CLIP (1 << 3)
+#define INFO_DO_HIDE (1 << 4)
+extern void transform_info_clear (transform_info *info);
+
+
+extern void pdf_dev_set_verbose (void);
+
+/* Not in spt_t. */
+extern int pdf_sprint_matrix (char *buf, const pdf_tmatrix *p);
+extern int pdf_sprint_rect (char *buf, const pdf_rect *p);
+extern int pdf_sprint_coord (char *buf, const pdf_coord *p);
+extern int pdf_sprint_length (char *buf, double value);
+extern int pdf_sprint_number (char *buf, double value);
+
+/* unit_conv: multiplier for input unit (spt_t) to bp conversion.
+ * precision: How many fractional digits preserved in output (not real
+ * accuracy control).
+ * is_bw: Ignore color related special instructions.
+ */
+extern void pdf_init_device (double unit_conv, int precision, int is_bw);
+extern void pdf_close_device (void);
+
+/* returns 1.0/unit_conv */
+extern double dev_unit_dviunit (void);
+
+#if 0
+/* DVI interpreter knows text positioning in relative motion.
+ * However, pdf_dev_set_string() recieves text string with placement
+ * in absolute position in user space, and it convert absolute
+ * positioning back to relative positioning. It is quite wasteful.
+ *
+ * TeX using DVI register stack operation to do CR and then use down
+ * command for LF. DVI interpreter knows hint for current leading
+ * and others (raised or lowered), but they are mostly lost in
+ * pdf_dev_set_string().
+ */
+
+typedef struct
+{
+ int argc;
+
+ struct {
+ int is_kern; /* kern or string */
+
+ spt_t kern; /* negative kern means space */
+
+ int offset; /* offset to sbuf */
+ int length; /* length of string */
+ } args[];
+
+ unsigned char sbuf[PDF_STRING_LEN_MAX];
+
+} pdf_text_string;
+
+/* Something for handling raise, leading, etc. here. */
+
+#endif
+
+/* Draw texts and rules:
+ *
+ * xpos, ypos, width, and height are all fixed-point numbers
+ * converted to big-points by multiplying unit_conv (dvi2pts).
+ * They must be position in the user space.
+ *
+ * ctype:
+ * 0 - input string is in multi-byte encoding.
+ * 1 - input string is in 8-bit encoding.
+ * 2 - input string is in 16-bit encoding.
+ */
+extern void pdf_dev_set_string (spt_t xpos, spt_t ypos,
+ const void *instr_ptr, int instr_len,
+ spt_t text_width,
+ int font_id, int ctype);
+extern void pdf_dev_set_rule (spt_t xpos, spt_t ypos,
+ spt_t width, spt_t height);
+
+/* Place XObject */
+extern int pdf_dev_put_image (int xobj_id,
+ transform_info *p, double ref_x, double ref_y);
+
+/* The design_size and ptsize required by PK font support...
+ */
+extern int pdf_dev_locate_font (const char *font_name, spt_t ptsize);
+
+extern int pdf_dev_setfont (const char *font_name, spt_t ptsize);
+
+/* The following two routines are NOT WORKING.
+ * Dvipdfmx doesn't manage gstate well..
+ */
+/* pdf_dev_translate() or pdf_dev_concat() should be used. */
+extern void pdf_dev_set_origin (double orig_x, double orig_y);
+/* Always returns 1.0, please rename this. */
+extern double pdf_dev_scale (void);
+
+/* Access text state parameters. */
+#if 0
+extern int pdf_dev_currentfont (void); /* returns font_id */
+extern double pdf_dev_get_font_ptsize (int font_id);
+#endif /* 0 */
+extern int pdf_dev_get_font_wmode (int font_id); /* ps: special support want this (pTeX). */
+
+/* Text composition (direction) mode
+ * This affects only when auto_rotate is enabled.
+ */
+extern int pdf_dev_get_dirmode (void);
+extern void pdf_dev_set_dirmode (int dir_mode);
+
+/* Set rect to rectangle in device space.
+ * Unit conversion spt_t to bp and transformation applied within it.
+ */
+extern void pdf_dev_set_rect (pdf_rect *rect,
+ spt_t x_pos, spt_t y_pos,
+ spt_t width, spt_t height, spt_t depth);
+
+/* Accessor to various device parameters.
+ */
+#define PDF_DEV_PARAM_AUTOROTATE 1
+#define PDF_DEV_PARAM_COLORMODE 2
+
+extern int pdf_dev_get_param (int param_type);
+extern void pdf_dev_set_param (int param_type, int value);
+
+/* Text composition mode is ignored (always same as font's
+ * writing mode) and glyph rotation is not enabled if
+ * auto_rotate is unset.
+ */
+#define pdf_dev_set_autorotate(v) pdf_dev_set_param(PDF_DEV_PARAM_AUTOROTATE, (v))
+#define pdf_dev_set_colormode(v) pdf_dev_set_param(PDF_DEV_PARAM_COLORMODE, (v))
+
+/*
+ * For pdf_doc, pdf_draw and others.
+ */
+
+/* Force reselecting font and color:
+ * XFrom (content grabbing) and Metapost support want them.
+ */
+extern void pdf_dev_reset_fonts (void);
+extern void pdf_dev_reset_color (void);
+
+extern void pdf_dev_set_color (pdf_color *color);
+extern void pdf_dev_set_strokingcolor (pdf_color *color);
+extern void pdf_dev_set_nonstrokingcolor (pdf_color *color);
+
+/* Initialization of transformation matrix with M and others.
+ * They are called within pdf_doc_begin_page() and pdf_doc_end_page().
+ */
+extern void pdf_dev_bop (const pdf_tmatrix *M);
+extern void pdf_dev_eop (void);
+
+/* Text is normal and line art is not normal in dvipdfmx. So we don't have
+ * begin_text (BT in PDF) and end_text (ET), but instead we have graphics_mode()
+ * to terminate text section. pdf_dev_flushpath() and others call this.
+ */
+extern void graphics_mode (void);
+
+extern void pdf_dev_get_coord(double *xpos, double *ypos);
+extern void pdf_dev_push_coord(double xpos, double ypos);
+extern void pdf_dev_pop_coord(void);
+
+#endif /* _PDFDEV_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/pdfdoc.c b/Build/source/texk/dvipdf-x/xsrc/pdfdoc.c
new file mode 100644
index 00000000000..9c4731ecffd
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pdfdoc.c
@@ -0,0 +1,2331 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2008-2012 by Jin-Hwan Cho, Matthias Franz, and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+/*
+ * TODO: Many things...
+ * {begin,end}_{bead,article}, box stack, name tree (not limited to dests)...
+ */
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <time.h>
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+#include "mfileio.h"
+
+#include "numbers.h"
+
+#include "pdfobj.h"
+#include "pdfparse.h"
+#include "pdfnames.h"
+
+#include "pdfencrypt.h"
+
+#include "pdfdev.h"
+#include "pdfdraw.h"
+#include "pdfcolor.h"
+
+#include "pdfresource.h"
+#include "pdffont.h"
+#include "pdfximage.h"
+
+#include "pdflimits.h"
+
+#if HAVE_LIBPNG
+#include "pngimage.h"
+#endif
+#include "jpegimage.h"
+
+#include "pdfdoc.h"
+
+#define PDFDOC_PAGES_ALLOC_SIZE 128u
+#define PDFDOC_ARTICLE_ALLOC_SIZE 16
+#define PDFDOC_BEAD_ALLOC_SIZE 16
+
+static int verbose = 0;
+
+static char manual_thumb_enabled = 0;
+static char *thumb_basename = NULL;
+
+void
+pdf_doc_enable_manual_thumbnails (void)
+{
+#if HAVE_LIBPNG
+ manual_thumb_enabled = 1;
+#else
+ WARN("Manual thumbnail is not supported without the libpng library.");
+#endif
+}
+
+static pdf_obj *
+read_thumbnail (const char *thumb_filename)
+{
+ pdf_obj *image_ref;
+ int xobj_id;
+ FILE *fp;
+
+ fp = MFOPEN(thumb_filename, FOPEN_RBIN_MODE);
+ if (!fp) {
+ WARN("Could not open thumbnail file \"%s\"", thumb_filename);
+ return NULL;
+ }
+ if (!check_for_png(fp) && !check_for_jpeg(fp)) {
+ WARN("Thumbnail \"%s\" not a png/jpeg file!", thumb_filename);
+ MFCLOSE(fp);
+ return NULL;
+ }
+ MFCLOSE(fp);
+
+ xobj_id = pdf_ximage_findresource(thumb_filename, 0, NULL);
+ if (xobj_id < 0) {
+ WARN("Could not read thumbnail file \"%s\".", thumb_filename);
+ image_ref = NULL;
+ } else {
+ image_ref = pdf_ximage_get_reference(xobj_id);
+ }
+
+ return image_ref;
+}
+
+void
+pdf_doc_set_verbose (void)
+{
+ verbose++;
+ pdf_font_set_verbose();
+ pdf_color_set_verbose();
+ pdf_ximage_set_verbose();
+}
+
+typedef struct pdf_form
+{
+ char *ident;
+
+ pdf_tmatrix matrix;
+ pdf_rect cropbox;
+
+ pdf_obj *resources;
+ pdf_obj *contents;
+} pdf_form;
+
+struct form_list_node
+{
+ int q_depth;
+ pdf_form form;
+
+ struct form_list_node *prev;
+};
+
+#define USE_MY_MEDIABOX (1 << 0)
+typedef struct pdf_page
+{
+ pdf_obj *page_obj;
+ pdf_obj *page_ref;
+
+ int flags;
+
+ double ref_x, ref_y;
+ pdf_rect cropbox;
+
+ pdf_obj *resources;
+
+ /* Contents */
+ pdf_obj *background;
+ pdf_obj *contents;
+
+ /* global bop, background, contents, global eop */
+ pdf_obj *content_refs[4];
+
+ pdf_obj *annots;
+ pdf_obj *beads;
+} pdf_page;
+
+typedef struct pdf_olitem
+{
+ pdf_obj *dict;
+
+ int is_open;
+
+ struct pdf_olitem *first;
+ struct pdf_olitem *parent;
+
+ struct pdf_olitem *next;
+} pdf_olitem;
+
+typedef struct pdf_bead
+{
+ char *id;
+ long page_no;
+ pdf_rect rect;
+} pdf_bead;
+
+typedef struct pdf_article
+{
+ char *id;
+ pdf_obj *info;
+ long num_beads;
+ long max_beads;
+ pdf_bead *beads;
+} pdf_article;
+
+struct name_dict
+{
+ const char *category;
+ struct ht_table *data;
+};
+
+
+typedef struct pdf_doc
+{
+ struct {
+ pdf_obj *dict;
+
+ pdf_obj *viewerpref;
+ pdf_obj *pagelabels;
+ pdf_obj *pages;
+ pdf_obj *names;
+ pdf_obj *threads;
+ } root;
+
+ pdf_obj *info;
+
+ struct {
+ pdf_rect mediabox;
+ pdf_obj *bop, *eop;
+
+ long num_entries; /* This is not actually total number of pages. */
+ long max_entries;
+ pdf_page *entries;
+ } pages;
+
+ struct {
+ pdf_olitem *first;
+ pdf_olitem *current;
+ int current_depth;
+ } outlines;
+
+ struct {
+ long num_entries;
+ long max_entries;
+ pdf_article *entries;
+ } articles;
+
+ struct name_dict *names;
+
+ struct {
+ int outline_open_depth;
+ double annot_grow;
+ } opt;
+
+ struct form_list_node *pending_forms;
+
+} pdf_doc;
+static pdf_doc pdoc;
+
+static void
+pdf_doc_init_catalog (pdf_doc *p)
+{
+ p->root.viewerpref = NULL;
+ p->root.pagelabels = NULL;
+ p->root.pages = NULL;
+ p->root.names = NULL;
+ p->root.threads = NULL;
+
+ p->root.dict = pdf_new_dict();
+ pdf_set_root(p->root.dict);
+
+ return;
+}
+
+static void
+pdf_doc_close_catalog (pdf_doc *p)
+{
+ pdf_obj *tmp;
+
+ if (p->root.viewerpref) {
+ tmp = pdf_lookup_dict(p->root.dict, "ViewerPreferences");
+ if (!tmp) {
+ pdf_add_dict(p->root.dict,
+ pdf_new_name("ViewerPreferences"),
+ pdf_ref_obj (p->root.viewerpref));
+ } else if (PDF_OBJ_DICTTYPE(tmp)) {
+ pdf_merge_dict(p->root.viewerpref, tmp);
+ pdf_add_dict(p->root.dict,
+ pdf_new_name("ViewerPreferences"),
+ pdf_ref_obj (p->root.viewerpref));
+ } else { /* Maybe reference */
+ /* What should I do? */
+ WARN("Could not modify ViewerPreferences.");
+ }
+ pdf_release_obj(p->root.viewerpref);
+ p->root.viewerpref = NULL;
+ }
+
+ if (p->root.pagelabels) {
+ tmp = pdf_lookup_dict(p->root.dict, "PageLabels");
+ if (!tmp) {
+ tmp = pdf_new_dict();
+ pdf_add_dict(tmp, pdf_new_name("Nums"), pdf_link_obj(p->root.pagelabels));
+ pdf_add_dict(p->root.dict,
+ pdf_new_name("PageLabels"), pdf_ref_obj(tmp));
+ pdf_release_obj(tmp);
+ } else { /* Maybe reference */
+ /* What should I do? */
+ WARN("Could not modify PageLabels.");
+ }
+ pdf_release_obj(p->root.pagelabels);
+ p->root.pagelabels = NULL;
+ }
+
+ pdf_add_dict(p->root.dict,
+ pdf_new_name("Type"), pdf_new_name("Catalog"));
+ pdf_release_obj(p->root.dict);
+ p->root.dict = NULL;
+
+ return;
+}
+
+/*
+ * Pages are starting at 1.
+ * The page count does not increase until the page is finished.
+ */
+#define LASTPAGE(p) (&(p->pages.entries[p->pages.num_entries]))
+#define FIRSTPAGE(p) (&(p->pages.entries[0]))
+#define PAGECOUNT(p) (p->pages.num_entries)
+#define MAXPAGES(p) (p->pages.max_entries)
+
+static void
+doc_resize_page_entries (pdf_doc *p, long size)
+{
+ if (size > MAXPAGES(p)) {
+ long i;
+
+ p->pages.entries = RENEW(p->pages.entries, size, struct pdf_page);
+ for (i = p->pages.max_entries; i < size; i++) {
+ p->pages.entries[i].page_obj = NULL;
+ p->pages.entries[i].page_ref = NULL;
+ p->pages.entries[i].flags = 0;
+ p->pages.entries[i].resources = NULL;
+ p->pages.entries[i].background = NULL;
+ p->pages.entries[i].contents = NULL;
+ p->pages.entries[i].content_refs[0] = NULL; /* global bop */
+ p->pages.entries[i].content_refs[1] = NULL; /* background */
+ p->pages.entries[i].content_refs[2] = NULL; /* page body */
+ p->pages.entries[i].content_refs[3] = NULL; /* global eop */
+ p->pages.entries[i].annots = NULL;
+ p->pages.entries[i].beads = NULL;
+ }
+ p->pages.max_entries = size;
+ }
+
+ return;
+}
+
+static pdf_page *
+doc_get_page_entry (pdf_doc *p, unsigned long page_no)
+{
+ pdf_page *page;
+
+ if (page_no > 65535ul) {
+ ERROR("Page number %ul too large!", page_no);
+ } else if (page_no == 0) {
+ ERROR("Invalid Page number %ul.", page_no);
+ }
+
+ if (page_no > MAXPAGES(p)) {
+ doc_resize_page_entries(p, page_no + PDFDOC_PAGES_ALLOC_SIZE);
+ }
+
+ page = &(p->pages.entries[page_no - 1]);
+
+ return page;
+}
+
+static void pdf_doc_init_page_tree (pdf_doc *p, double media_width, double media_height);
+static void pdf_doc_close_page_tree (pdf_doc *p);
+
+static void pdf_doc_init_names (pdf_doc *p);
+static void pdf_doc_close_names (pdf_doc *p);
+
+static void pdf_doc_init_docinfo (pdf_doc *p);
+static void pdf_doc_close_docinfo (pdf_doc *p);
+
+static void pdf_doc_init_articles (pdf_doc *p);
+static void pdf_doc_close_articles (pdf_doc *p);
+static void pdf_doc_init_bookmarks (pdf_doc *p, int bm_open_depth);
+static void pdf_doc_close_bookmarks (pdf_doc *p);
+
+void
+pdf_doc_set_bop_content (const char *content, unsigned length)
+{
+ pdf_doc *p = &pdoc;
+
+ ASSERT(p);
+
+ if (p->pages.bop) {
+ pdf_release_obj(p->pages.bop);
+ p->pages.bop = NULL;
+ }
+
+ if (length > 0) {
+ p->pages.bop = pdf_new_stream(STREAM_COMPRESS);
+ pdf_add_stream(p->pages.bop, content, length);
+ } else {
+ p->pages.bop = NULL;
+ }
+
+ return;
+}
+
+void
+pdf_doc_set_eop_content (const char *content, unsigned length)
+{
+ pdf_doc *p = &pdoc;
+
+ if (p->pages.eop) {
+ pdf_release_obj(p->pages.eop);
+ p->pages.eop = NULL;
+ }
+
+ if (length > 0) {
+ p->pages.eop = pdf_new_stream(STREAM_COMPRESS);
+ pdf_add_stream(p->pages.eop, content, length);
+ } else {
+ p->pages.eop = NULL;
+ }
+
+ return;
+}
+
+#ifndef HAVE_TM_GMTOFF
+#ifndef HAVE_TIMEZONE
+
+/* auxiliary function to compute timezone offset on
+ systems that do not support the tm_gmtoff in struct tm,
+ or have a timezone variable. Such as i386-solaris. */
+
+static long
+compute_timezone_offset()
+{
+ const time_t now = time(NULL);
+ struct tm tm;
+ struct tm local;
+ time_t gmtoff;
+
+ localtime_r(&now, &local);
+ gmtime_r(&now, &tm);
+ return (mktime(&local) - mktime(&tm));
+}
+
+#endif /* HAVE_TIMEZONE */
+#endif /* HAVE_TM_GMTOFF */
+
+/*
+ * Docinfo
+ */
+static long
+asn_date (char *date_string)
+{
+ long tz_offset;
+ time_t current_time;
+ struct tm *bd_time;
+
+ time(&current_time);
+ bd_time = localtime(&current_time);
+
+#ifdef HAVE_TM_GMTOFF
+ tz_offset = bd_time->tm_gmtoff;
+#else
+# ifdef HAVE_TIMEZONE
+ tz_offset = -timezone;
+# else
+ tz_offset = compute_timezone_offset();
+# endif /* HAVE_TIMEZONE */
+#endif /* HAVE_TM_GMTOFF */
+
+ sprintf(date_string, "D:%04d%02d%02d%02d%02d%02d%c%02ld'%02ld'",
+ bd_time->tm_year + 1900, bd_time->tm_mon + 1, bd_time->tm_mday,
+ bd_time->tm_hour, bd_time->tm_min, bd_time->tm_sec,
+ (tz_offset > 0) ? '+' : '-', labs(tz_offset) / 3600,
+ (labs(tz_offset) / 60) % 60);
+
+ return strlen(date_string);
+}
+
+static void
+pdf_doc_init_docinfo (pdf_doc *p)
+{
+ p->info = pdf_new_dict();
+ pdf_set_info(p->info);
+
+ return;
+}
+
+static void
+pdf_doc_close_docinfo (pdf_doc *p)
+{
+ pdf_obj *docinfo = p->info;
+
+ /*
+ * Excerpt from PDF Reference 4th ed., sec. 10.2.1.
+ *
+ * Any entry whose value is not known should be omitted from the dictionary,
+ * rather than included with an empty string as its value.
+ *
+ * ....
+ *
+ * Note: Although viewer applications can store custom metadata in the document
+ * information dictionary, it is inappropriate to store private content or
+ * structural information there; such information should be stored in the
+ * document catalog instead (see Section 3.6.1, Document Catalog ).
+ */
+ const char *keys[] = {
+ "Title", "Author", "Subject", "Keywords", "Creator", "Producer",
+ "CreationDate", "ModDate", /* Date */
+ NULL
+ };
+ pdf_obj *value;
+ char *banner;
+ int i;
+
+ for (i = 0; keys[i] != NULL; i++) {
+ value = pdf_lookup_dict(docinfo, keys[i]);
+ if (value) {
+ if (!PDF_OBJ_STRINGTYPE(value)) {
+ WARN("\"%s\" in DocInfo dictionary not string type.", keys[i]);
+ pdf_remove_dict(docinfo, keys[i]);
+ WARN("\"%s\" removed from DocInfo.", keys[i]);
+ } else if (pdf_string_length(value) == 0) {
+ /* The hyperref package often uses emtpy strings. */
+ pdf_remove_dict(docinfo, keys[i]);
+ }
+ }
+ }
+
+ banner = NEW(strlen(PACKAGE)+strlen(VERSION)+4, char);
+ sprintf(banner, "%s (%s)", PACKAGE, VERSION);
+ pdf_add_dict(docinfo,
+ pdf_new_name("Producer"),
+ pdf_new_string(banner, strlen(banner)));
+ RELEASE(banner);
+
+ if (!pdf_lookup_dict(docinfo, "CreationDate")) {
+ char now[32];
+
+ asn_date(now);
+ pdf_add_dict(docinfo,
+ pdf_new_name ("CreationDate"),
+ pdf_new_string(now, strlen(now)));
+ }
+
+ pdf_release_obj(docinfo);
+ p->info = NULL;
+
+ return;
+}
+
+static pdf_obj *
+pdf_doc_get_page_resources (pdf_doc *p, const char *category)
+{
+ pdf_obj *resources;
+ pdf_page *currentpage;
+ pdf_obj *res_dict;
+
+ if (!p || !category) {
+ return NULL;
+ }
+
+ if (p->pending_forms) {
+ if (p->pending_forms->form.resources) {
+ res_dict = p->pending_forms->form.resources;
+ } else {
+ res_dict = p->pending_forms->form.resources = pdf_new_dict();
+ }
+ } else {
+ currentpage = LASTPAGE(p);
+ if (currentpage->resources) {
+ res_dict = currentpage->resources;
+ } else {
+ res_dict = currentpage->resources = pdf_new_dict();
+ }
+ }
+ resources = pdf_lookup_dict(res_dict, category);
+ if (!resources) {
+ resources = pdf_new_dict();
+ pdf_add_dict(res_dict, pdf_new_name(category), resources);
+ }
+
+ return resources;
+}
+
+void
+pdf_doc_add_page_resource (const char *category,
+ const char *resource_name, pdf_obj *resource_ref)
+{
+ pdf_doc *p = &pdoc;
+ pdf_obj *resources;
+ pdf_obj *duplicate;
+
+ if (!PDF_OBJ_INDIRECTTYPE(resource_ref)) {
+ WARN("Passed non indirect reference...");
+ resource_ref = pdf_ref_obj(resource_ref); /* leak */
+ }
+ resources = pdf_doc_get_page_resources(p, category);
+ duplicate = pdf_lookup_dict(resources, resource_name);
+ if (duplicate && pdf_compare_reference(duplicate, resource_ref)) {
+ WARN("Conflicting page resource found (page: %ld, category: %s, name: %s).",
+ pdf_doc_current_page_number(), category, resource_name);
+ WARN("Ignoring...");
+ pdf_release_obj(resource_ref);
+ } else {
+ pdf_add_dict(resources, pdf_new_name(resource_name), resource_ref);
+ }
+
+ return;
+}
+
+static void
+doc_flush_page (pdf_doc *p, pdf_page *page, pdf_obj *parent_ref)
+{
+ pdf_obj *contents_array;
+ int count;
+
+ pdf_add_dict(page->page_obj,
+ pdf_new_name("Type"), pdf_new_name("Page"));
+ pdf_add_dict(page->page_obj,
+ pdf_new_name("Parent"), parent_ref);
+
+ /*
+ * Clipping area specified by CropBox is affected by MediaBox which
+ * might be inherit from parent node. If MediaBox of the root node
+ * does not have enough size to cover all page's imaging area, using
+ * CropBox here gives incorrect result.
+ */
+ if (page->flags & USE_MY_MEDIABOX) {
+ pdf_obj *mediabox;
+
+ mediabox = pdf_new_array();
+ pdf_add_array(mediabox,
+ pdf_new_number(ROUND(page->cropbox.llx, 0.01)));
+ pdf_add_array(mediabox,
+ pdf_new_number(ROUND(page->cropbox.lly, 0.01)));
+ pdf_add_array(mediabox,
+ pdf_new_number(ROUND(page->cropbox.urx, 0.01)));
+ pdf_add_array(mediabox,
+ pdf_new_number(ROUND(page->cropbox.ury, 0.01)));
+ pdf_add_dict(page->page_obj, pdf_new_name("MediaBox"), mediabox);
+ }
+
+ count = 0;
+ contents_array = pdf_new_array();
+ if (page->content_refs[0]) { /* global bop */
+ pdf_add_array(contents_array, page->content_refs[0]);
+ count++;
+ } else if (p->pages.bop &&
+ pdf_stream_length(p->pages.bop) > 0) {
+ pdf_add_array(contents_array, pdf_ref_obj(p->pages.bop));
+ count++;
+ }
+ if (page->content_refs[1]) { /* background */
+ pdf_add_array(contents_array, page->content_refs[1]);
+ count++;
+ }
+ if (page->content_refs[2]) { /* page body */
+ pdf_add_array(contents_array, page->content_refs[2]);
+ count++;
+ }
+ if (page->content_refs[3]) { /* global eop */
+ pdf_add_array(contents_array, page->content_refs[3]);
+ count++;
+ } else if (p->pages.eop &&
+ pdf_stream_length(p->pages.eop) > 0) {
+ pdf_add_array(contents_array, pdf_ref_obj(p->pages.eop));
+ count++;
+ }
+
+ if (count == 0) {
+ WARN("Page with empty content found!!!");
+ }
+ page->content_refs[0] = NULL;
+ page->content_refs[1] = NULL;
+ page->content_refs[2] = NULL;
+ page->content_refs[3] = NULL;
+
+ pdf_add_dict(page->page_obj,
+ pdf_new_name("Contents"), contents_array);
+
+
+ if (page->annots) {
+ pdf_add_dict(page->page_obj,
+ pdf_new_name("Annots"), pdf_ref_obj(page->annots));
+ pdf_release_obj(page->annots);
+ }
+ if (page->beads) {
+ pdf_add_dict(page->page_obj,
+ pdf_new_name("B"), pdf_ref_obj(page->beads));
+ pdf_release_obj(page->beads);
+ }
+ pdf_release_obj(page->page_obj);
+ pdf_release_obj(page->page_ref);
+
+ page->page_obj = NULL;
+ page->page_ref = NULL;
+ page->annots = NULL;
+ page->beads = NULL;
+
+ return;
+}
+
+/* B-tree? */
+#define PAGE_CLUSTER 4
+static pdf_obj *
+build_page_tree (pdf_doc *p,
+ pdf_page *firstpage, long num_pages,
+ pdf_obj *parent_ref)
+{
+ pdf_obj *self, *self_ref, *kids;
+ long i;
+
+ self = pdf_new_dict();
+ /*
+ * This is a slight kludge which allow the subtree dictionary
+ * generated by this routine to be merged with the real
+ * page_tree dictionary, while keeping the indirect object
+ * references right.
+ */
+ self_ref = parent_ref ? pdf_ref_obj(self) : pdf_ref_obj(p->root.pages);
+
+ pdf_add_dict(self, pdf_new_name("Type"), pdf_new_name("Pages"));
+ pdf_add_dict(self, pdf_new_name("Count"), pdf_new_number((double) num_pages));
+
+ if (parent_ref != NULL)
+ pdf_add_dict(self, pdf_new_name("Parent"), parent_ref);
+
+ kids = pdf_new_array();
+ if (num_pages > 0 && num_pages <= PAGE_CLUSTER) {
+ for (i = 0; i < num_pages; i++) {
+ pdf_page *page;
+
+ page = firstpage + i;
+ if (!page->page_ref)
+ page->page_ref = pdf_ref_obj(page->page_obj);
+ pdf_add_array (kids, pdf_link_obj(page->page_ref));
+ doc_flush_page(p, page, pdf_link_obj(self_ref));
+ }
+ } else if (num_pages > 0) {
+ for (i = 0; i < PAGE_CLUSTER; i++) {
+ long start, end;
+
+ start = (i*num_pages)/PAGE_CLUSTER;
+ end = ((i+1)*num_pages)/PAGE_CLUSTER;
+ if (end - start > 1) {
+ pdf_obj *subtree;
+
+ subtree = build_page_tree(p, firstpage + start, end - start,
+ pdf_link_obj(self_ref));
+ pdf_add_array(kids, pdf_ref_obj(subtree));
+ pdf_release_obj(subtree);
+ } else {
+ pdf_page *page;
+
+ page = firstpage + start;
+ if (!page->page_ref)
+ page->page_ref = pdf_ref_obj(page->page_obj);
+ pdf_add_array (kids, pdf_link_obj(page->page_ref));
+ doc_flush_page(p, page, pdf_link_obj(self_ref));
+ }
+ }
+ }
+ pdf_add_dict(self, pdf_new_name("Kids"), kids);
+ pdf_release_obj(self_ref);
+
+ return self;
+}
+
+static void
+pdf_doc_init_page_tree (pdf_doc *p, double media_width, double media_height)
+{
+ /*
+ * Create empty page tree.
+ * The docroot.pages is kept open until the document is closed.
+ * This allows the user to write to pages if he so choses.
+ */
+ p->root.pages = pdf_new_dict();
+
+ p->pages.num_entries = 0;
+ p->pages.max_entries = 0;
+ p->pages.entries = NULL;
+
+ p->pages.bop = NULL;
+ p->pages.eop = NULL;
+
+ p->pages.mediabox.llx = 0.0;
+ p->pages.mediabox.lly = 0.0;
+ p->pages.mediabox.urx = media_width;
+ p->pages.mediabox.ury = media_height;
+
+ return;
+}
+
+static void
+pdf_doc_close_page_tree (pdf_doc *p)
+{
+ pdf_obj *page_tree_root;
+ pdf_obj *mediabox;
+ long page_no;
+
+ /*
+ * Do consistency check on forward references to pages.
+ */
+ for (page_no = PAGECOUNT(p) + 1; page_no <= MAXPAGES(p); page_no++) {
+ pdf_page *page;
+
+ page = doc_get_page_entry(p, page_no);
+ if (page->page_obj) {
+ WARN("Nonexistent page #%ld refered.", page_no);
+ pdf_release_obj(page->page_ref);
+ page->page_ref = NULL;
+ }
+ if (page->page_obj) {
+ WARN("Entry for a nonexistent page #%ld created.", page_no);
+ pdf_release_obj(page->page_obj);
+ page->page_obj = NULL;
+ }
+ if (page->annots) {
+ WARN("Annotation attached to a nonexistent page #%ld.", page_no);
+ pdf_release_obj(page->annots);
+ page->annots = NULL;
+ }
+ if (page->beads) {
+ WARN("Article beads attached to a nonexistent page #%ld.", page_no);
+ pdf_release_obj(page->beads);
+ page->beads = NULL;
+ }
+ if (page->resources) {
+ pdf_release_obj(page->resources);
+ page->resources = NULL;
+ }
+ }
+
+ /*
+ * Connect page tree to root node.
+ */
+ page_tree_root = build_page_tree(p, FIRSTPAGE(p), PAGECOUNT(p), NULL);
+ pdf_merge_dict (p->root.pages, page_tree_root);
+ pdf_release_obj(page_tree_root);
+
+ /* They must be after build_page_tree() */
+ if (p->pages.bop) {
+ pdf_add_stream (p->pages.bop, "\n", 1);
+ pdf_release_obj(p->pages.bop);
+ p->pages.bop = NULL;
+ }
+ if (p->pages.eop) {
+ pdf_add_stream (p->pages.eop, "\n", 1);
+ pdf_release_obj(p->pages.eop);
+ p->pages.eop = NULL;
+ }
+
+ /* Create media box at root node and let the other pages inherit it. */
+ mediabox = pdf_new_array();
+ pdf_add_array(mediabox, pdf_new_number(ROUND(p->pages.mediabox.llx, 0.01)));
+ pdf_add_array(mediabox, pdf_new_number(ROUND(p->pages.mediabox.lly, 0.01)));
+ pdf_add_array(mediabox, pdf_new_number(ROUND(p->pages.mediabox.urx, 0.01)));
+ pdf_add_array(mediabox, pdf_new_number(ROUND(p->pages.mediabox.ury, 0.01)));
+ pdf_add_dict(p->root.pages, pdf_new_name("MediaBox"), mediabox);
+
+ pdf_add_dict(p->root.dict,
+ pdf_new_name("Pages"),
+ pdf_ref_obj (p->root.pages));
+ pdf_release_obj(p->root.pages);
+ p->root.pages = NULL;
+
+ RELEASE(p->pages.entries);
+ p->pages.entries = NULL;
+ p->pages.num_entries = 0;
+ p->pages.max_entries = 0;
+
+ return;
+}
+
+
+#ifndef BOOKMARKS_OPEN_DEFAULT
+#define BOOKMARKS_OPEN_DEFAULT 0
+#endif
+
+static int clean_bookmarks (pdf_olitem *item);
+static int flush_bookmarks (pdf_olitem *item,
+ pdf_obj *parent_ref,
+ pdf_obj *parent_dict);
+
+static void
+pdf_doc_init_bookmarks (pdf_doc *p, int bm_open_depth)
+{
+ pdf_olitem *item;
+
+#define MAX_OUTLINE_DEPTH 256u
+ p->opt.outline_open_depth =
+ ((bm_open_depth >= 0) ?
+ bm_open_depth : MAX_OUTLINE_DEPTH - bm_open_depth);
+
+ p->outlines.current_depth = 1;
+
+ item = NEW(1, pdf_olitem);
+ item->dict = NULL;
+ item->next = NULL;
+ item->first = NULL;
+ item->parent = NULL;
+ item->is_open = 1;
+
+ p->outlines.current = item;
+ p->outlines.first = item;
+
+ return;
+}
+
+static int
+clean_bookmarks (pdf_olitem *item)
+{
+ pdf_olitem *next;
+
+ while (item) {
+ next = item->next;
+ if (item->dict)
+ pdf_release_obj(item->dict);
+ if (item->first)
+ clean_bookmarks(item->first);
+ RELEASE(item);
+
+ item = next;
+ }
+
+ return 0;
+}
+
+static int
+flush_bookmarks (pdf_olitem *node,
+ pdf_obj *parent_ref, pdf_obj *parent_dict)
+{
+ int retval;
+ int count;
+ pdf_olitem *item;
+ pdf_obj *this_ref, *prev_ref, *next_ref;
+
+ ASSERT(node->dict);
+
+ this_ref = pdf_ref_obj(node->dict);
+ pdf_add_dict(parent_dict,
+ pdf_new_name("First"), pdf_link_obj(this_ref));
+
+ retval = 0;
+ for (item = node, prev_ref = NULL;
+ item && item->dict; item = item->next) {
+ if (item->first && item->first->dict) {
+ count = flush_bookmarks(item->first, this_ref, item->dict);
+ if (item->is_open) {
+ pdf_add_dict(item->dict,
+ pdf_new_name("Count"),
+ pdf_new_number(count));
+ retval += count;
+ } else {
+ pdf_add_dict(item->dict,
+ pdf_new_name("Count"),
+ pdf_new_number(-count));
+ }
+ }
+ pdf_add_dict(item->dict,
+ pdf_new_name("Parent"),
+ pdf_link_obj(parent_ref));
+ if (prev_ref) {
+ pdf_add_dict(item->dict,
+ pdf_new_name("Prev"),
+ prev_ref);
+ }
+ if (item->next && item->next->dict) {
+ next_ref = pdf_ref_obj(item->next->dict);
+ pdf_add_dict(item->dict,
+ pdf_new_name("Next"),
+ pdf_link_obj(next_ref));
+ } else {
+ next_ref = NULL;
+ }
+
+ pdf_release_obj(item->dict);
+ item->dict = NULL;
+
+ prev_ref = this_ref;
+ this_ref = next_ref;
+ retval++;
+ }
+
+ pdf_add_dict(parent_dict,
+ pdf_new_name("Last"),
+ pdf_link_obj(prev_ref));
+
+ pdf_release_obj(prev_ref);
+ pdf_release_obj(node->dict);
+ node->dict = NULL;
+
+ return retval;
+}
+
+int
+pdf_doc_bookmarks_up (void)
+{
+ pdf_doc *p = &pdoc;
+ pdf_olitem *parent, *item;
+
+ item = p->outlines.current;
+ if (!item || !item->parent) {
+ WARN("Can't go up above the bookmark root node!");
+ return -1;
+ }
+ parent = item->parent;
+ item = parent->next;
+ if (!parent->next) {
+ parent->next = item = NEW(1, pdf_olitem);
+ item->dict = NULL;
+ item->first = NULL;
+ item->next = NULL;
+ item->is_open = 0;
+ item->parent = parent->parent;
+ }
+ p->outlines.current = item;
+ p->outlines.current_depth--;
+
+ return 0;
+}
+
+int
+pdf_doc_bookmarks_down (void)
+{
+ pdf_doc *p = &pdoc;
+ pdf_olitem *item, *first;
+
+ item = p->outlines.current;
+ if (!item->dict) {
+ pdf_obj *tcolor, *action;
+
+ WARN("Empty bookmark node!");
+ WARN("You have tried to jump more than 1 level.");
+
+ item->dict = pdf_new_dict();
+
+#define TITLE_STRING "<No Title>"
+ pdf_add_dict(item->dict,
+ pdf_new_name("Title"),
+ pdf_new_string(TITLE_STRING, strlen(TITLE_STRING)));
+
+ tcolor = pdf_new_array();
+ pdf_add_array(tcolor, pdf_new_number(1.0));
+ pdf_add_array(tcolor, pdf_new_number(0.0));
+ pdf_add_array(tcolor, pdf_new_number(0.0));
+ pdf_add_dict (item->dict,
+ pdf_new_name("C"), pdf_link_obj(tcolor));
+ pdf_release_obj(tcolor);
+
+ pdf_add_dict (item->dict,
+ pdf_new_name("F"), pdf_new_number(1.0));
+
+#define JS_CODE "app.alert(\"The author of this document made this bookmark item empty!\", 3, 0)"
+ action = pdf_new_dict();
+ pdf_add_dict(action,
+ pdf_new_name("S"), pdf_new_name("JavaScript"));
+ pdf_add_dict(action,
+ pdf_new_name("JS"), pdf_new_string(JS_CODE, strlen(JS_CODE)));
+ pdf_add_dict(item->dict,
+ pdf_new_name("A"), pdf_link_obj(action));
+ pdf_release_obj(action);
+ }
+
+ item->first = first = NEW(1, pdf_olitem);
+ first->dict = NULL;
+ first->is_open = 0;
+ first->parent = item;
+ first->next = NULL;
+ first->first = NULL;
+
+ p->outlines.current = first;
+ p->outlines.current_depth++;
+
+ return 0;
+}
+
+int
+pdf_doc_bookmarks_depth (void)
+{
+ pdf_doc *p = &pdoc;
+
+ return p->outlines.current_depth;
+}
+
+void
+pdf_doc_bookmarks_add (pdf_obj *dict, int is_open)
+{
+ pdf_doc *p = &pdoc;
+ pdf_olitem *item, *next;
+
+ ASSERT(p && dict);
+
+ item = p->outlines.current;
+
+ if (!item) {
+ item = NEW(1, pdf_olitem);
+ item->parent = NULL;
+ p->outlines.first = item;
+ } else if (item->dict) { /* go to next item */
+ item = item->next;
+ }
+
+#define BMOPEN(b,p) (((b) < 0) ? (((p)->outlines.current_depth > (p)->opt.outline_open_depth) ? 0 : 1) : (b))
+
+#if 0
+ item->dict = pdf_link_obj(dict);
+#endif
+ item->dict = dict;
+ item->first = NULL;
+ item->is_open = BMOPEN(is_open, p);
+
+ item->next = next = NEW(1, pdf_olitem);
+ next->dict = NULL;
+ next->parent = item->parent;
+ next->first = NULL;
+ next->is_open = -1;
+ next->next = NULL;
+
+ p->outlines.current = item;
+
+ return;
+}
+
+static void
+pdf_doc_close_bookmarks (pdf_doc *p)
+{
+ pdf_obj *catalog = p->root.dict;
+ pdf_olitem *item;
+ int count;
+ pdf_obj *bm_root, *bm_root_ref;
+
+ item = p->outlines.first;
+ if (item->dict) {
+ bm_root = pdf_new_dict();
+ bm_root_ref = pdf_ref_obj(bm_root);
+ count = flush_bookmarks(item, bm_root_ref, bm_root);
+ pdf_add_dict(bm_root,
+ pdf_new_name("Count"),
+ pdf_new_number(count));
+ pdf_add_dict(catalog,
+ pdf_new_name("Outlines"),
+ bm_root_ref);
+ pdf_release_obj(bm_root);
+ }
+ clean_bookmarks(item);
+
+ p->outlines.first = NULL;
+ p->outlines.current = NULL;
+ p->outlines.current_depth = 0;
+
+ return;
+}
+
+
+static const char *name_dict_categories[] = {
+ "Dests", "AP", "JavaScript", "Pages",
+ "Templates", "IDS", "URLS", "EmbeddedFiles",
+ "AlternatePresentations", "Renditions"
+};
+#define NUM_NAME_CATEGORY (sizeof(name_dict_categories)/sizeof(name_dict_categories[0]))
+
+static void
+pdf_doc_init_names (pdf_doc *p)
+{
+ int i;
+
+ p->root.names = NULL;
+
+ p->names = NEW(NUM_NAME_CATEGORY + 1, struct name_dict);
+ for (i = 0; i < NUM_NAME_CATEGORY; i++) {
+ p->names[i].category = name_dict_categories[i];
+ p->names[i].data = NULL;
+ }
+ p->names[NUM_NAME_CATEGORY].category = NULL;
+ p->names[NUM_NAME_CATEGORY].data = NULL;
+
+ return;
+}
+
+int
+pdf_doc_add_names (const char *category,
+ const void *key, int keylen, pdf_obj *value)
+{
+ pdf_doc *p = &pdoc;
+ int i;
+
+ for (i = 0; p->names[i].category != NULL; i++) {
+ if (!strcmp(p->names[i].category, category)) {
+ break;
+ }
+ }
+ if (p->names[i].category == NULL) {
+ WARN("Unknown name dictionary category \"%s\".", category);
+ return -1;
+ }
+ if (!p->names[i].data) {
+ p->names[i].data = pdf_new_name_tree();
+ }
+
+ return pdf_names_add_object(p->names[i].data, key, keylen, value);
+}
+
+static void
+pdf_doc_close_names (pdf_doc *p)
+{
+ pdf_obj *tmp;
+ int i;
+
+ for (i = 0; p->names[i].category != NULL; i++) {
+ if (p->names[i].data) {
+ pdf_obj *name_tree;
+
+ name_tree = pdf_names_create_tree(p->names[i].data);
+ if (!p->root.names) {
+ p->root.names = pdf_new_dict();
+ }
+ pdf_add_dict(p->root.names,
+ pdf_new_name(p->names[i].category), pdf_ref_obj(name_tree));
+ pdf_release_obj(name_tree);
+ pdf_delete_name_tree(&p->names[i].data);
+ }
+ }
+
+ if (p->root.names) {
+ tmp = pdf_lookup_dict(p->root.dict, "Names");
+ if (!tmp) {
+ pdf_add_dict(p->root.dict,
+ pdf_new_name("Names"),
+ pdf_ref_obj (p->root.names));
+ } else if (PDF_OBJ_DICTTYPE(tmp)) {
+ pdf_merge_dict(p->root.names, tmp);
+ pdf_add_dict(p->root.dict,
+ pdf_new_name("Names"),
+ pdf_ref_obj (p->root.names));
+ } else { /* Maybe reference */
+ /* What should I do? */
+ WARN("Could not modify Names dictionary.");
+ }
+ pdf_release_obj(p->root.names);
+ p->root.names = NULL;
+ }
+
+ RELEASE(p->names);
+ p->names = NULL;
+
+ return;
+}
+
+
+void
+pdf_doc_add_annot (unsigned page_no, const pdf_rect *rect, pdf_obj *annot_dict)
+{
+ pdf_doc *p = &pdoc;
+ pdf_page *page;
+ pdf_obj *rect_array;
+ double annot_grow = p->opt.annot_grow;
+
+ page = doc_get_page_entry(p, page_no);
+ if (!page->annots)
+ page->annots = pdf_new_array();
+
+#if 1
+ {
+ pdf_rect mediabox;
+
+ pdf_doc_get_mediabox(page_no, &mediabox);
+ if (rect->llx < mediabox.llx ||
+ rect->urx > mediabox.urx ||
+ rect->lly < mediabox.lly ||
+ rect->ury > mediabox.ury) {
+ WARN("Annotation out of page boundary.");
+ WARN("Current page's MediaBox: [%g %g %g %g]",
+ mediabox.llx, mediabox.lly, mediabox.urx, mediabox.ury);
+ WARN("Annotation: [%g %g %g %g]",
+ rect->llx, rect->lly, rect->urx, rect->ury);
+ WARN("Maybe incorrect paper size specified.");
+ }
+ if (rect->llx > rect->urx || rect->lly > rect->ury) {
+ WARN("Rectangle with negative width/height: [%g %g %g %g]",
+ rect->llx, rect->lly, rect->urx, rect->ury);
+ }
+ }
+#endif
+
+ rect_array = pdf_new_array();
+ pdf_add_array(rect_array, pdf_new_number(ROUND(rect->llx - annot_grow, 0.001)));
+ pdf_add_array(rect_array, pdf_new_number(ROUND(rect->lly - annot_grow, 0.001)));
+ pdf_add_array(rect_array, pdf_new_number(ROUND(rect->urx + annot_grow, 0.001)));
+ pdf_add_array(rect_array, pdf_new_number(ROUND(rect->ury + annot_grow, 0.001)));
+ pdf_add_dict (annot_dict, pdf_new_name("Rect"), rect_array);
+
+ pdf_add_array(page->annots, pdf_ref_obj(annot_dict));
+
+ return;
+}
+
+
+/*
+ * PDF Article Thread
+ */
+static void
+pdf_doc_init_articles (pdf_doc *p)
+{
+ p->root.threads = NULL;
+
+ p->articles.num_entries = 0;
+ p->articles.max_entries = 0;
+ p->articles.entries = NULL;
+
+ return;
+}
+
+void
+pdf_doc_begin_article (const char *article_id, pdf_obj *article_info)
+{
+ pdf_doc *p = &pdoc;
+ pdf_article *article;
+
+ if (article_id == NULL || strlen(article_id) == 0)
+ ERROR("Article thread without internal identifier.");
+
+ if (p->articles.num_entries >= p->articles.max_entries) {
+ p->articles.max_entries += PDFDOC_ARTICLE_ALLOC_SIZE;
+ p->articles.entries = RENEW(p->articles.entries,
+ p->articles.max_entries, struct pdf_article);
+ }
+ article = &(p->articles.entries[p->articles.num_entries]);
+
+ article->id = NEW(strlen(article_id)+1, char);
+ strcpy(article->id, article_id);
+ article->info = article_info;
+ article->num_beads = 0;
+ article->max_beads = 0;
+ article->beads = NULL;
+
+ p->articles.num_entries++;
+
+ return;
+}
+
+#if 0
+void
+pdf_doc_end_article (const char *article_id)
+{
+ return; /* no-op */
+}
+#endif
+
+static pdf_bead *
+find_bead (pdf_article *article, const char *bead_id)
+{
+ pdf_bead *bead;
+ long i;
+
+ bead = NULL;
+ for (i = 0; i < article->num_beads; i++) {
+ if (!strcmp(article->beads[i].id, bead_id)) {
+ bead = &(article->beads[i]);
+ break;
+ }
+ }
+
+ return bead;
+}
+
+void
+pdf_doc_add_bead (const char *article_id,
+ const char *bead_id, long page_no, const pdf_rect *rect)
+{
+ pdf_doc *p = &pdoc;
+ pdf_article *article;
+ pdf_bead *bead;
+ long i;
+
+ if (!article_id) {
+ ERROR("No article identifier specified.");
+ }
+
+ article = NULL;
+ for (i = 0; i < p->articles.num_entries; i++) {
+ if (!strcmp(p->articles.entries[i].id, article_id)) {
+ article = &(p->articles.entries[i]);
+ break;
+ }
+ }
+ if (!article) {
+ ERROR("Specified article thread that doesn't exist.");
+ return;
+ }
+
+ bead = bead_id ? find_bead(article, bead_id) : NULL;
+ if (!bead) {
+ if (article->num_beads >= article->max_beads) {
+ article->max_beads += PDFDOC_BEAD_ALLOC_SIZE;
+ article->beads = RENEW(article->beads,
+ article->max_beads, struct pdf_bead);
+ for (i = article->num_beads; i < article->max_beads; i++) {
+ article->beads[i].id = NULL;
+ article->beads[i].page_no = -1;
+ }
+ }
+ bead = &(article->beads[article->num_beads]);
+ if (bead_id) {
+ bead->id = NEW(strlen(bead_id)+1, char);
+ strcpy(bead->id, bead_id);
+ } else {
+ bead->id = NULL;
+ }
+ article->num_beads++;
+ }
+ bead->rect.llx = rect->llx;
+ bead->rect.lly = rect->lly;
+ bead->rect.urx = rect->urx;
+ bead->rect.ury = rect->ury;
+ bead->page_no = page_no;
+
+ return;
+}
+
+static pdf_obj *
+make_article (pdf_doc *p,
+ pdf_article *article,
+ const char **bead_ids, int num_beads,
+ pdf_obj *article_info)
+{
+ pdf_obj *art_dict;
+ pdf_obj *first, *prev, *last;
+ long i, n;
+
+ if (!article)
+ return NULL;
+
+ art_dict = pdf_new_dict();
+ first = prev = last = NULL;
+ /*
+ * The bead_ids represents logical order of beads in an article thread.
+ * If bead_ids is not given, we create an article thread in the order of
+ * beads appeared.
+ */
+ n = bead_ids ? num_beads : article->num_beads;
+ for (i = 0; i < n; i++) {
+ pdf_bead *bead;
+
+ bead = bead_ids ? find_bead(article, bead_ids[i]) : &(article->beads[i]);
+ if (!bead || bead->page_no < 0) {
+ continue;
+ }
+ last = pdf_new_dict();
+ if (prev == NULL) {
+ first = last;
+ pdf_add_dict(first,
+ pdf_new_name("T"), pdf_ref_obj(art_dict));
+ } else {
+ pdf_add_dict(prev,
+ pdf_new_name("N"), pdf_ref_obj(last));
+ pdf_add_dict(last,
+ pdf_new_name("V"), pdf_ref_obj(prev));
+ /* We must link first to last. */
+ if (prev != first)
+ pdf_release_obj(prev);
+ }
+
+ /* Realize bead now. */
+ {
+ pdf_page *page;
+ pdf_obj *rect;
+
+ page = doc_get_page_entry(p, bead->page_no);
+ if (!page->beads) {
+ page->beads = pdf_new_array();
+ }
+ pdf_add_dict(last, pdf_new_name("P"), pdf_link_obj(page->page_ref));
+ rect = pdf_new_array();
+ pdf_add_array(rect, pdf_new_number(ROUND(bead->rect.llx, 0.01)));
+ pdf_add_array(rect, pdf_new_number(ROUND(bead->rect.lly, 0.01)));
+ pdf_add_array(rect, pdf_new_number(ROUND(bead->rect.urx, 0.01)));
+ pdf_add_array(rect, pdf_new_number(ROUND(bead->rect.ury, 0.01)));
+ pdf_add_dict (last, pdf_new_name("R"), rect);
+ pdf_add_array(page->beads, pdf_ref_obj(last));
+ }
+
+ prev = last;
+ }
+
+ if (first && last) {
+ pdf_add_dict(last,
+ pdf_new_name("N"), pdf_ref_obj(first));
+ pdf_add_dict(first,
+ pdf_new_name("V"), pdf_ref_obj(last));
+ if (first != last) {
+ pdf_release_obj(last);
+ }
+ pdf_add_dict(art_dict,
+ pdf_new_name("F"), pdf_ref_obj(first));
+ /* If article_info is supplied, we override article->info. */
+ if (article_info) {
+ pdf_add_dict(art_dict,
+ pdf_new_name("I"), article_info);
+ } else if (article->info) {
+ pdf_add_dict(art_dict,
+ pdf_new_name("I"), pdf_ref_obj(article->info));
+ pdf_release_obj(article->info);
+ article->info = NULL; /* We do not write as object reference. */
+ }
+ pdf_release_obj(first);
+ } else {
+ pdf_release_obj(art_dict);
+ art_dict = NULL;
+ }
+
+ return art_dict;
+}
+
+static void
+clean_article (pdf_article *article)
+{
+ if (!article)
+ return;
+
+ if (article->beads) {
+ long i;
+
+ for (i = 0; i < article->num_beads; i++) {
+ if (article->beads[i].id)
+ RELEASE(article->beads[i].id);
+ }
+ RELEASE(article->beads);
+ article->beads = NULL;
+ }
+
+ if (article->id)
+ RELEASE(article->id);
+ article->id = NULL;
+ article->num_beads = 0;
+ article->max_beads = 0;
+
+ return;
+}
+
+static void
+pdf_doc_close_articles (pdf_doc *p)
+{
+ int i;
+
+ for (i = 0; i < p->articles.num_entries; i++) {
+ pdf_article *article;
+
+ article = &(p->articles.entries[i]);
+ if (article->beads) {
+ pdf_obj *art_dict;
+
+ art_dict = make_article(p, article, NULL, 0, NULL);
+ if (!p->root.threads) {
+ p->root.threads = pdf_new_array();
+ }
+ pdf_add_array(p->root.threads, pdf_ref_obj(art_dict));
+ pdf_release_obj(art_dict);
+ }
+ clean_article(article);
+ }
+ RELEASE(p->articles.entries);
+ p->articles.entries = NULL;
+ p->articles.num_entries = 0;
+ p->articles.max_entries = 0;
+
+ if (p->root.threads) {
+ pdf_add_dict(p->root.dict,
+ pdf_new_name("Threads"),
+ pdf_ref_obj (p->root.threads));
+ pdf_release_obj(p->root.threads);
+ p->root.threads = NULL;
+ }
+
+ return;
+}
+
+/* page_no = 0 for root page tree node. */
+void
+pdf_doc_set_mediabox (unsigned page_no, const pdf_rect *mediabox)
+{
+ pdf_doc *p = &pdoc;
+ pdf_page *page;
+
+ if (page_no == 0) {
+ p->pages.mediabox.llx = mediabox->llx;
+ p->pages.mediabox.lly = mediabox->lly;
+ p->pages.mediabox.urx = mediabox->urx;
+ p->pages.mediabox.ury = mediabox->ury;
+ } else {
+ page = doc_get_page_entry(p, page_no);
+ page->cropbox.llx = mediabox->llx;
+ page->cropbox.lly = mediabox->lly;
+ page->cropbox.urx = mediabox->urx;
+ page->cropbox.ury = mediabox->ury;
+ page->flags |= USE_MY_MEDIABOX;
+ }
+
+ return;
+}
+
+void
+pdf_doc_get_mediabox (unsigned page_no, pdf_rect *mediabox)
+{
+ pdf_doc *p = &pdoc;
+ pdf_page *page;
+
+ if (page_no == 0) {
+ mediabox->llx = p->pages.mediabox.llx;
+ mediabox->lly = p->pages.mediabox.lly;
+ mediabox->urx = p->pages.mediabox.urx;
+ mediabox->ury = p->pages.mediabox.ury;
+ } else {
+ page = doc_get_page_entry(p, page_no);
+ if (page->flags & USE_MY_MEDIABOX) {
+ mediabox->llx = page->cropbox.llx;
+ mediabox->lly = page->cropbox.lly;
+ mediabox->urx = page->cropbox.urx;
+ mediabox->ury = page->cropbox.ury;
+ } else {
+ mediabox->llx = p->pages.mediabox.llx;
+ mediabox->lly = p->pages.mediabox.lly;
+ mediabox->urx = p->pages.mediabox.urx;
+ mediabox->ury = p->pages.mediabox.ury;
+ }
+ }
+
+ return;
+}
+
+pdf_obj *
+pdf_doc_current_page_resources (void)
+{
+ pdf_obj *resources;
+ pdf_doc *p = &pdoc;
+ pdf_page *currentpage;
+
+ if (p->pending_forms) {
+ if (p->pending_forms->form.resources) {
+ resources = p->pending_forms->form.resources;
+ } else {
+ resources = p->pending_forms->form.resources = pdf_new_dict();
+ }
+ } else {
+ currentpage = LASTPAGE(p);
+ if (currentpage->resources) {
+ resources = currentpage->resources;
+ } else {
+ resources = currentpage->resources = pdf_new_dict();
+ }
+ }
+
+ return resources;
+}
+
+pdf_obj *
+pdf_doc_get_dictionary (const char *category)
+{
+ pdf_doc *p = &pdoc;
+ pdf_obj *dict = NULL;
+
+ ASSERT(category);
+
+ if (!strcmp(category, "Names")) {
+ if (!p->root.names)
+ p->root.names = pdf_new_dict();
+ dict = p->root.names;
+ } else if (!strcmp(category, "Pages")) {
+ if (!p->root.pages)
+ p->root.pages = pdf_new_dict();
+ dict = p->root.pages;
+ } else if (!strcmp(category, "Catalog")) {
+ if (!p->root.dict)
+ p->root.dict = pdf_new_dict();
+ dict = p->root.dict;
+ } else if (!strcmp(category, "Info")) {
+ if (!p->info)
+ p->info = pdf_new_dict();
+ dict = p->info;
+ } else if (!strcmp(category, "@THISPAGE")) {
+ /* Sorry for this... */
+ pdf_page *currentpage;
+
+ currentpage = LASTPAGE(p);
+ dict = currentpage->page_obj;
+ }
+
+ if (!dict) {
+ ERROR("Document dict. \"%s\" not exist. ", category);
+ }
+
+ return dict;
+}
+
+long
+pdf_doc_current_page_number (void)
+{
+ pdf_doc *p = &pdoc;
+
+ return (long) (PAGECOUNT(p) + 1);
+}
+
+pdf_obj *
+pdf_doc_ref_page (unsigned long page_no)
+{
+ pdf_doc *p = &pdoc;
+ pdf_page *page;
+
+ page = doc_get_page_entry(p, page_no);
+ if (!page->page_obj) {
+ page->page_obj = pdf_new_dict();
+ page->page_ref = pdf_ref_obj(page->page_obj);
+ }
+
+ return pdf_link_obj(page->page_ref);
+}
+
+pdf_obj *
+pdf_doc_get_reference (const char *category)
+{
+ pdf_obj *ref = NULL;
+ long page_no;
+
+ ASSERT(category);
+
+ page_no = pdf_doc_current_page_number();
+ if (!strcmp(category, "@THISPAGE")) {
+ ref = pdf_doc_ref_page(page_no);
+ } else if (!strcmp(category, "@PREVPAGE")) {
+ if (page_no <= 1) {
+ ERROR("Reference to previous page, but no pages have been completed yet.");
+ }
+ ref = pdf_doc_ref_page(page_no - 1);
+ } else if (!strcmp(category, "@NEXTPAGE")) {
+ ref = pdf_doc_ref_page(page_no + 1);
+ }
+
+ if (!ref) {
+ ERROR("Reference to \"%s\" not exist. ", category);
+ }
+
+ return ref;
+}
+
+static void
+pdf_doc_new_page (pdf_doc *p)
+{
+ pdf_page *currentpage;
+
+ if (PAGECOUNT(p) >= MAXPAGES(p)) {
+ doc_resize_page_entries(p, MAXPAGES(p) + PDFDOC_PAGES_ALLOC_SIZE);
+ }
+
+ /*
+ * This is confusing. pdf_doc_finish_page() have increased page count!
+ */
+ currentpage = LASTPAGE(p);
+ /* Was this page already instantiated by a forward reference to it? */
+ if (!currentpage->page_ref) {
+ currentpage->page_obj = pdf_new_dict();
+ currentpage->page_ref = pdf_ref_obj(currentpage->page_obj);
+ }
+
+ currentpage->background = NULL;
+ currentpage->contents = pdf_new_stream(STREAM_COMPRESS);
+ currentpage->resources = pdf_new_dict();
+
+ currentpage->annots = NULL;
+ currentpage->beads = NULL;
+
+ return;
+}
+
+/* This only closes contents and resources. */
+static void
+pdf_doc_finish_page (pdf_doc *p)
+{
+ pdf_page *currentpage;
+
+ if (p->pending_forms) {
+ ERROR("A pending form XObject at the end of page.");
+ }
+
+ currentpage = LASTPAGE(p);
+ if (!currentpage->page_obj)
+ currentpage->page_obj = pdf_new_dict();
+
+ /*
+ * Make Contents array.
+ */
+
+ /*
+ * Global BOP content stream.
+ * pdf_ref_obj() returns reference itself when the object is
+ * indirect reference, not reference to the indirect reference.
+ * We keep bop itself but not reference to it since it is
+ * expected to be small.
+ */
+ if (p->pages.bop &&
+ pdf_stream_length(p->pages.bop) > 0) {
+ currentpage->content_refs[0] = pdf_ref_obj(p->pages.bop);
+ } else {
+ currentpage->content_refs[0] = NULL;
+ }
+ /*
+ * Current page background content stream.
+ */
+ if (currentpage->background) {
+ if (pdf_stream_length(currentpage->background) > 0) {
+ currentpage->content_refs[1] = pdf_ref_obj(currentpage->background);
+ pdf_add_stream (currentpage->background, "\n", 1);
+ }
+ pdf_release_obj(currentpage->background);
+ currentpage->background = NULL;
+ } else {
+ currentpage->content_refs[1] = NULL;
+ }
+
+ /* Content body of current page */
+ currentpage->content_refs[2] = pdf_ref_obj(currentpage->contents);
+ pdf_add_stream (currentpage->contents, "\n", 1);
+ pdf_release_obj(currentpage->contents);
+ currentpage->contents = NULL;
+
+ /*
+ * Global EOP content stream.
+ */
+ if (p->pages.eop &&
+ pdf_stream_length(p->pages.eop) > 0) {
+ currentpage->content_refs[3] = pdf_ref_obj(p->pages.eop);
+ } else {
+ currentpage->content_refs[3] = NULL;
+ }
+
+ /*
+ * Page resources.
+ */
+ if (currentpage->resources) {
+ pdf_obj *procset;
+ /*
+ * ProcSet is obsolete in PDF-1.4 but recommended for compatibility.
+ */
+
+ procset = pdf_new_array ();
+ pdf_add_array(procset, pdf_new_name("PDF"));
+ pdf_add_array(procset, pdf_new_name("Text"));
+ pdf_add_array(procset, pdf_new_name("ImageC"));
+ pdf_add_array(procset, pdf_new_name("ImageB"));
+ pdf_add_array(procset, pdf_new_name("ImageI"));
+ pdf_add_dict(currentpage->resources, pdf_new_name("ProcSet"), procset);
+
+ pdf_add_dict(currentpage->page_obj,
+ pdf_new_name("Resources"),
+ pdf_ref_obj(currentpage->resources));
+ pdf_release_obj(currentpage->resources);
+ currentpage->resources = NULL;
+ }
+
+ if (manual_thumb_enabled) {
+ char *thumb_filename;
+ pdf_obj *thumb_ref;
+
+ thumb_filename = NEW(strlen(thumb_basename)+7, char);
+ sprintf(thumb_filename, "%s.%ld",
+ thumb_basename, (p->pages.num_entries % 99999) + 1L);
+ thumb_ref = read_thumbnail(thumb_filename);
+ RELEASE(thumb_filename);
+ if (thumb_ref)
+ pdf_add_dict(currentpage->page_obj, pdf_new_name("Thumb"), thumb_ref);
+ }
+
+ p->pages.num_entries++;
+
+ return;
+}
+
+
+static pdf_color bgcolor = { 1, { 1.0 } };
+void
+pdf_doc_set_bgcolor (const pdf_color *color)
+{
+ if (color)
+ memcpy(&bgcolor, color, sizeof(pdf_color));
+ else { /* as clear... */
+ pdf_color_graycolor(&bgcolor, 1.0);
+ }
+}
+
+static void
+doc_fill_page_background (pdf_doc *p)
+{
+ pdf_page *currentpage;
+ pdf_rect r;
+ int cm;
+ pdf_obj *saved_content;
+
+ cm = pdf_dev_get_param(PDF_DEV_PARAM_COLORMODE);
+ if (!cm || pdf_color_is_white(&bgcolor)) {
+ return;
+ }
+
+ pdf_doc_get_mediabox(pdf_doc_current_page_number(), &r);
+
+ currentpage = LASTPAGE(p);
+ ASSERT(currentpage);
+
+ if (!currentpage->background)
+ currentpage->background = pdf_new_stream(STREAM_COMPRESS);
+
+ saved_content = currentpage->contents;
+ currentpage->contents = currentpage->background;
+
+ pdf_dev_gsave();
+ //pdf_color_push();
+ pdf_dev_set_nonstrokingcolor(&bgcolor);
+ pdf_dev_rectfill(r.llx, r.lly, r.urx - r.llx, r.ury - r.lly);
+ //pdf_color_pop();
+ pdf_dev_grestore();
+
+ currentpage->contents = saved_content;
+
+ return;
+}
+
+void
+pdf_doc_begin_page (double scale, double x_origin, double y_origin)
+{
+ pdf_doc *p = &pdoc;
+ pdf_tmatrix M;
+
+ M.a = scale; M.b = 0.0;
+ M.c = 0.0 ; M.d = scale;
+ M.e = x_origin;
+ M.f = y_origin;
+
+ /* pdf_doc_new_page() allocates page content stream. */
+ pdf_doc_new_page(p);
+ pdf_dev_bop(&M);
+
+ return;
+}
+
+void
+pdf_doc_end_page (void)
+{
+ pdf_doc *p = &pdoc;
+
+ pdf_dev_eop();
+ doc_fill_page_background(p);
+
+ pdf_doc_finish_page(p);
+
+ return;
+}
+
+void
+pdf_doc_add_page_content (const char *buffer, unsigned length)
+{
+ pdf_doc *p = &pdoc;
+ pdf_page *currentpage;
+
+ if (p->pending_forms) {
+ pdf_add_stream(p->pending_forms->form.contents, buffer, length);
+ } else {
+ currentpage = LASTPAGE(p);
+ pdf_add_stream(currentpage->contents, buffer, length);
+ }
+
+ return;
+}
+
+static char *doccreator = NULL; /* Ugh */
+
+void
+pdf_open_document (const char *filename,
+ int do_encryption,
+ double media_width, double media_height,
+ double annot_grow_amount, int bookmark_open_depth)
+{
+ pdf_doc *p = &pdoc;
+
+ pdf_out_init(filename, do_encryption);
+
+ pdf_doc_init_catalog(p);
+
+ p->opt.annot_grow = annot_grow_amount;
+ p->opt.outline_open_depth = bookmark_open_depth;
+
+ pdf_init_resources();
+ pdf_init_colors();
+ pdf_init_fonts();
+ /* Thumbnail want this to be initialized... */
+ pdf_init_images();
+
+ pdf_doc_init_docinfo(p);
+ if (doccreator) {
+ pdf_add_dict(p->info,
+ pdf_new_name("Creator"),
+ pdf_new_string(doccreator, strlen(doccreator)));
+ RELEASE(doccreator); doccreator = NULL;
+ }
+
+ pdf_doc_init_bookmarks(p, bookmark_open_depth);
+ pdf_doc_init_articles (p);
+ pdf_doc_init_names (p);
+ pdf_doc_init_page_tree(p, media_width, media_height);
+
+ if (do_encryption) {
+ pdf_obj *encrypt = pdf_encrypt_obj();
+ pdf_set_encrypt(encrypt, pdf_enc_id_array());
+ pdf_release_obj(encrypt);
+ }
+
+ /* Create a default name for thumbnail image files */
+ if (manual_thumb_enabled) {
+ if (strlen(filename) > 4 &&
+ !strncmp(".pdf", filename + strlen(filename) - 4, 4)) {
+ thumb_basename = NEW(strlen(filename)-4+1, char);
+ strncpy(thumb_basename, filename, strlen(filename)-4);
+ thumb_basename[strlen(filename)-4] = 0;
+ } else {
+ thumb_basename = NEW(strlen(filename)+1, char);
+ strcpy(thumb_basename, filename);
+ }
+ }
+
+ p->pending_forms = NULL;
+
+ return;
+}
+
+void
+pdf_doc_set_creator (const char *creator)
+{
+ if (!creator ||
+ creator[0] == '\0')
+ return;
+
+ doccreator = NEW(strlen(creator)+1, char);
+ strcpy(doccreator, creator); /* Ugh */
+}
+
+
+void
+pdf_close_document (void)
+{
+ pdf_doc *p = &pdoc;
+
+ /*
+ * Following things were kept around so user can add dictionary items.
+ */
+ pdf_doc_close_articles (p);
+ pdf_doc_close_names (p);
+ pdf_doc_close_bookmarks(p);
+ pdf_doc_close_page_tree(p);
+ pdf_doc_close_docinfo (p);
+
+ pdf_doc_close_catalog (p);
+
+ pdf_close_images();
+ pdf_close_fonts ();
+ pdf_close_colors();
+
+ pdf_close_resources(); /* Should be at last. */
+
+ pdf_out_flush();
+
+ if (thumb_basename)
+ RELEASE(thumb_basename);
+
+ return;
+}
+
+/*
+ * All this routine does is give the form a name and add a unity scaling matrix.
+ * It fills in required fields. The caller must initialize the stream.
+ */
+static void
+pdf_doc_make_xform (pdf_obj *xform,
+ pdf_rect *bbox,
+ pdf_tmatrix *matrix,
+ pdf_obj *resources,
+ pdf_obj *attrib)
+{
+ pdf_obj *xform_dict;
+ pdf_obj *tmp;
+
+ xform_dict = pdf_stream_dict(xform);
+ pdf_add_dict(xform_dict,
+ pdf_new_name("Type"), pdf_new_name("XObject"));
+ pdf_add_dict(xform_dict,
+ pdf_new_name("Subtype"), pdf_new_name("Form"));
+ pdf_add_dict(xform_dict,
+ pdf_new_name("FormType"), pdf_new_number(1.0));
+
+ if (!bbox)
+ ERROR("No BoundingBox supplied.");
+
+ tmp = pdf_new_array();
+ pdf_add_array(tmp, pdf_new_number(ROUND(bbox->llx, .001)));
+ pdf_add_array(tmp, pdf_new_number(ROUND(bbox->lly, .001)));
+ pdf_add_array(tmp, pdf_new_number(ROUND(bbox->urx, .001)));
+ pdf_add_array(tmp, pdf_new_number(ROUND(bbox->ury, .001)));
+ pdf_add_dict(xform_dict, pdf_new_name("BBox"), tmp);
+
+ if (matrix) {
+ tmp = pdf_new_array();
+ pdf_add_array(tmp, pdf_new_number(ROUND(matrix->a, .00001)));
+ pdf_add_array(tmp, pdf_new_number(ROUND(matrix->b, .00001)));
+ pdf_add_array(tmp, pdf_new_number(ROUND(matrix->c, .00001)));
+ pdf_add_array(tmp, pdf_new_number(ROUND(matrix->d, .00001)));
+ pdf_add_array(tmp, pdf_new_number(ROUND(matrix->e, .001 )));
+ pdf_add_array(tmp, pdf_new_number(ROUND(matrix->f, .001 )));
+ pdf_add_dict(xform_dict, pdf_new_name("Matrix"), tmp);
+ }
+
+ if (attrib) {
+ pdf_merge_dict(xform_dict, attrib);
+ }
+
+ pdf_add_dict(xform_dict, pdf_new_name("Resources"), resources);
+
+ return;
+}
+
+/*
+ * begin_form_xobj creates an xobject with its "origin" at
+ * xpos and ypos that is clipped to the specified bbox. Note
+ * that the origin is not the lower left corner of the bbox.
+ */
+int
+pdf_doc_begin_grabbing (const char *ident,
+ double ref_x, double ref_y, const pdf_rect *cropbox)
+{
+ int xobj_id = -1;
+ pdf_doc *p = &pdoc;
+ pdf_form *form;
+ struct form_list_node *fnode;
+ xform_info info;
+
+ fnode = NEW(1, struct form_list_node);
+
+ fnode->prev = p->pending_forms;
+ fnode->q_depth = pdf_dev_current_depth();
+ form = &fnode->form;
+
+ /*
+ * The reference point of an Xobject is at the lower left corner
+ * of the bounding box. Since we would like to have an arbitrary
+ * reference point, we use a transformation matrix, translating
+ * the reference point to (0,0).
+ */
+
+ form->matrix.a = 1.0; form->matrix.b = 0.0;
+ form->matrix.c = 0.0; form->matrix.d = 1.0;
+ form->matrix.e = -ref_x;
+ form->matrix.f = -ref_y;
+
+ form->cropbox.llx = ref_x + cropbox->llx;
+ form->cropbox.lly = ref_y + cropbox->lly;
+ form->cropbox.urx = ref_x + cropbox->urx;
+ form->cropbox.ury = ref_y + cropbox->ury;
+
+ form->contents = pdf_new_stream(STREAM_COMPRESS);
+ form->resources = pdf_new_dict();
+
+ pdf_ximage_init_form_info(&info);
+
+ info.matrix.a = 1.0; info.matrix.b = 0.0;
+ info.matrix.c = 0.0; info.matrix.d = 1.0;
+ info.matrix.e = -ref_x;
+ info.matrix.f = -ref_y;
+
+ info.bbox.llx = cropbox->llx;
+ info.bbox.lly = cropbox->lly;
+ info.bbox.urx = cropbox->urx;
+ info.bbox.ury = cropbox->ury;
+
+ /* Use reference since content itself isn't available yet. */
+ xobj_id = pdf_ximage_defineresource(ident,
+ PDF_XOBJECT_TYPE_FORM,
+ &info, pdf_ref_obj(form->contents));
+
+ p->pending_forms = fnode;
+
+ /*
+ * Make sure the object is self-contained by adding the
+ * current font and color to the object stream.
+ */
+ pdf_dev_reset_fonts();
+ pdf_dev_reset_color();
+
+ return xobj_id;
+}
+
+void
+pdf_doc_end_grabbing (pdf_obj *attrib)
+{
+ pdf_form *form;
+ pdf_obj *procset;
+ pdf_doc *p = &pdoc;
+ struct form_list_node *fnode;
+
+ if (!p->pending_forms) {
+ WARN("Tried to close a nonexistent form XOject.");
+ return;
+ }
+
+ fnode = p->pending_forms;
+ form = &fnode->form;
+
+ pdf_dev_grestore_to(fnode->q_depth);
+
+ /*
+ * ProcSet is obsolete in PDF-1.4 but recommended for compatibility.
+ */
+ procset = pdf_new_array();
+ pdf_add_array(procset, pdf_new_name("PDF"));
+ pdf_add_array(procset, pdf_new_name("Text"));
+ pdf_add_array(procset, pdf_new_name("ImageC"));
+ pdf_add_array(procset, pdf_new_name("ImageB"));
+ pdf_add_array(procset, pdf_new_name("ImageI"));
+ pdf_add_dict (form->resources, pdf_new_name("ProcSet"), procset);
+
+ pdf_doc_make_xform(form->contents,
+ &form->cropbox, &form->matrix,
+ pdf_ref_obj(form->resources), attrib);
+ pdf_release_obj(form->resources);
+ pdf_release_obj(form->contents);
+ if (attrib) pdf_release_obj(attrib);
+
+ p->pending_forms = fnode->prev;
+
+ /* Here we do not need pdf_dev_reset_color(). */
+ pdf_dev_reset_fonts();
+
+ RELEASE(fnode);
+
+ return;
+}
+
+static struct
+{
+ int dirty;
+ pdf_obj *annot_dict;
+ pdf_rect rect;
+} breaking_state = {0, NULL, {0.0, 0.0, 0.0, 0.0}};
+
+static void
+reset_box (void)
+{
+ breaking_state.rect.llx = 10000.0; /* large value */
+ breaking_state.rect.lly = 10000.0; /* large value */
+ breaking_state.rect.urx = 0.0; /* small value */
+ breaking_state.rect.ury = 0.0; /* small value */
+ breaking_state.dirty = 0;
+}
+
+void
+pdf_doc_begin_annot (pdf_obj *dict)
+{
+ breaking_state.annot_dict = dict;
+ reset_box();
+}
+
+void
+pdf_doc_end_annot (void)
+{
+ pdf_doc_break_annot();
+ breaking_state.annot_dict = NULL;
+}
+
+void
+pdf_doc_break_annot (void)
+{
+ if (breaking_state.dirty) {
+ pdf_obj *annot_dict;
+
+ /* Copy dict */
+ annot_dict = pdf_new_dict();
+ pdf_merge_dict(annot_dict, breaking_state.annot_dict);
+ pdf_doc_add_annot(pdf_doc_current_page_number(),
+ &(breaking_state.rect), annot_dict);
+ pdf_release_obj(annot_dict);
+ }
+ reset_box();
+}
+
+void
+pdf_doc_expand_box (const pdf_rect *rect)
+{
+ breaking_state.rect.llx = MIN(breaking_state.rect.llx, rect->llx);
+ breaking_state.rect.lly = MIN(breaking_state.rect.lly, rect->lly);
+ breaking_state.rect.urx = MAX(breaking_state.rect.urx, rect->urx);
+ breaking_state.rect.ury = MAX(breaking_state.rect.ury, rect->ury);
+ breaking_state.dirty = 1;
+}
+
+#if 0
+/* This should be number tree */
+void
+pdf_doc_set_pagelabel (long pg_start,
+ const char *type,
+ const void *prefix, int prfx_len, long start)
+{
+ pdf_doc *p = &pdoc;
+ pdf_obj *label_dict;
+
+ if (!p->root.pagelabels)
+ p->root.pagelabels = pdf_new_array();
+
+ label_dict = pdf_new_dict();
+ if (!type || type[0] == '\0') /* Set back to default. */
+ pdf_add_dict(label_dict, pdf_new_name("S"), pdf_new_name("D"));
+ else {
+ if (type)
+ pdf_add_dict(label_dict, pdf_new_name("S"), pdf_new_name(type));
+ if (prefix && prfx_len > 0)
+ pdf_add_dict(label_dict,
+ pdf_new_name("P"),
+ pdf_new_string(prefix, prfx_len));
+ if (start != 1)
+ pdf_add_dict(label_dict,
+ pdf_new_name("St"), pdf_new_number(start));
+ }
+
+ pdf_add_array(p->root.pagelabels, pdf_new_number(pg_start));
+ pdf_add_array(p->root.pagelabels, label_dict);
+
+ return;
+}
+#endif
diff --git a/Build/source/texk/dvipdf-x/xsrc/pdfdoc.h b/Build/source/texk/dvipdf-x/xsrc/pdfdoc.h
new file mode 100644
index 00000000000..5e65da405e3
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pdfdoc.h
@@ -0,0 +1,137 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2007-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _PDFDOC_H_
+#define _PDFDOC_H_
+
+#include "pdfobj.h"
+#include "pdfdev.h"
+
+#define PDF_DOC_GRABBING_NEST_MAX 4
+
+extern void pdf_doc_set_verbose (void);
+
+extern void pdf_open_document (const char *filename,
+ int do_encryption,
+ double media_width, double media_height,
+ double annot_grow_amount, int bookmark_open_depth);
+extern void pdf_close_document (void);
+
+
+/* PDF document metadata */
+extern void pdf_doc_set_creator (const char *creator);
+
+
+/* They just return PDF dictionary object.
+ * Callers are completely responsible for doing right thing...
+ */
+extern pdf_obj *pdf_doc_get_dictionary (const char *category);
+extern pdf_obj *pdf_doc_get_reference (const char *category);
+
+#define pdf_doc_page_tree() pdf_doc_get_dictionary("Pages")
+#define pdf_doc_catalog() pdf_doc_get_dictionary("Catalog")
+#define pdf_doc_docinfo() pdf_doc_get_dictionary("Info")
+#define pdf_doc_names() pdf_doc_get_dictionary("Names")
+#define pdf_doc_this_page() pdf_doc_get_dictionary("@THISPAGE")
+
+extern long pdf_doc_current_page_number (void);
+extern pdf_obj *pdf_doc_current_page_resources (void);
+
+extern pdf_obj *pdf_doc_ref_page (unsigned long page_no);
+#define pdf_doc_this_page_ref() pdf_doc_get_reference("@THISPAGE")
+#define pdf_doc_next_page_ref() pdf_doc_get_reference("@NEXTPAGE")
+#define pdf_doc_prev_page_ref() pdf_doc_get_reference("@PREVPAGE")
+
+/* Not really managing tree...
+ * There should be something for number tree.
+ */
+extern int pdf_doc_add_names (const char *category,
+ const void *key, int keylen, pdf_obj *value);
+
+extern void pdf_doc_set_bop_content (const char *str, unsigned length);
+extern void pdf_doc_set_eop_content (const char *str, unsigned length);
+
+/* Page */
+extern void pdf_doc_begin_page (double scale, double x_origin, double y_origin);
+extern void pdf_doc_end_page (void);
+
+extern void pdf_doc_set_mediabox (unsigned page_no, const pdf_rect *mediabox);
+extern void pdf_doc_get_mediabox (unsigned page_no, pdf_rect *mediabox);
+
+extern void pdf_doc_add_page_content (const char *buffer, unsigned length);
+extern void pdf_doc_add_page_resource (const char *category,
+ const char *resource_name, pdf_obj *resources);
+
+/* Article thread */
+extern void pdf_doc_begin_article (const char *article_id, pdf_obj *info);
+#if 0
+extern void pdf_doc_end_article (const char *article_id); /* Do nothing... */
+#endif
+extern void pdf_doc_make_article (const char *article_id,
+ const char **bead_order, int num_beads);
+extern void pdf_doc_add_bead (const char *article_id,
+ const char *bead_id,
+ long page_no, const pdf_rect *rect);
+
+/* Bookmarks */
+extern int pdf_doc_bookmarks_up (void);
+extern int pdf_doc_bookmarks_down (void);
+extern void pdf_doc_bookmarks_add (pdf_obj *dict, int is_open);
+extern int pdf_doc_bookmarks_depth (void);
+
+
+/* Returns xobj_id of started xform. */
+extern int pdf_doc_begin_grabbing (const char *ident,
+ double ref_x, double ref_y,
+ const pdf_rect *cropbox);
+extern void pdf_doc_end_grabbing (pdf_obj *attrib);
+
+
+/* Annotation */
+extern void pdf_doc_add_annot (unsigned page_no,
+ const pdf_rect *rect, pdf_obj *annot_dict);
+
+/* Annotation with auto- clip and line (or page) break */
+extern void pdf_doc_begin_annot (pdf_obj *dict);
+extern void pdf_doc_end_annot (void);
+
+extern void pdf_doc_break_annot (void);
+extern void pdf_doc_expand_box (const pdf_rect *rect);
+
+/* Manual thumbnail */
+extern void pdf_doc_enable_manual_thumbnails (void);
+
+#if 0
+/* PageLabels - */
+extern void pdf_doc_set_pagelabel (long page_start,
+ const char *type,
+ const void *prefix, int pfrx_len,
+ long counter_start);
+#endif
+
+/* Similar to bop_content */
+#include "pdfcolor.h"
+extern void pdf_doc_set_bgcolor (const pdf_color *color);
+
+#endif /* _PDFDOC_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/pdfdraw.c b/Build/source/texk/dvipdf-x/xsrc/pdfdraw.c
new file mode 100644
index 00000000000..9f1f0713fc6
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pdfdraw.c
@@ -0,0 +1,1842 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <math.h>
+
+#include "system.h"
+#include "error.h"
+#include "mem.h"
+#include "mfileio.h"
+#include "dpxutil.h"
+#include "numbers.h"
+
+#include "pdfdoc.h"
+#include "pdfdev.h"
+#include "pdfcolor.h"
+
+#include "pdfdraw.h"
+
+#if 1
+typedef void pdf_dev;
+#endif
+
+
+/*
+ * Numbers are rounding to 0-5 fractional digits
+ * in output routine.
+ */
+#define detM(M) ((M).a * (M).d - (M).b * (M).c)
+#define detP(M) ((M)->a * (M)->d - (M)->b * (M)->c)
+
+
+static /* __inline__ */ int
+inversematrix (pdf_tmatrix *W, const pdf_tmatrix *M)
+{
+ double det;
+
+ det = detP(M);
+ if (fabs(det) < 1.e-8) {
+#if 1
+ WARN("Inverting matrix with zero determinant...");
+#endif
+ return -1; /* result is undefined. */
+ }
+
+ W->a = (M->d) / det; W->b = -(M->b) / det;
+ W->c = -(M->c) / det; W->d = (M->a) / det;
+ W->e = (M->c) * (M->f) - (M->d) * (M->e);
+ W->f = (M->b) * (M->e) - (M->a) * (M->f);
+
+ return 0;
+}
+
+/* pdf_coord as vector */
+#define vecprd(v,w) ((v).x * (w).x + (v).y * (w).y)
+#define vecrot(v,w) ((v).x * (w).y - (v).y * (w).x)
+#define dsign(v) (((v) >= 0.0) ? 1.0 : -1.0)
+/* acos => [0, pi] */
+#define vecang(v,w) ( \
+ dsign(vecrot((v),(w))) * \
+ acos(vecprd((v),(w)) / sqrt(vecprd((v),(v)) * vecprd((w),(w)))) \
+)
+
+static /* __inline__ */ int
+pdf_coord__equal (const pdf_coord *p1, const pdf_coord *p2)
+{
+ if (fabs(p1->x - p2->x) < 1.e-7 &&
+ fabs(p1->y - p2->y) < 1.e-7)
+ return 1;
+ return 0;
+}
+#define COORD_EQUAL(p,q) pdf_coord__equal((p),(q))
+
+#if 0
+static int
+pdf_coord__sort_compar_X (const void *pp1, const void *pp2)
+{
+ pdf_coord *p1 = (pdf_coord *)pp1;
+ pdf_coord *p2 = (pdf_coord *)pp2;
+
+ if (pdf_coord__equal(p1, p2))
+ return 0;
+ else
+ return (int) dsign(p1->x - p2->x);
+
+ return 1;
+}
+
+static int
+pdf_coord__sort_compar_Y (const void *pp1, const void *pp2)
+{
+ pdf_coord *p1 = (pdf_coord *)pp1;
+ pdf_coord *p2 = (pdf_coord *)pp2;
+
+ if (pdf_coord__equal(p1, p2))
+ return 0;
+ else
+ return (int) dsign(p1->y - p2->y);
+
+ return 1;
+}
+#endif
+
+
+static /* __inline__ */ int
+pdf_coord__transform (pdf_coord *p, const pdf_tmatrix *M)
+{
+ double x, y;
+
+ x = p->x; y = p->y;
+ p->x = x * M->a + y * M->c + M->e;
+ p->y = x * M->b + y * M->d + M->f;
+
+ return 0;
+}
+
+#if 0
+static /* __inline__ */ int
+pdf_coord__itransform (pdf_coord *p, const pdf_tmatrix *M)
+{
+ pdf_tmatrix W;
+ double x, y;
+ int error;
+
+ error = inversematrix(&W, M);
+ if (error)
+ return error;
+
+ x = p->x; y = p->y;
+ p->x = x * W.a + y * W.c + W.e;
+ p->y = x * W.b + y * W.d + W.f;
+
+ return 0;
+}
+#endif /* 0 */
+
+static /* __inline__ */ int
+pdf_coord__dtransform (pdf_coord *p, const pdf_tmatrix *M)
+{
+ double x, y;
+
+ x = p->x; y = p->y;
+ p->x = x * M->a + y * M->c;
+ p->y = x * M->b + y * M->d;
+
+ return 0;
+}
+
+static /* __inline__ */ int
+pdf_coord__idtransform (pdf_coord *p, const pdf_tmatrix *M)
+{
+ pdf_tmatrix W;
+ double x, y;
+ int error;
+
+ error = inversematrix(&W, M);
+ if (error)
+ return error;
+
+ x = p->x; y = p->y;
+ p->x = x * W.a + y * W.c;
+ p->y = x * W.b + y * W.d;
+
+ return 0;
+}
+
+
+/* Modify M itself */
+void
+pdf_invertmatrix (pdf_tmatrix *M)
+{
+ pdf_tmatrix W;
+ double det;
+
+ ASSERT(M);
+
+ det = detP(M);
+ if (fabs(det) < 1.e-8) {
+ WARN("Inverting matrix with zero determinant...");
+ W.a = 1.0; W.c = 0.0;
+ W.b = 0.0; W.d = 1.0;
+ W.e = 0.0; W.f = 0.0;
+ } else {
+ W.a = (M->d) / det; W.b = -(M->b) / det;
+ W.c = -(M->c) / det; W.d = (M->a) / det;
+ W.e = (M->c) * (M->f) - (M->d) * (M->e);
+ W.f = (M->b) * (M->e) - (M->a) * (M->f);
+ W.e /= det; W.f /= det;
+ }
+
+ pdf_copymatrix(M, &W);
+
+ return;
+}
+
+
+typedef struct pa_elem_
+{
+ int type;
+ pdf_coord p[3];
+} pa_elem;
+
+/* each subpath delimitted by moveto */
+struct pdf_path_
+{
+ int num_paths;
+ int max_paths;
+ pa_elem *path;
+};
+
+static const struct {
+ char opchr; /* PDF operator char */
+ int n_pts; /* number of *points* */
+ const char *strkey;
+} petypes[] = {
+#define PE_TYPE__INVALID -1
+#define PE_TYPE__MOVETO 0
+ {'m', 1, "moveto" },
+#define PE_TYPE__LINETO 1
+ {'l', 1, "lineto" },
+#define PE_TYPE__CURVETO 2
+ {'c', 3, "curveto" },
+ /* no PS correspondence for v and y */
+#define PE_TYPE__CURVETO_V 3
+ {'v', 2, "vcurveto"}, /* current point replicated */
+#define PE_TYPE__CURVETO_Y 4
+ {'y', 2, "ycurveto"}, /* last point replicated */
+#define PE_TYPE__CLOSEPATH 5
+ {'h', 0, "closepath"},
+#define PE_TYPE__TERMINATE 6
+ {' ', 0, NULL}
+};
+
+#define PE_VALID(p) ((p) && \
+ (p)->type > PE_TYPE__INVALID && (p)->type < PE_TYPE__TERMINATE)
+#define PE_N_PTS(p) (PE_VALID((p)) ? petypes[(p)->type].n_pts : 0)
+#define PE_OPCHR(p) (PE_VALID((p)) ? petypes[(p)->type].opchr : ' ')
+
+#define PA_LENGTH(pa) ((pa)->num_paths)
+
+#define GS_FLAG_CURRENTPOINT_SET (1 << 0)
+
+
+static char fmt_buf[1024]; /* FIXME */
+#define FORMAT_BUFF_PTR(p) fmt_buf
+#define FORMAT_BUFF_LEN(p) 1024
+
+static void
+init_a_path (pdf_path *p)
+{
+ ASSERT(p);
+
+ p->num_paths = 0;
+ p->max_paths = 0;
+ p->path = NULL;
+
+ return;
+}
+
+static void
+pdf_path__clearpath (pdf_path *p)
+{
+ ASSERT(p);
+
+ p->num_paths = 0;
+
+ return;
+}
+
+static int
+pdf_path__growpath (pdf_path *p, int max_pe)
+{
+ if (max_pe < p->max_paths)
+ return 0;
+
+ p->max_paths = MAX(p->max_paths + 8, max_pe);
+ p->path = RENEW(p->path, p->max_paths, pa_elem);
+
+ return 0;
+}
+
+static void
+clear_a_path (pdf_path *p)
+{
+ ASSERT(p);
+
+ if (p->path)
+ RELEASE(p->path);
+ p->path = NULL;
+ p->num_paths = 0;
+ p->max_paths = 0;
+
+ return;
+}
+
+static int
+pdf_path__copypath (pdf_path *p1, const pdf_path *p0)
+{
+ pa_elem *pe0, *pe1;
+ int i;
+
+ pdf_path__growpath(p1, PA_LENGTH(p0));
+ for (i = 0; i < PA_LENGTH(p0); i++) {
+ pe1 = &(p1->path[i]);
+ pe0 = &(p0->path[i]);
+ /* FIXME */
+ pe1->type = pe0->type;
+ pe1->p[0].x = pe0->p[0].x;
+ pe1->p[0].y = pe0->p[0].y;
+ pe1->p[1].x = pe0->p[1].x;
+ pe1->p[1].y = pe0->p[1].y;
+ pe1->p[2].x = pe0->p[2].x;
+ pe1->p[2].y = pe0->p[2].y;
+ }
+ p1->num_paths = PA_LENGTH(p0);
+
+ return 0;
+}
+
+
+/* start new subpath */
+static int
+pdf_path__moveto (pdf_path *pa,
+ pdf_coord *cp,
+ const pdf_coord *p0)
+{
+ pa_elem *pe;
+
+ pdf_path__growpath(pa, PA_LENGTH(pa) + 1);
+ if (PA_LENGTH(pa) > 0) {
+ pe = &pa->path[pa->num_paths-1];
+ if (pe->type == PE_TYPE__MOVETO) {
+ pe->p[0].x = cp->x = p0->x;
+ pe->p[0].y = cp->y = p0->y;
+ return 0;
+ }
+ }
+ pe = &pa->path[pa->num_paths++];
+ pe->type = PE_TYPE__MOVETO;
+ pe->p[0].x = cp->x = p0->x;
+ pe->p[0].y = cp->y = p0->y;
+
+ return 0;
+}
+
+/* Do 'compression' of path while adding new path elements.
+ * Sequantial moveto command will be replaced with a
+ * single moveto. If cp is not equal to the last point in pa,
+ * then moveto is inserted (starting new subpath).
+ * FIXME:
+ * 'moveto' must be used to enforce starting new path.
+ * This affects how 'closepath' is treated.
+ */
+static pa_elem *
+pdf_path__next_pe (pdf_path *pa, const pdf_coord *cp)
+{
+ pa_elem *pe;
+
+ pdf_path__growpath(pa, PA_LENGTH(pa) + 2);
+ if (PA_LENGTH(pa) == 0) {
+ pe = &pa->path[pa->num_paths++];
+ pe->type = PE_TYPE__MOVETO;
+ pe->p[0].x = cp->x;
+ pe->p[0].y = cp->y;
+
+ return &pa->path[pa->num_paths++];
+ }
+
+ pe = &pa->path[pa->num_paths-1];
+ switch (pe->type) {
+ case PE_TYPE__MOVETO:
+ pe->p[0].x = cp->x;
+ pe->p[0].y = cp->y;
+ break;
+ case PE_TYPE__LINETO:
+ if (!COORD_EQUAL(&pe->p[0], cp)) {
+ pe = &pa->path[pa->num_paths++];
+ pe->type = PE_TYPE__MOVETO;
+ pe->p[0].x = cp->x;
+ pe->p[0].y = cp->y;
+ }
+ break;
+ case PE_TYPE__CURVETO:
+ if (!COORD_EQUAL(&pe->p[2], cp)) {
+ pe = &pa->path[pa->num_paths++];
+ pe->type = PE_TYPE__MOVETO;
+ pe->p[0].x = cp->x;
+ pe->p[0].y = cp->y;
+ }
+ break;
+ case PE_TYPE__CURVETO_Y:
+ case PE_TYPE__CURVETO_V:
+ if (!COORD_EQUAL(&pe->p[1], cp)) {
+ pe = &pa->path[pa->num_paths++];
+ pe->type = PE_TYPE__MOVETO;
+ pe->p[0].x = cp->x;
+ pe->p[0].y = cp->y;
+ }
+ break;
+ case PE_TYPE__CLOSEPATH:
+ pe = &pa->path[pa->num_paths++];
+ pe->type = PE_TYPE__MOVETO;
+ pe->p[0].x = cp->x;
+ pe->p[0].y = cp->y;
+ break;
+ }
+
+ return &pa->path[pa->num_paths++];
+}
+
+static int
+pdf_path__transform (pdf_path *pa, const pdf_tmatrix *M)
+{
+ pa_elem *pe;
+ int n = 0, i;
+
+ ASSERT(pa && M);
+
+ for (i = 0; i < PA_LENGTH(pa); i++) {
+ pe = &(pa->path[i]);
+ n = PE_N_PTS(pe);
+ while (n-- > 0)
+ pdf_coord__transform(&(pe->p[n]), M);
+ }
+
+ return 0;
+}
+
+
+/* Path Construction */
+static int
+pdf_path__lineto (pdf_path *pa,
+ pdf_coord *cp,
+ const pdf_coord *p0)
+{
+ pa_elem *pe;
+
+ pe = pdf_path__next_pe(pa, cp);
+ pe->type = PE_TYPE__LINETO;
+ pe->p[0].x = cp->x = p0->x;
+ pe->p[0].y = cp->y = p0->y;
+
+ return 0;
+}
+
+static int
+pdf_path__curveto (pdf_path *pa,
+ pdf_coord *cp,
+ const pdf_coord *p0,
+ const pdf_coord *p1,
+ const pdf_coord *p2
+ )
+{
+ pa_elem *pe;
+
+ pe = pdf_path__next_pe(pa, cp);
+ if (COORD_EQUAL(cp, p0)) {
+ pe->type = PE_TYPE__CURVETO_V;
+ pe->p[0].x = p1->x;
+ pe->p[0].y = p1->y;
+ pe->p[1].x = cp->x = p2->x;
+ pe->p[1].y = cp->y = p2->y;
+ } else if (COORD_EQUAL(p1, p2)) {
+ pe->type = PE_TYPE__CURVETO_Y;
+ pe->p[0].x = p0->x;
+ pe->p[0].y = p0->y;
+ pe->p[1].x = cp->x = p1->x;
+ pe->p[1].y = cp->y = p1->y;
+ } else {
+ pe->type = PE_TYPE__CURVETO;
+ pe->p[0].x = p0->x;
+ pe->p[0].y = p0->y;
+ pe->p[1].x = p1->x;
+ pe->p[1].y = p1->y;
+ pe->p[2].x = cp->x = p2->x;
+ pe->p[2].y = cp->y = p2->y;
+ }
+
+ return 0;
+}
+
+#if 0
+#define QB_TWO_THIRD (2.0/3.0)
+#define QB_ONE_THIRD (1.0/3.0)
+
+static int
+pdf_path__curveto_QB (pdf_path *pa,
+ pdf_coord *cp,
+ const pdf_coord *p0,
+ const pdf_coord *p1
+ )
+{
+ pdf_coord q0, q1;
+
+ q0.x = cp->x + QB_TWO_THIRD * (p0->x - cp->x);
+ q0.y = cp->y + QB_TWO_THIRD * (p0->y - cp->y);
+ q1.x = p0->x + QB_ONE_THIRD * (p1->x - p0->x);
+ q1.y = p0->y + QB_ONE_THIRD * (p1->y - p0->y);
+ /* q2 == p1 */
+
+ return pdf_path__curveto(pa, cp, &q0, &q1, p1);
+}
+#endif
+
+
+/* This isn't specified as cp to somewhere. */
+static int
+pdf_path__elliptarc (pdf_path *pa,
+ pdf_coord *cp,
+ const pdf_coord *ca, /* ellipsis center */
+ double r_x, /* x radius */
+ double r_y, /* y radius */
+ double xar, /* x-axis-rotation (deg!) */
+ double a_0, /* start angle */
+ double a_1, /* stop angle */
+ int a_d /* arc orientation */
+ )
+{
+ double b, b_x, b_y;
+ double d_a, q;
+ pdf_coord p0, p1, p2, p3;
+ pdf_coord e0, e1;
+ pdf_tmatrix T;
+ int n_c; /* number of segments */
+ int i, error = 0;
+
+ if (fabs(r_x) < 1.e-8 ||
+ fabs(r_y) < 1.e-8)
+ return -1;
+
+ if (a_d < 0) {
+ for ( ; a_1 > a_0; a_1 -= 360.0);
+ } else {
+ for ( ; a_1 < a_0; a_0 -= 360.0);
+ }
+
+ d_a = a_1 - a_0;
+ for (n_c = 1; fabs(d_a) > 90.0 * n_c; n_c++);
+ d_a /= n_c;
+ if (fabs(d_a) < 1.e-8)
+ return -1;
+
+ a_0 *= M_PI / 180.0;
+ a_1 *= M_PI / 180.0;
+ d_a *= M_PI / 180.0;
+ xar *= M_PI / 180.0;
+ T.a = cos(xar); T.c = -sin(xar);
+ T.b = -T.c ; T.d = T.a;
+ T.e = 0.0 ; T.f = 0.0;
+
+ /* A parameter that controls cb-curve (off-curve) points */
+ b = 4.0 * (1.0 - cos(.5 * d_a)) / (3.0 * sin(.5 * d_a));
+ b_x = r_x * b;
+ b_y = r_y * b;
+
+ p0.x = r_x * cos(a_0);
+ p0.y = r_y * sin(a_0);
+ pdf_coord__transform(&p0, &T);
+ p0.x += ca->x; p0.y += ca->y;
+ if (PA_LENGTH(pa) == 0) {
+ pdf_path__moveto(pa, cp, &p0);
+ } else if (!COORD_EQUAL(cp, &p0)) {
+ pdf_path__lineto(pa, cp, &p0); /* add line seg */
+ }
+ for (i = 0; !error && i < n_c; i++) {
+ q = a_0 + i * d_a;
+ e0.x = cos(q); e0.y = sin(q);
+ e1.x = cos(q + d_a); e1.y = sin(q + d_a);
+
+ /* Condition for tangent vector requirs
+ * d1 = p1 - p0 = f ( sin a, -cos a)
+ * d2 = p2 - p3 = g ( sin b, -cos b)
+ * and from symmetry
+ * g^2 = f^2
+ */
+ p0.x = r_x * e0.x; /* s.p. */
+ p0.y = r_y * e0.y;
+ p3.x = r_x * e1.x; /* e.p. */
+ p3.y = r_y * e1.y;
+
+ p1.x = -b_x * e0.y;
+ p1.y = b_y * e0.x;
+ p2.x = b_x * e1.y;
+ p2.y = -b_y * e1.x;
+
+ pdf_coord__transform(&p0, &T);
+ pdf_coord__transform(&p1, &T);
+ pdf_coord__transform(&p2, &T);
+ pdf_coord__transform(&p3, &T);
+ p0.x += ca->x; p0.y += ca->y;
+ p3.x += ca->x; p3.y += ca->y;
+ p1.x += p0.x ; p1.y += p0.y ;
+ p2.x += p3.x ; p2.y += p3.y ;
+
+ error = pdf_path__curveto(pa, &p0, &p1, &p2, &p3);
+ cp->x = p3.x; cp->y = p3.y;
+ }
+
+ return error;
+}
+
+static int
+pdf_path__closepath (pdf_path *pa, pdf_coord *cp /* no arg */)
+{
+ pa_elem *pe = NULL;
+ int i;
+
+ /* search for start point of the last subpath */
+ for (i = PA_LENGTH(pa) - 1; i >= 0; i--) {
+ pe = &pa->path[i];
+ if (pe->type == PE_TYPE__MOVETO)
+ break;
+ }
+
+ if (!pe || i < 0)
+ return -1; /* No path or no start point(!) */
+
+ cp->x = pe->p[0].x;
+ cp->y = pe->p[0].y;
+
+ pdf_path__growpath(pa, PA_LENGTH(pa) + 1);
+
+ /* NOTE:
+ * Manually closed path without closepath is not
+ * affected by linejoin. A path with coincidental
+ * starting and ending point is not the same as
+ * 'closed' path.
+ */
+ pe = &pa->path[pa->num_paths++];
+ pe->type = PE_TYPE__CLOSEPATH;
+
+ return 0;
+}
+
+/*
+ * x y width height re
+ *
+ * is equivalent to
+ *
+ * x y m
+ * (x + width) y l
+ * (x + width) (y + height) l
+ * x (y + height) l
+ * h
+ */
+/* Just for quick test */
+static /* __inline__ */ int
+pdf_path__isarect (pdf_path *pa,
+ int f_ir /* fill-rule is ignorable */
+ )
+{
+ pa_elem *pe0, *pe1, *pe2, *pe3, *pe4;
+
+ if (PA_LENGTH(pa) == 5) {
+ pe0 = &(pa->path[0]);
+ pe1 = &(pa->path[1]);
+ pe2 = &(pa->path[2]);
+ pe3 = &(pa->path[3]);
+ pe4 = &(pa->path[4]);
+ if (pe0->type == PE_TYPE__MOVETO &&
+ pe1->type == PE_TYPE__LINETO &&
+ pe2->type == PE_TYPE__LINETO &&
+ pe3->type == PE_TYPE__LINETO &&
+ pe4->type == PE_TYPE__CLOSEPATH) {
+ if (pe1->p[0].y - pe0->p[0].y == 0 &&
+ pe2->p[0].x - pe1->p[0].x == 0 &&
+ pe3->p[0].y - pe2->p[0].y == 0) {
+ if (pe1->p[0].x - pe0->p[0].x
+ == pe2->p[0].x - pe3->p[0].x) {
+ return 1;
+ }
+ /* Winding number is different but ignore it here. */
+ } else if (f_ir &&
+ pe1->p[0].x - pe0->p[0].x == 0 &&
+ pe2->p[0].y - pe1->p[0].y == 0 &&
+ pe3->p[0].x - pe2->p[0].x == 0) {
+ if (pe1->p[0].y - pe0->p[0].y
+ == pe2->p[0].y - pe3->p[0].y) {
+ return 1;
+ }
+ }
+ }
+ }
+
+ return 0;
+}
+
+/* Path Painting */
+/* F is obsoleted */
+#define PT_OP_VALID(c) ( \
+ (c) == 'f' || (c) == 'F' || \
+ (c) == 's' || (c) == 'S' || \
+ (c) == 'b' || (c) == 'B' || \
+ (c) == 'W' || (c) == ' ' \
+)
+
+static /* __inline__ */ int
+INVERTIBLE_MATRIX (const pdf_tmatrix *M)
+{
+ if (fabs(detP(M)) < 1.e-8) {
+ WARN("Transformation matrix not invertible.");
+ WARN("--- M = [%g %g %g %g %g %g]",
+ M->a, M->b, M->c, M->d, M->e, M->f);
+ return -1;
+ }
+ return 0;
+}
+
+/* rectfill, rectstroke, rectclip, recteoclip
+ *
+ * Draw isolated rectangle without actually doing
+ * gsave/grestore operation.
+ *
+ * TODO:
+ * linestyle, fill-opacity, stroke-opacity,....
+ * As this routine draw a single graphics object
+ * each time, there should be options for specifying
+ * various drawing styles, which might inherite
+ * current graphcs state parameter.
+ */
+static int
+pdf_dev__rectshape (pdf_dev *P,
+ const pdf_rect *r,
+ const pdf_tmatrix *M,
+ char opchr
+ )
+{
+ char *buf = FORMAT_BUFF_PTR(P);
+ int len = 0;
+ int isclip = 0;
+ pdf_coord p;
+ double wd, ht;
+
+ ASSERT(r && PT_OP_VALID(opchr));
+
+ isclip = (opchr == 'W' || opchr == ' ') ? 1 : 0;
+
+ /* disallow matrix for clipping.
+ * q ... clip Q does nothing and
+ * n M cm ... clip n alter CTM.
+ */
+ if (M && (isclip ||
+ !INVERTIBLE_MATRIX(M)))
+ return -1;
+
+ graphics_mode();
+
+ buf[len++] = ' ';
+ if (!isclip) {
+ buf[len++] = 'q';
+ if (M) {
+ buf[len++] = ' ';
+ len += pdf_sprint_matrix(buf + len, M);
+ buf[len++] = ' ';
+ buf[len++] = 'c'; buf[len++] = 'm';
+ }
+ buf[len++] = ' ';
+ }
+ buf[len++] = 'n';
+
+ p.x = r->llx; p.y = r->lly;
+ wd = r->urx - r->llx;
+ ht = r->ury - r->lly;
+ buf[len++] = ' ';
+ len += pdf_sprint_coord (buf + len, &p);
+ buf[len++] = ' ';
+ len += pdf_sprint_length(buf + len, wd);
+ buf[len++] = ' ';
+ len += pdf_sprint_length(buf + len, ht);
+ buf[len++] = ' ';
+ buf[len++] = 'r'; buf[len++] = 'e';
+
+ if (opchr != ' ') {
+ buf[len++] = ' ';
+ buf[len++] = opchr;
+
+ buf[len++] = ' ';
+ buf[len++] = isclip ? 'n' : 'Q';
+ }
+
+ pdf_doc_add_page_content(buf, len); len = 0;
+
+ return 0;
+}
+
+static int path_added = 0;
+
+/* FIXME */
+static int
+pdf_dev__flushpath (pdf_dev *P,
+ pdf_path *pa,
+ char opchr,
+ int rule,
+ int ignore_rule)
+{
+ pa_elem *pe, *pe1;
+ char *b = FORMAT_BUFF_PTR(P);
+ long b_len = FORMAT_BUFF_LEN(P);
+ pdf_rect r; /* FIXME */
+ pdf_coord *pt;
+ int n_pts, n_seg;
+ int len = 0;
+ int isclip = 0;
+ int isrect, i, j;
+
+ ASSERT(pa && PT_OP_VALID(opchr));
+
+ isclip = (opchr == 'W') ? 1 : 0;
+
+ if (PA_LENGTH(pa) <= 0 && path_added == 0)
+ return 0;
+
+ path_added = 0;
+ graphics_mode();
+ isrect = pdf_path__isarect(pa, ignore_rule);
+ if (isrect) {
+ pe = &(pa->path[0]);
+ pe1 = &(pa->path[2]);
+
+ r.llx = pe->p[0].x;
+ r.lly = pe->p[0].y;
+ r.urx = pe1->p[0].x - pe->p[0].x; /* width... */
+ r.ury = pe1->p[0].y - pe->p[0].y; /* height... */
+
+ b[len++] = ' ';
+ len += pdf_sprint_rect(b + len, &r);
+ b[len++] = ' ';
+ b[len++] = 'r';
+ b[len++] = 'e';
+ pdf_doc_add_page_content(b, len); len = 0;
+ } else {
+ n_seg = PA_LENGTH(pa);
+ for (i = 0, len = 0, pe = &pa->path[0];
+ i < n_seg; pe++, i++) {
+ n_pts = PE_N_PTS(pe);
+ for (j = 0, pt = &pe->p[0];
+ j < n_pts; j++, pt++) {
+ b[len++] = ' ';
+ len += pdf_sprint_coord(b + len, pt);
+ }
+ b[len++] = ' ';
+ b[len++] = PE_OPCHR(pe);
+ if (len + 128 > b_len) {
+ pdf_doc_add_page_content(b, len); len = 0;
+ }
+ }
+ if (len > 0) {
+ pdf_doc_add_page_content(b, len); len = 0;
+ }
+ }
+
+ b[len++] = ' ';
+ b[len++] = opchr;
+ if (rule == PDF_FILL_RULE_EVENODD)
+ b[len++] = '*';
+ if (isclip) {
+ b[len++] = ' '; b[len++] = 'n';
+ }
+
+ pdf_doc_add_page_content(b, len);
+
+ return 0;
+}
+
+
+/* Graphics State */
+typedef struct pdf_gstate_
+{
+ pdf_coord cp;
+
+ pdf_tmatrix matrix; /* cm, - */
+
+ pdf_color strokecolor;
+ pdf_color fillcolor;
+ /* colorspace here */
+
+ struct {
+ int num_dash;
+ double pattern[PDF_DASH_SIZE_MAX];
+ double offset;
+ } linedash; /* d, D */
+
+ double linewidth; /* w, LW */
+
+ int linecap; /* J, LC */
+ int linejoin; /* j, LJ */
+ double miterlimit; /* M, ML */
+
+ int flatness; /* i, FL, 0 to 100 (0 for use device-default) */
+
+ /* internal */
+ pdf_path path;
+ long flags;
+ /* bookkeeping the origin of the last transform applied */
+ pdf_coord pt_fixee;
+} pdf_gstate;
+
+
+typedef struct m_stack_elem
+{
+ void *data;
+ struct m_stack_elem *prev;
+} m_stack_elem;
+
+typedef struct m_stack
+{
+ int size;
+ m_stack_elem *top;
+ m_stack_elem *bottom;
+} m_stack;
+
+static void
+m_stack_init (m_stack *stack)
+{
+ ASSERT(stack);
+
+ stack->size = 0;
+ stack->top = NULL;
+ stack->bottom = NULL;
+
+ return;
+}
+
+static void
+m_stack_push (m_stack *stack, void *data)
+{
+ m_stack_elem *elem;
+
+ ASSERT(stack);
+
+ elem = NEW(1, m_stack_elem);
+ elem->prev = stack->top;
+ elem->data = data;
+
+ stack->top = elem;
+ if (stack->size == 0)
+ stack->bottom = elem;
+
+ stack->size++;
+
+ return;
+}
+
+static void *
+m_stack_pop (m_stack *stack)
+{
+ m_stack_elem *elem;
+ void *data;
+
+ ASSERT(stack);
+
+ if (stack->size == 0)
+ return NULL;
+
+ data = stack->top->data;
+ elem = stack->top;
+ stack->top = elem->prev;
+ if (stack->size == 1)
+ stack->bottom = NULL;
+ RELEASE(elem);
+
+ stack->size--;
+
+ return data;
+}
+
+static void *
+m_stack_top (m_stack *stack)
+{
+ void *data;
+
+ ASSERT(stack);
+
+ if (stack->size == 0)
+ return NULL;
+
+ data = stack->top->data;
+
+ return data;
+}
+
+#define m_stack_depth(s) ((s)->size)
+
+static m_stack gs_stack;
+
+static void
+init_a_gstate (pdf_gstate *gs)
+{
+ gs->cp.x = 0.0;
+ gs->cp.y = 0.0;
+
+ pdf_setmatrix(&gs->matrix, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
+
+ pdf_color_graycolor(&gs->strokecolor, 0.0);
+ pdf_color_graycolor(&gs->fillcolor, 0.0);
+
+ gs->linedash.num_dash = 0;
+ gs->linedash.offset = 0;
+ gs->linecap = 0;
+ gs->linejoin = 0;
+ gs->linewidth = 1.0;
+ gs->miterlimit = 10.0;
+
+ gs->flatness = 1; /* default to 1 in PDF */
+
+ /* Internal variables */
+ gs->flags = 0;
+ init_a_path(&gs->path);
+ gs->pt_fixee.x = 0;
+ gs->pt_fixee.y = 0;
+
+ return;
+}
+
+static void
+clear_a_gstate (pdf_gstate *gs)
+{
+ clear_a_path(&gs->path);
+ memset(gs, 0, sizeof(pdf_gstate));
+
+ return;
+}
+
+static void
+copy_a_gstate (pdf_gstate *gs1, pdf_gstate *gs2)
+{
+ int i;
+
+ ASSERT(gs1 && gs2);
+
+ gs1->cp.x = gs2->cp.x;
+ gs1->cp.y = gs2->cp.y;
+
+ pdf_copymatrix(&gs1->matrix, &gs2->matrix);
+
+ /* TODO:
+ * Path should be linked list and gsave only
+ * record starting point within path rather than
+ * copying whole path.
+ */
+ pdf_path__copypath(&gs1->path, &gs2->path);
+
+ gs1->linedash.num_dash = gs2->linedash.num_dash;
+ for (i = 0; i < gs2->linedash.num_dash; i++) {
+ gs1->linedash.pattern[i] = gs2->linedash.pattern[i];
+ }
+ gs1->linedash.offset = gs2->linedash.offset;
+
+ gs1->linecap = gs2->linecap;
+ gs1->linejoin = gs2->linejoin;
+ gs1->linewidth = gs2->linewidth;
+ gs1->miterlimit = gs2->miterlimit;
+ gs1->flatness = gs2->flatness;
+
+ pdf_color_copycolor(&gs1->fillcolor , &gs2->fillcolor);
+ pdf_color_copycolor(&gs1->strokecolor, &gs2->strokecolor);
+ gs1->pt_fixee.x = gs2->pt_fixee.x;
+ gs1->pt_fixee.y = gs2->pt_fixee.y;
+
+ return;
+}
+
+void
+pdf_dev_init_gstates (void)
+{
+ pdf_gstate *gs;
+
+ m_stack_init(&gs_stack);
+
+ gs = NEW(1, pdf_gstate);
+ init_a_gstate(gs);
+
+ m_stack_push(&gs_stack, gs); /* Initial state */
+
+ return;
+}
+
+void
+pdf_dev_clear_gstates (void)
+{
+ pdf_gstate *gs;
+
+ if (m_stack_depth(&gs_stack) > 1) /* at least 1 elem. */
+ WARN("GS stack depth is not zero at the end of the document.");
+
+ while ((gs = m_stack_pop(&gs_stack)) != NULL) {
+ clear_a_gstate(gs);
+ RELEASE(gs);
+ }
+ return;
+}
+
+int
+pdf_dev_gsave (void)
+{
+ pdf_gstate *gs0, *gs1;
+ pdf_color *sc, *fc;
+
+ gs0 = m_stack_top(&gs_stack);
+ gs1 = NEW(1, pdf_gstate);
+ init_a_gstate(gs1);
+ copy_a_gstate(gs1, gs0);
+ pdf_color_get_current(&sc, &fc);
+ pdf_color_copycolor(&gs1->strokecolor, sc);
+ pdf_color_copycolor(&gs1->fillcolor, fc);
+ m_stack_push(&gs_stack, gs1);
+
+ pdf_doc_add_page_content(" q", 2);
+
+ return 0;
+}
+
+int
+pdf_dev_grestore (void)
+{
+ pdf_gstate *gs;
+
+ if (m_stack_depth(&gs_stack) <= 1) { /* Initial state at bottom */
+ WARN("Too many grestores.");
+ return -1;
+ }
+
+ gs = m_stack_pop(&gs_stack);
+ clear_a_gstate(gs);
+ RELEASE(gs);
+
+ pdf_doc_add_page_content(" Q", 2);
+
+ pdf_dev_reset_fonts();
+
+ return 0;
+}
+
+
+int
+pdf_dev_push_gstate (void)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs0;
+
+ gs0 = NEW(1, pdf_gstate);
+
+ init_a_gstate(gs0);
+
+ m_stack_push(gss, gs0);
+
+ return 0;
+}
+
+
+int
+pdf_dev_pop_gstate (void)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs;
+
+ if (m_stack_depth(gss) <= 1) { /* Initial state at bottom */
+ WARN("Too many grestores.");
+ return -1;
+ }
+
+ gs = m_stack_pop(gss);
+ clear_a_gstate(gs);
+ RELEASE(gs);
+
+ return 0;
+}
+
+
+int
+pdf_dev_current_depth (void)
+{
+ return (m_stack_depth(&gs_stack) - 1); /* 0 means initial state */
+}
+
+void
+pdf_dev_grestore_to (int depth)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs;
+
+ ASSERT(depth >= 0);
+
+ if (m_stack_depth(gss) > depth + 1) {
+ WARN("Closing pending transformations at end of page/XObject.");
+ }
+
+ while (m_stack_depth(gss) > depth + 1) {
+ pdf_doc_add_page_content(" Q", 2);
+ gs = m_stack_pop(gss);
+ clear_a_gstate(gs);
+ RELEASE(gs);
+ }
+ pdf_dev_reset_fonts();
+
+ return;
+}
+
+int
+pdf_dev_currentpoint (pdf_coord *p)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_coord *cpt = &gs->cp;
+
+ ASSERT(p);
+
+ p->x = cpt->x; p->y = cpt->y;
+
+ return 0;
+}
+
+int
+pdf_dev_currentmatrix (pdf_tmatrix *M)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_tmatrix *CTM = &gs->matrix;
+
+ ASSERT(M);
+
+ pdf_copymatrix(M, CTM);
+
+ return 0;
+}
+
+#if 0
+int
+pdf_dev_currentcolor (pdf_color *color, int is_fill)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_color *fcl = &gs->fillcolor;
+ pdf_color *scl = &gs->strokecolor;
+
+ ASSERT(color);
+
+ pdf_color_copycolor(color, is_fill ? fcl : scl);
+
+ return 0;
+}
+#endif /* 0 */
+
+int
+pdf_dev_concat (const pdf_tmatrix *M)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *cpa = &gs->path;
+ pdf_coord *cpt = &gs->cp;
+ pdf_tmatrix *CTM = &gs->matrix;
+ pdf_tmatrix W;
+ char *buf = FORMAT_BUFF_PTR(NULL);
+ int len = 0;
+
+ ASSERT(M);
+
+ /* Adobe Reader erases page content if there are
+ * non invertible transformation.
+ */
+ if (fabs(detP(M)) < 1.0e-8) {
+ WARN("Transformation matrix not invertible.");
+ WARN("--- M = [%g %g %g %g %g %g]",
+ M->a, M->b, M->c, M->d, M->e, M->f);
+ return -1;
+ }
+
+ if (fabs(M->a - 1.0) > 1.e-8 || fabs(M->b) > 1.e-8
+ || fabs(M->c) > 1.e-8 || fabs(M->d - 1.0) > 1.e-8
+ || fabs(M->e) > 1.e-8 || fabs(M->f) > 1.e-8) {
+ buf[len++] = ' ';
+ len += pdf_sprint_matrix(buf + len, M);
+ buf[len++] = ' ';
+ buf[len++] = 'c';
+ buf[len++] = 'm';
+ pdf_doc_add_page_content(buf, len);
+
+ pdf_concatmatrix(CTM, M);
+ }
+ inversematrix(&W, M);
+
+ pdf_path__transform (cpa, &W);
+ pdf_coord__transform(cpt, &W);
+
+ return 0;
+}
+
+/*
+ * num w LW linewidth (g.t. 0)
+ * int J LC linecap
+ * int j LJ linejoin
+ * num M ML miter limit (g.t. 0)
+ * array num d D line dash
+ * int ri RI renderint intnet
+ * int i FL flatness tolerance (0-100)
+ * name gs -- name: res. name of ExtGState dict.
+ */
+int
+pdf_dev_setmiterlimit (double mlimit)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ int len = 0;
+ char *buf = FORMAT_BUFF_PTR(NULL);
+
+ if (gs->miterlimit != mlimit) {
+ buf[len++] = ' ';
+ len += pdf_sprint_length(buf + len, mlimit);
+ buf[len++] = ' ';
+ buf[len++] = 'M';
+ pdf_doc_add_page_content(buf, len);
+ gs->miterlimit = mlimit;
+ }
+
+ return 0;
+}
+
+int
+pdf_dev_setlinecap (int capstyle)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ int len = 0;
+ char *buf = FORMAT_BUFF_PTR(NULL);
+
+ if (gs->linecap != capstyle) {
+ len = sprintf(buf, " %d J", capstyle);
+ pdf_doc_add_page_content(buf, len);
+ gs->linecap = capstyle;
+ }
+
+ return 0;
+}
+
+int
+pdf_dev_setlinejoin (int joinstyle)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ int len = 0;
+ char *buf = FORMAT_BUFF_PTR(NULL);
+
+ if (gs->linejoin != joinstyle) {
+ len = sprintf(buf, " %d j", joinstyle);
+ pdf_doc_add_page_content(buf, len);
+ gs->linejoin = joinstyle;
+ }
+
+ return 0;
+}
+
+int
+pdf_dev_setlinewidth (double width)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ int len = 0;
+ char *buf = FORMAT_BUFF_PTR(NULL);
+
+ if (gs->linewidth != width) {
+ buf[len++] = ' ';
+ len += pdf_sprint_length(buf + len, width);
+ buf[len++] = ' ';
+ buf[len++] = 'w';
+ pdf_doc_add_page_content(buf, len);
+ gs->linewidth = width;
+ }
+
+ return 0;
+}
+
+int
+pdf_dev_setdash (int count, double *pattern, double offset)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ int len = 0;
+ char *buf = FORMAT_BUFF_PTR(NULL);
+ int i;
+
+ gs->linedash.num_dash = count;
+ gs->linedash.offset = offset;
+ pdf_doc_add_page_content(" [", 2);
+ for (i = 0; i < count; i++) {
+ buf[0] = ' ';
+ len = pdf_sprint_length (buf + 1, pattern[i]);
+ pdf_doc_add_page_content(buf, len + 1);
+ gs->linedash.pattern[i] = pattern[i];
+ }
+ pdf_doc_add_page_content("] ", 2);
+ len = pdf_sprint_length (buf, offset);
+ pdf_doc_add_page_content(buf, len);
+ pdf_doc_add_page_content(" d", 2);
+
+ return 0;
+}
+
+#if 0
+int
+pdf_dev_setflat (int flatness)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ int len = 0;
+ char *buf = FORMAT_BUFF_PTR(NULL);
+
+ if (flatness < 0 || flatness > 100)
+ return -1;
+
+ if (gs->flatness != flatness) {
+ gs->flatness = flatness;
+ len = sprintf(buf, " %d i", flatness);
+ pdf_doc_add_page_content(buf, len);
+ }
+
+ return 0;
+}
+#endif /* 0 */
+
+/* ZSYUEDVEDEOF */
+int
+pdf_dev_clip (void)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *cpa = &gs->path;
+
+ return pdf_dev__flushpath(NULL, cpa, 'W', PDF_FILL_RULE_NONZERO, 0);
+}
+
+int
+pdf_dev_eoclip (void)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *cpa = &gs->path;
+
+ return pdf_dev__flushpath(NULL, cpa, 'W', PDF_FILL_RULE_EVENODD, 0);
+}
+
+int
+pdf_dev_flushpath (char p_op, int fill_rule)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *cpa = &gs->path;
+ int error = 0;
+
+ /* last arg 'ignore_rule' is only for single object
+ * that can be converted to a rect where fill rule
+ * is inessential.
+ */
+ error = pdf_dev__flushpath(NULL, cpa, p_op, fill_rule, 1);
+ pdf_path__clearpath(cpa);
+
+ gs->flags &= ~GS_FLAG_CURRENTPOINT_SET;
+
+ return error;
+}
+
+int
+pdf_dev_newpath (void)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *p = &gs->path;
+
+ if (PA_LENGTH(p) > 0) {
+ pdf_path__clearpath (p);
+ }
+ /* The following is required for "newpath" operator in mpost.c. */
+ pdf_doc_add_page_content(" n", 2);
+
+ return 0;
+}
+
+int
+pdf_dev_moveto (double x, double y)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *cpa = &gs->path;
+ pdf_coord *cpt = &gs->cp;
+ pdf_coord p;
+
+ p.x = x; p.y = y;
+ return pdf_path__moveto(cpa, cpt, &p); /* cpt updated */
+}
+
+int
+pdf_dev_rmoveto (double x, double y)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *cpa = &gs->path;
+ pdf_coord *cpt = &gs->cp;
+ pdf_coord p;
+
+ p.x = cpt->x + x;
+ p.y = cpt->y + y;
+ return pdf_path__moveto(cpa, cpt, &p); /* cpt updated */
+}
+
+int
+pdf_dev_lineto (double x, double y)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *cpa = &gs->path;
+ pdf_coord *cpt = &gs->cp;
+ pdf_coord p0;
+
+ p0.x = x; p0.y = y;
+
+ return pdf_path__lineto(cpa, cpt, &p0);
+}
+
+int
+pdf_dev_rlineto (double x, double y)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *cpa = &gs->path;
+ pdf_coord *cpt = &gs->cp;
+ pdf_coord p0;
+
+ p0.x = x + cpt->x; p0.y = y + cpt->y;
+
+ return pdf_path__lineto(cpa, cpt, &p0);
+}
+
+int
+pdf_dev_curveto (double x0, double y0,
+ double x1, double y1,
+ double x2, double y2)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *cpa = &gs->path;
+ pdf_coord *cpt = &gs->cp;
+ pdf_coord p0, p1, p2;
+
+ p0.x = x0; p0.y = y0;
+ p1.x = x1; p1.y = y1;
+ p2.x = x2; p2.y = y2;
+
+ return pdf_path__curveto(cpa, cpt, &p0, &p1, &p2);
+}
+
+int
+pdf_dev_vcurveto (double x0, double y0,
+ double x1, double y1)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *cpa = &gs->path;
+ pdf_coord *cpt = &gs->cp;
+ pdf_coord p0, p1;
+
+ p0.x = x0; p0.y = y0;
+ p1.x = x1; p1.y = y1;
+
+ return pdf_path__curveto(cpa, cpt, cpt, &p0, &p1);
+}
+
+int
+pdf_dev_ycurveto (double x0, double y0,
+ double x1, double y1)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *cpa = &gs->path;
+ pdf_coord *cpt = &gs->cp;
+ pdf_coord p0, p1;
+
+ p0.x = x0; p0.y = y0;
+ p1.x = x1; p1.y = y1;
+
+ return pdf_path__curveto(cpa, cpt, &p0, &p1, &p1);
+}
+
+int
+pdf_dev_rcurveto (double x0, double y0,
+ double x1, double y1,
+ double x2, double y2)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *cpa = &gs->path;
+ pdf_coord *cpt = &gs->cp;
+ pdf_coord p0, p1, p2;
+
+ p0.x = x0 + cpt->x; p0.y = y0 + cpt->y;
+ p1.x = x1 + cpt->x; p1.y = y1 + cpt->y;
+ p2.x = x2 + cpt->x; p2.y = y2 + cpt->y;
+
+ return pdf_path__curveto(cpa, cpt, &p0, &p1, &p2);
+}
+
+
+int
+pdf_dev_closepath (void)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_coord *cpt = &gs->cp;
+ pdf_path *cpa = &gs->path;
+
+ return pdf_path__closepath(cpa, cpt);
+}
+
+
+void
+pdf_dev_dtransform (pdf_coord *p, const pdf_tmatrix *M)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_tmatrix *CTM = &gs->matrix;
+
+ ASSERT(p);
+
+ pdf_coord__dtransform(p, (M ? M : CTM));
+
+ return;
+}
+
+void
+pdf_dev_idtransform (pdf_coord *p, const pdf_tmatrix *M)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_tmatrix *CTM = &gs->matrix;
+
+ ASSERT(p);
+
+ pdf_coord__idtransform(p, (M ? M : CTM));
+
+ return;
+}
+
+void
+pdf_dev_transform (pdf_coord *p, const pdf_tmatrix *M)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_tmatrix *CTM = &gs->matrix;
+
+ ASSERT(p);
+
+ pdf_coord__transform(p, (M ? M : CTM));
+
+ return;
+}
+
+#if 0
+void
+pdf_dev_itransform (pdf_coord *p, const pdf_tmatrix *M)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_tmatrix *CTM = &gs->matrix;
+
+ ASSERT(p);
+
+ pdf_coord__itransform(p, (M ? M : CTM));
+
+ return;
+}
+#endif /* 0 */
+
+int
+pdf_dev_arc (double c_x , double c_y, double r,
+ double a_0 , double a_1)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *cpa = &gs->path;
+ pdf_coord *cpt = &gs->cp;
+ pdf_coord c;
+
+ c.x = c_x; c.y = c_y;
+
+ return pdf_path__elliptarc(cpa, cpt, &c, r, r, 0.0, a_0, a_1, +1);
+}
+
+/* *negative* arc */
+int
+pdf_dev_arcn (double c_x , double c_y, double r,
+ double a_0 , double a_1)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *cpa = &gs->path;
+ pdf_coord *cpt = &gs->cp;
+ pdf_coord c;
+
+ c.x = c_x; c.y = c_y;
+
+ return pdf_path__elliptarc(cpa, cpt, &c, r, r, 0.0, a_0, a_1, -1);
+}
+
+int
+pdf_dev_arcx (double c_x , double c_y,
+ double r_x , double r_y,
+ double a_0 , double a_1,
+ int a_d ,
+ double xar)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *cpa = &gs->path;
+ pdf_coord *cpt = &gs->cp;
+ pdf_coord c;
+
+ c.x = c_x; c.y = c_y;
+
+ return pdf_path__elliptarc(cpa, cpt, &c, r_x, r_y, xar, a_0, a_1, a_d);
+}
+
+/* Required by Tpic */
+int
+pdf_dev_bspline (double x0, double y0,
+ double x1, double y1, double x2, double y2)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ pdf_path *cpa = &gs->path;
+ pdf_coord *cpt = &gs->cp;
+ pdf_coord p1, p2, p3;
+
+ p1.x = x0 + 2.0 * (x1 - x0) / 3.0;
+ p1.y = y0 + 2.0 * (y1 - y0) / 3.0;
+ p2.x = x1 + (x2 - x1) / 3.0;
+ p2.y = y1 + (y2 - y1) / 3.0;
+ p3.x = x2;
+ p3.y = y2;
+
+ return pdf_path__curveto(cpa, cpt, &p1, &p2, &p3);
+}
+
+#if 0
+int
+pdf_dev_rectstroke (double x, double y,
+ double w, double h,
+ const pdf_tmatrix *M /* optional */
+ )
+{
+ pdf_rect r;
+
+ r.llx = x;
+ r.lly = y;
+ r.urx = x + w;
+ r.ury = y + h;
+
+ return pdf_dev__rectshape(NULL, &r, M, 'S');
+}
+#endif /* 0 */
+
+int
+pdf_dev_rectfill (double x, double y,
+ double w, double h)
+{
+ pdf_rect r;
+
+ r.llx = x;
+ r.lly = y;
+ r.urx = x + w;
+ r.ury = y + h;
+
+ return pdf_dev__rectshape(NULL, &r, NULL, 'f');
+}
+
+int
+pdf_dev_rectclip (double x, double y,
+ double w, double h)
+{
+ pdf_rect r;
+
+ r.llx = x;
+ r.lly = y;
+ r.urx = x + w;
+ r.ury = y + h;
+
+ return pdf_dev__rectshape(NULL, &r, NULL, 'W');
+}
+
+int
+pdf_dev_rectadd (double x, double y,
+ double w, double h)
+{
+ pdf_rect r;
+
+ r.llx = x;
+ r.lly = y;
+ r.urx = x + w;
+ r.ury = y + h;
+ path_added = 1;
+
+ return pdf_dev__rectshape(NULL, &r, NULL, ' ');
+}
+
+void
+pdf_dev_set_fixed_point (double x, double y)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ gs->pt_fixee.x = x;
+ gs->pt_fixee.y = y;
+}
+
+void
+pdf_dev_get_fixed_point (pdf_coord *p)
+{
+ m_stack *gss = &gs_stack;
+ pdf_gstate *gs = m_stack_top(gss);
+ p->x = gs->pt_fixee.x;
+ p->y = gs->pt_fixee.y;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/pdfdraw.h b/Build/source/texk/dvipdf-x/xsrc/pdfdraw.h
new file mode 100644
index 00000000000..f24540ef2bf
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pdfdraw.h
@@ -0,0 +1,172 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _PDF_DRAW_H_
+#define _PDF_DRAW_H_
+
+#include "pdfcolor.h"
+#include "pdfdev.h"
+
+#define PDF_DASH_SIZE_MAX 16
+#define PDF_GSAVE_MAX 256
+
+extern void pdf_dev_init_gstates (void);
+extern void pdf_dev_clear_gstates (void);
+
+#define pdf_copymatrix(m,n) do {\
+ (m)->a = (n)->a; (m)->b = (n)->b;\
+ (m)->c = (n)->c; (m)->d = (n)->d;\
+ (m)->e = (n)->e; (m)->f = (n)->f;\
+} while (0)
+
+#define pdf_setmatrix(m,p,q,r,s,t,u) do {\
+ (m)->a = (p); (m)->b = (q);\
+ (m)->c = (r); (m)->d = (s);\
+ (m)->e = (t); (m)->f = (u);\
+} while (0)
+
+/* m -> n x m */
+#define pdf_concatmatrix(m,n) do {\
+ double _tmp_a, _tmp_b, _tmp_c, _tmp_d; \
+ _tmp_a = (m)->a; _tmp_b = (m)->b; \
+ _tmp_c = (m)->c; _tmp_d = (m)->d; \
+ (m)->a = ((n)->a) * _tmp_a + ((n)->b) * _tmp_c; \
+ (m)->b = ((n)->a) * _tmp_b + ((n)->b) * _tmp_d; \
+ (m)->c = ((n)->c) * _tmp_a + ((n)->d) * _tmp_c; \
+ (m)->d = ((n)->c) * _tmp_b + ((n)->d) * _tmp_d; \
+ (m)->e += ((n)->e) * _tmp_a + ((n)->f) * _tmp_c; \
+ (m)->f += ((n)->e) * _tmp_b + ((n)->f) * _tmp_d; \
+} while (0)
+
+typedef struct pdf_path_ pdf_path;
+
+extern int pdf_dev_currentmatrix (pdf_tmatrix *M);
+extern int pdf_dev_currentpoint (pdf_coord *cp);
+
+extern int pdf_dev_setlinewidth (double width);
+extern int pdf_dev_setmiterlimit (double mlimit);
+extern int pdf_dev_setlinecap (int style);
+extern int pdf_dev_setlinejoin (int style);
+extern int pdf_dev_setdash (int count,
+ double *pattern,
+ double offset);
+#if 0
+extern int pdf_dev_setflat (int flatness);
+#endif /* 0 */
+
+/* Path Construction */
+extern int pdf_dev_moveto (double x , double y);
+extern int pdf_dev_rmoveto (double x , double y);
+extern int pdf_dev_closepath (void);
+
+extern int pdf_dev_lineto (double x0 , double y0);
+extern int pdf_dev_rlineto (double x0 , double y0);
+extern int pdf_dev_curveto (double x0 , double y0,
+ double x1 , double y1,
+ double x2 , double y2);
+extern int pdf_dev_vcurveto (double x0 , double y0,
+ double x1 , double y1);
+extern int pdf_dev_ycurveto (double x0 , double y0,
+ double x1 , double y1);
+extern int pdf_dev_rcurveto (double x0 , double y0,
+ double x1 , double y1,
+ double x2 , double y2);
+extern int pdf_dev_arc (double c_x, double c_y, double r,
+ double a_0, double a_1);
+extern int pdf_dev_arcn (double c_x, double c_y, double r,
+ double a_0, double a_1);
+
+#define PDF_FILL_RULE_NONZERO 0
+#define PDF_FILL_RULE_EVENODD 1
+
+extern int pdf_dev_newpath (void);
+
+/* Path Painting */
+extern int pdf_dev_clip (void);
+extern int pdf_dev_eoclip (void);
+
+#if 0
+extern int pdf_dev_rectstroke (double x, double y,
+ double w, double h,
+ const pdf_tmatrix *M /* optional */
+ );
+#endif /* 0 */
+
+extern int pdf_dev_rectfill (double x, double y, double w, double h);
+extern int pdf_dev_rectclip (double x, double y, double w, double h);
+extern int pdf_dev_rectadd (double x, double y, double w, double h);
+
+extern int pdf_dev_flushpath (char p_op, int fill_rule);
+
+#define pdf_dev_fill() pdf_dev_flushpath('f', PDF_FILL_RULE_NONZERO)
+#define pdf_dev_eofill() pdf_dev_flushpath('f', PDF_FILL_RULE_EVENODD)
+#define pdf_dev_stroke() pdf_dev_flushpath('S', PDF_FILL_RULE_NONZERO)
+#define pdf_dev_fillstroke() pdf_dev_flushpath('B', PDF_FILL_RULE_NONZERO)
+
+extern int pdf_dev_concat (const pdf_tmatrix *M);
+/* NULL pointer of M mean apply current transformation */
+extern void pdf_dev_dtransform (pdf_coord *p, const pdf_tmatrix *M);
+extern void pdf_dev_idtransform (pdf_coord *p, const pdf_tmatrix *M);
+extern void pdf_dev_transform (pdf_coord *p, const pdf_tmatrix *M);
+#if 0
+extern void pdf_dev_itransform (pdf_coord *p, const pdf_tmatrix *M);
+#endif /* 0 */
+
+extern int pdf_dev_gsave (void);
+extern int pdf_dev_grestore (void);
+
+/* Requires from mpost.c because new MetaPost graphics must initialize
+ * the current gstate. */
+extern int pdf_dev_push_gstate (void);
+extern int pdf_dev_pop_gstate (void);
+
+
+/* extension */
+extern int pdf_dev_arcx (double c_x, double c_y,
+ double r_x, double r_y,
+ double a_0, double a_1,
+ int a_d, /* arc direction */
+ double xar /* x-axis-rotation */
+ );
+extern int pdf_dev_bspline (double x0, double y0,
+ double x1, double y1,
+ double x2, double y2);
+
+
+extern void pdf_invertmatrix (pdf_tmatrix *M);
+
+/* The depth here is the depth of q/Q nesting.
+ * We must remember current depth of nesting when starting a page or xform,
+ * and must recover until that depth at the end of page/xform.
+ */
+extern int pdf_dev_current_depth (void);
+extern void pdf_dev_grestore_to (int depth);
+#define pdf_dev_grestoreall() pdf_dev_grestore_to(0);
+
+extern int pdf_dev_currentcolor (pdf_color *color, int is_fill);
+extern int pdf_dev_setcolor (const pdf_color *color, int is_fill);
+
+extern void pdf_dev_set_fixed_point (double x, double y);
+extern void pdf_dev_get_fixed_point (pdf_coord *p);
+#endif /* _PDF_DRAW_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/pdfencrypt.c b/Build/source/texk/dvipdf-x/xsrc/pdfencrypt.c
new file mode 100644
index 00000000000..464f97e2b3d
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pdfencrypt.c
@@ -0,0 +1,539 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#ifdef WIN32
+#include <conio.h>
+#define getch _getch
+#else /* !WIN32 */
+#include <unistd.h>
+#endif /* WIN32 */
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+#include "pdfobj.h"
+#include "dpxcrypt.h"
+
+#include "pdfencrypt.h"
+
+#define MAX_KEY_LEN 16
+#define MAX_STR_LEN 32
+
+static unsigned char algorithm, revision, key_size;
+static unsigned long permission;
+
+static unsigned char key_data[MAX_KEY_LEN], id_string[MAX_KEY_LEN];
+static unsigned char opwd_string[MAX_STR_LEN], upwd_string[MAX_STR_LEN];
+
+static unsigned long current_label = 0;
+static unsigned current_generation = 0;
+
+static ARC4_KEY key;
+static MD5_CONTEXT md5_ctx;
+
+static unsigned char md5_buf[MAX_KEY_LEN], key_buf[MAX_KEY_LEN];
+static unsigned char in_buf[MAX_STR_LEN], out_buf[MAX_STR_LEN];
+
+static const unsigned char padding_string[MAX_STR_LEN] = {
+ 0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41,
+ 0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08,
+ 0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80,
+ 0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a
+};
+
+static char owner_passwd[MAX_PWD_LEN], user_passwd[MAX_PWD_LEN];
+
+static unsigned char verbose = 0;
+
+void pdf_enc_set_verbose (void)
+{
+ if (verbose < 255) verbose++;
+}
+
+#define PRODUCER "%s-%s, Copyright \251 2002-2010 by Jin-Hwan Cho, Matthias Franz, and Shunsaku Hirata"
+void pdf_enc_compute_id_string (char *dviname, char *pdfname)
+{
+ char *date_string, *producer;
+ time_t current_time;
+ struct tm *bd_time;
+
+ MD5_init(&md5_ctx);
+
+ date_string = NEW (15, char);
+ time(&current_time);
+ bd_time = localtime(&current_time);
+ sprintf (date_string, "%04d%02d%02d%02d%02d%02d",
+ bd_time -> tm_year+1900, bd_time -> tm_mon+1, bd_time -> tm_mday,
+ bd_time -> tm_hour, bd_time -> tm_min, bd_time -> tm_sec);
+ MD5_write(&md5_ctx, (unsigned char *)date_string, strlen(date_string));
+ RELEASE (date_string);
+
+ producer = NEW (strlen(PRODUCER)+strlen(PACKAGE)+strlen(VERSION), char);
+ sprintf(producer, PRODUCER, PACKAGE, VERSION);
+ MD5_write(&md5_ctx, (unsigned char *)producer, strlen(producer));
+ RELEASE (producer);
+
+ if (dviname)
+ MD5_write(&md5_ctx, (unsigned char *)dviname, strlen(dviname));
+ if (pdfname)
+ MD5_write(&md5_ctx, (unsigned char *)pdfname, strlen(pdfname));
+ MD5_final(id_string, &md5_ctx);
+}
+
+static void passwd_padding (unsigned char *src, unsigned char *dst)
+{
+ register int len = strlen((char *)src);
+
+ if (len > MAX_STR_LEN)
+ len = MAX_STR_LEN;
+
+ memcpy(dst, src, len);
+ memcpy(dst+len, padding_string, MAX_STR_LEN-len);
+}
+
+static void compute_owner_password (void)
+{
+ register unsigned char i, j;
+ /*
+ * Algorithm 3.3 Computing the encryption dictionary's O (owner password)
+ * value
+ *
+ * 1. Pad or truncate the owner password string as described in step 1
+ * of Algorithm 3.2. If there is no owner password, use the user
+ * password instead. (See implementation note 17 in Appendix H.)
+ */
+ passwd_padding((unsigned char *)(strlen(owner_passwd) > 0 ? owner_passwd : user_passwd), in_buf);
+ /*
+ * 2. Initialize the MD5 hash function and pass the result of step 1
+ * as input to this function.
+ */
+ MD5_init(&md5_ctx);
+ MD5_write(&md5_ctx, in_buf, MAX_STR_LEN);
+ MD5_final(md5_buf, &md5_ctx);
+ /*
+ * 3. (Revision 3 only) Do the following 50 times: Take the output
+ * from the previous MD5 hash and pass it as input into a new
+ * MD5 hash.
+ */
+ if (revision == 3)
+ for (i = 0; i < 50; i++) {
+ /*
+ * NOTE: We truncate each MD5 hash as in the following step.
+ * Otherwise Adobe Reader won't decrypt the PDF file.
+ */
+ MD5_init(&md5_ctx);
+ MD5_write(&md5_ctx, md5_buf, key_size);
+ MD5_final(md5_buf, &md5_ctx);
+ }
+ /*
+ * 4. Create an RC4 encryption key using the first n bytes of the output
+ * from the final MD5 hash, where n is always 5 for revision 2 but
+ * for revision 3 depends on the value of the encryption dictionary's
+ * Length entry.
+ */
+ ARC4_set_key(&key, key_size, md5_buf);
+ /*
+ * 5. Pad or truncate the user password string as described in step 1
+ * of Algorithm 3.2.
+ */
+ passwd_padding((unsigned char *)user_passwd, in_buf);
+ /*
+ * 6. Encrypt the result of step 5, using an RC4 encryption function
+ * with the encryption key obtained in step 4.
+ */
+ ARC4(&key, MAX_STR_LEN, in_buf, out_buf);
+ /*
+ * 7. (Revision 3 only) Do the following 19 times: Take the output
+ * from the previous invocation of the RC4 function and pass it
+ * as input to a new invocation of the function; use an encryption
+ * key generated by taking each byte of the encryption key obtained
+ * in step 4 and performing an XOR (exclusive or) operation between
+ * that byte and the single-byte value of the iteration counter
+ * (from 1 to 19).
+ */
+ if (revision == 3)
+ for (i = 1; i <= 19; i++) {
+ memcpy(in_buf, out_buf, MAX_STR_LEN);
+ for (j = 0; j < key_size; j++)
+ key_buf[j] = md5_buf[j] ^ i;
+ ARC4_set_key(&key, key_size, key_buf);
+ ARC4(&key, MAX_STR_LEN, in_buf, out_buf);
+ }
+ /*
+ * 8. Store the output from the final invocation of the RC4 function
+ * as the value of the O entry in the encryption dictionary.
+ */
+ memcpy(opwd_string, out_buf, MAX_STR_LEN);
+}
+
+static void compute_encryption_key (unsigned char *pwd)
+{
+ register unsigned char i;
+ /*
+ * Algorithm 3.2 Computing an encryption key
+ *
+ * 1. Pad or truncate the password string to exactly 32 bytes. If the
+ * password string is more than 32 bytes long, use only its first
+ * 32 bytes; if it is less than 32 bytes long, pad it by appending
+ * the required number of additional bytes from the beginning of
+ * the following padding string:
+ *
+ * < 28 BF 4E 5E 4E 75 8A 41 64 00 4E 56 FF FA 01 08
+ * 2E 2E 00 B6 D0 68 3E 80 2F 0C A9 FE 64 53 69 7A >
+ *
+ * That is, if the password string is n bytes long, append the
+ * first 32 - n bytes of the padding string to the end of the
+ * password string. If the password string is empty (zero-length),
+ * meaning there is no user password, substitute the entire
+ * padding string in its place.
+ */
+ passwd_padding(pwd, in_buf);
+ /*
+ * 2. Initialize the MD5 hash function and pass the result of step 1
+ * as input to this fuction.
+ */
+ MD5_init(&md5_ctx);
+ MD5_write(&md5_ctx, in_buf, MAX_STR_LEN);
+ /*
+ * 3. Pass the value of the encryption dictionary's O entry to the
+ * MD5 hash function. (Algorithm 3.3 shows how the O value is
+ * computed.)
+ */
+ MD5_write(&md5_ctx, opwd_string, MAX_STR_LEN);
+ /*
+ * 4. Treat the value of the P entry as an unsigned 4-byte integer
+ * and pass these bytes to the MD5 hash function, low-order byte
+ * first.
+ */
+ in_buf[0] = (unsigned char)(permission) & 0xFF;
+ in_buf[1] = (unsigned char)(permission >> 8) & 0xFF;
+ in_buf[2] = (unsigned char)(permission >> 16) & 0xFF;
+ in_buf[3] = (unsigned char)(permission >> 24) & 0xFF;
+ MD5_write(&md5_ctx, in_buf, 4);
+ /*
+ * 5. Pass the first element of the file's file identifier array
+ * (the value of the ID entry in the document's trailer dictionary;
+ * see Table 3.12 on page 68) to the MD5 hash function and
+ * finish the hash.
+ */
+ MD5_write(&md5_ctx, id_string, MAX_KEY_LEN);
+ MD5_final(md5_buf, &md5_ctx);
+ /*
+ * 6. (Revision 3 only) Do the following 50 times; Take the output from
+ * the previous MD5 hash and pass it as input into a new MD5 hash.
+ */
+ if (revision == 3)
+ for (i = 0; i < 50; i++) {
+ /*
+ * NOTE: We truncate each MD5 hash as in the following step.
+ * Otherwise Adobe Reader won't decrypt the PDF file.
+ */
+ MD5_init(&md5_ctx);
+ MD5_write(&md5_ctx, md5_buf, key_size);
+ MD5_final(md5_buf, &md5_ctx);
+ }
+ /*
+ * 7. Set the encryption key to the first n bytes of the output from
+ * the final MD5 hash, where n is always 5 for revision 2 but for
+ * revision 3 depends on the value of the encryption dictionary's
+ * Length entry.
+ */
+ memcpy(key_data, md5_buf, key_size);
+}
+
+static void compute_user_password (void)
+{
+ register unsigned char i, j;
+ /*
+ * Algorithm 3.4 Computing the encryption dictionary's U (user password)
+ * value (Revision 2)
+ *
+ * 1. Create an encryption key based on the user password string, as
+ * described in Algorithm 3.2.
+ *
+ * 2. Encrypt the 32-byte padding string shown in step 1 of Algorithm
+ * 3.2, using an RC4 encryption fuction with the encryption key from
+ * the preceeding step.
+ *
+ * 3. Store the result of step 2 as the value of the U entry in the
+ * encryption dictionary.
+ */
+ /*
+ * Algorithm 3.5 Computing the encryption dictionary's U (user password)
+ * value (Revision 3)
+ *
+ * 1. Create an encryption key based on the user password string, as
+ * described in Algorithm 3.2.
+ *
+ * 2. Initialize the MD5 hash function and pass the 32-byte padding
+ * string shown in step 1 of Algorithm 3.2 as input to this function.
+ *
+ * 3. Pass the first element of the file's file identifier array (the
+ * value of the ID entry in the document's trailer dictionary; see
+ * Table 3.12 on page 68) to the hash function and finish the hash.
+ *
+ * 4. Encrypt the 16-byte result of the hash, using an RC4 encryption
+ * function with the encryption key from step 1.
+ *
+ * 5. Do the following 19 times: Take the output from the previous
+ * invocation of the RC4 function and pass it as input to a new
+ * invocation of the function; use an encryption key generated by
+ * taking each byte of the original encryption key (obtained in
+ * step 1) and performing an XOR (exclusive or) operation between
+ * that byte and the single-byte value of the iteration counter
+ * (from 1 to 19).
+ *
+ * 6. Append 16 bytes of arbitrary padding to the output from the
+ * final invocation of the RC4 function and store the 32-byte
+ * result as the value of the U entry in the encryption dictionary.
+ */
+ compute_encryption_key((unsigned char *)user_passwd);
+
+ switch (revision) {
+ case 2:
+ ARC4_set_key(&key, key_size, key_data);
+ ARC4(&key, MAX_STR_LEN, padding_string, out_buf);
+ break;
+ case 3:
+ MD5_init(&md5_ctx);
+ MD5_write(&md5_ctx, padding_string, MAX_STR_LEN);
+
+ MD5_write(&md5_ctx, id_string, MAX_KEY_LEN);
+ MD5_final(md5_buf, &md5_ctx);
+
+ ARC4_set_key(&key, key_size, key_data);
+ ARC4(&key, MAX_KEY_LEN, md5_buf, out_buf);
+
+ for (i = 1; i <= 19; i++) {
+ memcpy(in_buf, out_buf, MAX_KEY_LEN);
+ for (j = 0; j < key_size; j++)
+ key_buf[j] = key_data[j] ^ i;
+ ARC4_set_key(&key, key_size, key_buf);
+ ARC4(&key, MAX_KEY_LEN, in_buf, out_buf);
+ }
+ break;
+ default:
+ ERROR("Invalid revision number.\n");
+ }
+
+ memcpy(upwd_string, out_buf, MAX_STR_LEN);
+}
+
+#ifdef WIN32
+static char *getpass (const char *prompt)
+{
+ static char pwd_buf[128];
+ size_t i;
+
+ fputs(prompt, stderr);
+ fflush(stderr);
+ for (i = 0; i < sizeof(pwd_buf)-1; i++) {
+ pwd_buf[i] = getch();
+ if (pwd_buf[i] == '\r')
+ break;
+ fputs("*", stderr);
+ fflush(stderr);
+ }
+ pwd_buf[i] = '\0';
+ fputs("\n", stderr);
+ return pwd_buf;
+}
+#endif
+
+void pdf_enc_set_passwd (unsigned bits, unsigned perm, const char *owner_pw, const char *user_pw)
+{
+ char *retry_passwd;
+
+ if (owner_pw) {
+ strncpy(owner_passwd, owner_pw, MAX_PWD_LEN);
+ } else
+ while (1) {
+ strncpy(owner_passwd, getpass("Owner password: "), MAX_PWD_LEN);
+ retry_passwd = getpass("Re-enter owner password: ");
+ if (!strncmp(owner_passwd, retry_passwd, MAX_PWD_LEN))
+ break;
+ fputs("Password is not identical.\nTry again.\n", stderr);
+ fflush(stderr);
+ }
+
+ if (user_pw) {
+ strncpy(user_passwd, user_pw, MAX_PWD_LEN);
+ } else
+ while (1) {
+ strncpy(user_passwd, getpass("User password: "), MAX_PWD_LEN);
+ retry_passwd = getpass("Re-enter user password: ");
+ if (!strncmp(user_passwd, retry_passwd, MAX_PWD_LEN))
+ break;
+ fputs("Password is not identical.\nTry again.\n", stderr);
+ fflush(stderr);
+ }
+
+ key_size = (unsigned char)(bits / 8);
+ algorithm = (key_size == 5 ? 1 : 2);
+ permission = (unsigned long)perm | 0x000000C0;
+ revision = ((algorithm == 1 && permission < 0x100) ? 2 : 3);
+ if (revision == 3)
+ permission |= 0xFFFFF000;
+
+ compute_owner_password();
+ compute_user_password();
+}
+
+void pdf_encrypt_data (unsigned char *data, unsigned long len)
+{
+ unsigned char *result;
+
+ memcpy(in_buf, key_data, key_size);
+ in_buf[key_size] = (unsigned char)(current_label) & 0xFF;
+ in_buf[key_size+1] = (unsigned char)(current_label >> 8) & 0xFF;
+ in_buf[key_size+2] = (unsigned char)(current_label >> 16) & 0xFF;
+ in_buf[key_size+3] = (unsigned char)(current_generation) & 0xFF;
+ in_buf[key_size+4] = (unsigned char)(current_generation >> 8) & 0xFF;
+
+ MD5_init(&md5_ctx);
+ MD5_write(&md5_ctx, in_buf, key_size+5);
+ MD5_final(md5_buf, &md5_ctx);
+
+ result = NEW (len, unsigned char);
+ ARC4_set_key(&key, (key_size > 10 ? MAX_KEY_LEN : key_size+5), md5_buf);
+ ARC4(&key, len, data, result);
+ memcpy(data, result, len);
+ RELEASE (result);
+}
+
+pdf_obj *pdf_encrypt_obj (void)
+{
+ pdf_obj *doc_encrypt;
+
+#ifdef DEBUG
+ fprintf (stderr, "(pdf_encrypt_obj)");
+#endif
+
+ doc_encrypt = pdf_new_dict ();
+
+ /* KEY : Filter
+ * TYPE : name
+ * VALUE: (Required) The name of the security handler for this document;
+ * see below. Default value: Standard, for the built-in security
+ * handler.
+ */
+ pdf_add_dict (doc_encrypt,
+ pdf_new_name ("Filter"),
+ pdf_new_name ("Standard"));
+ /* KEY : V
+ * TYPE : number
+ * VALUE: (Optional but strongly recommended) A code specifying the
+ * algorithm to be used in encrypting and decrypting the document:
+ * 0 An algorithm that is undocumented and no longer supported,
+ * and whose use is strongly discouraged.
+ * 1 Algorithm 3.1 on page 73, with an encryption key length
+ * of 40 bits; see below.
+ * 2 (PDF 1.4) Algorithm 3.1 on page 73, but allowing encryption
+ * key lengths greater than 40 bits.
+ * 3 (PDF 1.4) An unpublished algorithm allowing encryption key
+ * lengths ranging from 40 to 128 bits. (This algorithm is
+ * unpublished as an export requirement of the U.S. Department
+ * of Commerce.)
+ * The default value if this entry is omitted is 0, but a value
+ * of 1 or greater is strongly recommended.
+ */
+ pdf_add_dict (doc_encrypt,
+ pdf_new_name ("V"),
+ pdf_new_number (algorithm));
+ /* KEY : Length
+ * TYPE : integer
+ * VALUE: (Optional; PDF 1.4; only if V is 2 or 3) The length of the
+ * encryption key, in bits. The value must be a multiple of 8,
+ * in the range 40 to 128. Default value: 40.
+ */
+ if (algorithm > 1)
+ pdf_add_dict (doc_encrypt,
+ pdf_new_name ("Length"),
+ pdf_new_number (key_size * 8));
+ /* KEY : R
+ * TYPE : number
+ * VALUE: (Required) A number specifying which revision of the standard
+ * security handler should be used to interpret this dictionary.
+ * The revison number should be 2 if the document is encrypted
+ * with a V value less than 2; otherwise this value should be 3.
+ */
+ pdf_add_dict (doc_encrypt,
+ pdf_new_name ("R"),
+ pdf_new_number (revision));
+ /* KEY : O
+ * TYPE : string
+ * VALUE: (Required) A 32-byte string, based on both the owner and
+ * user passwords, that is used in computing the encryption
+ * key and in determining whether a valid owner password was
+ * entered.
+ */
+ pdf_add_dict (doc_encrypt,
+ pdf_new_name ("O"),
+ pdf_new_string (opwd_string, 32));
+ /* KEY : U
+ * TYPE : string
+ * VALUE: (Required) A 32-byte string, based on the user password,
+ * that is used in determining whether to prompt the user
+ * for a password and, if so, whether a valid user or owner
+ * password was entered.
+ */
+ pdf_add_dict (doc_encrypt,
+ pdf_new_name ("U"),
+ pdf_new_string (upwd_string, 32));
+ /* KEY : P
+ * TYPE : integer
+ * VALUE: (Required) A set of flags specifying which operations are
+ * permitted when the document is opened with user access.
+ */
+ pdf_add_dict (doc_encrypt,
+ pdf_new_name ("P"),
+ pdf_new_number (permission));
+
+ return doc_encrypt;
+}
+
+pdf_obj *pdf_enc_id_array (void)
+{
+ pdf_obj *id = pdf_new_array();
+ pdf_add_array(id, pdf_new_string(id_string, MAX_KEY_LEN));
+ pdf_add_array(id, pdf_new_string(id_string, MAX_KEY_LEN));
+ return id;
+}
+
+void pdf_enc_set_label (unsigned long label)
+{
+ current_label = label;
+}
+
+void pdf_enc_set_generation (unsigned generation)
+{
+ current_generation = generation;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/pdfnames.c b/Build/source/texk/dvipdf-x/xsrc/pdfnames.c
new file mode 100644
index 00000000000..83eb997e249
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pdfnames.c
@@ -0,0 +1,488 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <ctype.h>
+#include <math.h>
+#include <string.h>
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+#include "numbers.h"
+
+/* Hash */
+#include "dpxutil.h"
+
+#include "pdfobj.h"
+
+#include "pdfnames.h"
+
+struct obj_data
+{
+ pdf_obj *object_ref;
+ pdf_obj *object;
+ int reserve; /* 1 if object is not actually defined. */
+};
+
+char *
+printable_key (const char *key, int keylen)
+{
+#define MAX_KEY 32
+ static char pkey[MAX_KEY+4];
+ int i, len;
+ unsigned char hi, lo;
+
+ for (i = 0, len = 0;
+ i < keylen && len < MAX_KEY; i++) {
+ if (isprint(key[i])) {
+ pkey[len++] = key[i];
+ } else {
+ hi = (key[i] >> 4) & 0xff;
+ lo = key[i] & 0xff;
+ pkey[len++] = '#';
+ pkey[len++] = (hi < 10) ? hi + '0' : (hi - 10) + 'A';
+ pkey[len++] = (lo < 10) ? lo + '0' : (lo - 10) + 'A';
+ }
+ }
+ pkey[len] = '\0';
+
+ return (char *) pkey;
+}
+
+static void
+flush_objects (struct ht_table *ht_tab)
+{
+ struct ht_iter iter;
+
+ if (ht_set_iter(ht_tab, &iter) >= 0) {
+ do {
+ char *key;
+ int keylen;
+ struct obj_data *value;
+
+ key = ht_iter_getkey(&iter, &keylen);
+ value = ht_iter_getval(&iter);
+ if (value->reserve) {
+ WARN("Unresolved object reference \"%s\" found!!!",
+ printable_key(key, keylen));
+ }
+ if (value->object) {
+ pdf_release_obj(value->object);
+ }
+ if (value->object_ref) {
+ pdf_release_obj(value->object_ref);
+ }
+ value->object = NULL;
+ value->object_ref = NULL;
+ value->reserve = 0;
+ } while (ht_iter_next(&iter) >= 0);
+ ht_clear_iter(&iter);
+ }
+}
+
+static void CDECL
+hval_free (void *hval)
+{
+ struct obj_data *value;
+
+ value = (struct obj_data *) hval;
+ if (value->object)
+ pdf_release_obj(value->object);
+ if (value->object_ref)
+ pdf_release_obj(value->object_ref);
+
+ value->object = NULL;
+ value->object_ref = NULL;
+ value->reserve = 0;
+
+ RELEASE(value);
+
+ return;
+}
+
+struct ht_table *
+pdf_new_name_tree (void)
+{
+ struct ht_table *names;
+
+ names = NEW(1, struct ht_table);
+ ht_init_table(names, hval_free);
+
+ return names;
+}
+
+void
+pdf_delete_name_tree (struct ht_table **names)
+{
+ ASSERT(names && *names);
+
+ flush_objects (*names);
+ ht_clear_table(*names);
+ RELEASE(*names);
+ *names = NULL;
+}
+
+int
+pdf_names_add_object (struct ht_table *names,
+ const void *key, int keylen, pdf_obj *object)
+{
+ struct obj_data *value;
+
+ ASSERT(names && object);
+
+ if (!key || keylen < 1) {
+ WARN("Null string used for name tree key.");
+ return -1;
+ }
+
+ value = ht_lookup_table(names, key, keylen);
+ if (!value) {
+ value = NEW(1, struct obj_data);
+ value->object = object;
+ value->object_ref = NULL;
+ value->reserve = 0;
+ ht_append_table(names, key, keylen, value);
+ } else {
+ if (value->reserve) {
+ /* null object is used for undefined objects */
+ pdf_copy_object(value->object, object);
+ pdf_release_obj(object); /* PLEASE FIX THIS!!! */
+ } else {
+ if (value->object || value->object_ref) {
+ if (pdf_obj_get_verbose()) {
+ WARN("Object reference with key \"%s\" is in use.", printable_key(key, keylen));
+ }
+ pdf_release_obj(object);
+ return -1;
+ } else {
+ value->object = object;
+ }
+ }
+ value->reserve = 0;
+ }
+
+ return 0;
+}
+
+int
+pdf_names_add_reference (struct ht_table *names,
+ const void *key, int keylen, pdf_obj *object_ref)
+{
+ struct obj_data *value;
+
+ ASSERT(names);
+
+ if (!PDF_OBJ_INDIRECTTYPE(object_ref)) {
+ WARN("Invalid type: @%s is not reference...",
+ printable_key(key, keylen));
+ return -1;
+ }
+
+ value = ht_lookup_table(names, key, keylen);
+ if (!value) {
+ value = NEW(1, struct obj_data);
+ value->object = NULL;
+ value->object_ref = object_ref;
+ value->reserve = 0;
+ ht_append_table(names, key, keylen, value);
+ } else {
+ if (value->object || value->object_ref) {
+ WARN("Object reference \"%s\" is in use.",
+ printable_key(key, keylen));
+ WARN("Please close it before redefining.");
+ return -1;
+ } else {
+ value->object = NULL;
+ value->object_ref = object_ref;
+ }
+ value->reserve = 0;
+ }
+
+ return 0;
+}
+
+/*
+ * The following routine returns copies, not the original object.
+ */
+pdf_obj *
+pdf_names_lookup_reference (struct ht_table *names,
+ const void *key, int keylen)
+{
+ struct obj_data *value;
+
+ ASSERT(names);
+
+ value = ht_lookup_table(names, key, keylen);
+ /* Reserve object label */
+ if (!value) {
+ value = NEW(1, struct obj_data);
+ value->object = pdf_new_null(); /* dummy */
+ value->object_ref = NULL;
+ value->reserve = 1;
+ ht_append_table(names, key, keylen, value);
+ }
+
+ if (!value->object_ref) {
+ if (value->object)
+ value->object_ref = pdf_ref_obj(value->object);
+ else {
+ WARN("Object @%s not defined or already closed.",
+ printable_key(key, keylen));
+ }
+ }
+
+ return pdf_link_obj(value->object_ref);
+}
+
+pdf_obj *
+pdf_names_lookup_object (struct ht_table *names,
+ const void *key, int keylen)
+{
+ struct obj_data *value;
+
+ ASSERT(names);
+
+ value = ht_lookup_table(names, key, keylen);
+ if (!value)
+ return NULL;
+ else if (!value->object) {
+ WARN("Object @%s not defined or already closed.",
+ printable_key(key, keylen));
+ }
+
+ return value->object;
+}
+
+int
+pdf_names_close_object (struct ht_table *names,
+ const void *key, int keylen)
+{
+ struct obj_data *value;
+
+ ASSERT(names);
+
+ value = ht_lookup_table(names, key, keylen);
+ if (!value) {
+ WARN("Tried to release nonexistent reference: %s",
+ printable_key(key, keylen));
+ return -1;
+ }
+
+ if (value->object) {
+ pdf_release_obj(value->object);
+ value->object = NULL;
+ } else {
+ WARN("Trying to close object @%s twice?",
+ printable_key(key, keylen));
+ return -1;
+ }
+
+ return 0;
+}
+
+struct named_object
+{
+ char *key;
+ int keylen;
+ pdf_obj *value;
+};
+
+static int CDECL
+cmp_key (const void *d1, const void *d2)
+{
+ const struct named_object *sd1, *sd2;
+ int keylen, cmp;
+
+ sd1 = (const struct named_object *) d1;
+ sd2 = (const struct named_object *) d2;
+
+ if (!sd1->key)
+ cmp = -1;
+ else if (!sd2->key)
+ cmp = 1;
+ else {
+ keylen = MIN(sd1->keylen, sd2->keylen);
+ cmp = memcmp(sd1->key, sd2->key, keylen);
+ if (!cmp) {
+ cmp = sd1->keylen - sd2->keylen;
+ }
+ }
+
+ return cmp;
+}
+
+#define NAME_CLUSTER 4
+static pdf_obj *
+build_name_tree (struct named_object *first, long num_leaves, int is_root)
+{
+ pdf_obj *result;
+ int i;
+
+ result = pdf_new_dict();
+ /*
+ * According to PDF Refrence, Third Edition (p.101-102), a name tree
+ * always has exactly one root node, which contains a SINGLE entry:
+ * either Kids or Names but not both. If the root node has a Names
+ * entry, it is the only node in the tree. If it has a Kids entry,
+ * then each of the remaining nodes is either an intermediate node,
+ * containing a Limits entry and a Kids entry, or a leaf node,
+ * containing a Limits entry and a Names entry.
+ */
+ if (!is_root) {
+ struct named_object *last;
+ pdf_obj *limits;
+
+ limits = pdf_new_array();
+ last = &first[num_leaves - 1];
+ pdf_add_array(limits, pdf_new_string(first->key, first->keylen));
+ pdf_add_array(limits, pdf_new_string(last->key , last->keylen ));
+ pdf_add_dict (result, pdf_new_name("Limits"), limits);
+ }
+
+ if (num_leaves > 0 &&
+ num_leaves <= 2 * NAME_CLUSTER) {
+ pdf_obj *names;
+
+ /* Create leaf nodes. */
+ names = pdf_new_array();
+ for (i = 0; i < num_leaves; i++) {
+ struct named_object *cur;
+
+ cur = &first[i];
+ pdf_add_array(names, pdf_new_string(cur->key, cur->keylen));
+ switch (PDF_OBJ_TYPEOF(cur->value)) {
+ case PDF_ARRAY:
+ case PDF_DICT:
+ case PDF_STREAM:
+ case PDF_STRING:
+ pdf_add_array(names, pdf_ref_obj(cur->value));
+ break;
+ case PDF_OBJ_INVALID:
+ ERROR("Invalid object...: %s", printable_key(cur->key, cur->keylen));
+ break;
+ default:
+ pdf_add_array(names, pdf_link_obj(cur->value));
+ break;
+ }
+ pdf_release_obj(cur->value);
+ cur->value = NULL;
+ }
+ pdf_add_dict(result, pdf_new_name("Names"), names);
+ } else if (num_leaves > 0) {
+ pdf_obj *kids;
+
+ /* Intermediate node */
+ kids = pdf_new_array();
+ for (i = 0; i < NAME_CLUSTER; i++) {
+ pdf_obj *subtree;
+ long start, end;
+
+ start = (i*num_leaves) / NAME_CLUSTER;
+ end = ((i+1)*num_leaves) / NAME_CLUSTER;
+ subtree = build_name_tree(&first[start], (end - start), 0);
+ pdf_add_array (kids, pdf_ref_obj(subtree));
+ pdf_release_obj(subtree);
+ }
+ pdf_add_dict(result, pdf_new_name("Kids"), kids);
+ }
+
+ return result;
+}
+
+static struct named_object *
+flat_table (struct ht_table *ht_tab, long *num_entries)
+{
+ struct named_object *objects;
+ struct ht_iter iter;
+ long count;
+
+ ASSERT(ht_tab);
+
+ *num_entries = count = ht_tab->count;
+ objects = NEW(count, struct named_object);
+ if (ht_set_iter(ht_tab, &iter) >= 0) {
+ do {
+ char *key;
+ int keylen;
+ struct obj_data *value;
+
+ count--;
+ key = ht_iter_getkey(&iter, &keylen);
+ value = ht_iter_getval(&iter);
+ if (value->reserve) {
+ WARN("Named object \"%s\" not defined!!!",
+ printable_key(key, keylen));
+ WARN("Replacing with null.");
+ objects[count].key = (char *) key;
+ objects[count].keylen = keylen;
+ objects[count].value = pdf_new_null();
+ } else if (value->object_ref) {
+ objects[count].key = (char *) key;
+ objects[count].keylen = keylen;
+ objects[count].value = pdf_link_obj(value->object_ref);
+ } else if (value->object) {
+ objects[count].key = (char *) key;
+ objects[count].keylen = keylen;
+ objects[count].value = pdf_link_obj(value->object);
+ } else {
+ WARN("Named object \"%s\" not defined!!!",
+ printable_key(key, keylen));
+ WARN("Replacing with null.");
+ objects[count].key = (char *) key;
+ objects[count].keylen = keylen;
+ objects[count].value = pdf_new_null();
+ }
+ } while (ht_iter_next(&iter) >= 0 && count > 0);
+ ht_clear_iter(&iter);
+ }
+
+ return objects;
+}
+
+pdf_obj *
+pdf_names_create_tree (struct ht_table *names)
+{
+ pdf_obj *name_tree;
+ struct named_object *flat;
+ long count;
+
+ flat = flat_table(names, &count);
+ if (!flat)
+ name_tree = NULL;
+ else {
+ if (count < 1)
+ name_tree = NULL;
+ else {
+ qsort(flat, count, sizeof(struct named_object), cmp_key);
+ name_tree = build_name_tree(flat, count, 1);
+ }
+ RELEASE(flat);
+ }
+
+ return name_tree;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/pdfnames.h b/Build/source/texk/dvipdf-x/xsrc/pdfnames.h
new file mode 100644
index 00000000000..ca4a7dbc0bf
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pdfnames.h
@@ -0,0 +1,52 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _PDF_NAMES_H_
+#define _PDF_NAMES_H_
+
+/* Hash */
+#include "dpxutil.h"
+#include "pdfobj.h"
+
+/* Not actually tree... */
+extern struct ht_table *pdf_new_name_tree (void);
+extern void pdf_delete_name_tree (struct ht_table **names);
+
+extern int pdf_names_add_object (struct ht_table *names,
+ const void *key, int keylen, pdf_obj *object);
+extern int pdf_names_add_reference (struct ht_table *names,
+ const void *key, int keylen, pdf_obj *object_ref);
+extern pdf_obj *pdf_names_lookup_reference (struct ht_table *names,
+ const void *key, int keylen);
+extern pdf_obj *pdf_names_lookup_object (struct ht_table *names,
+ const void *key, int keylen);
+extern int pdf_names_close_object (struct ht_table *names,
+ const void *key, int keylen);
+
+/* Really create name tree... */
+extern pdf_obj *pdf_names_create_tree (struct ht_table *names);
+
+extern char *printable_key (const char *key, int keylen);
+
+#endif /* _PDF_NAMES_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/pdfobj.c b/Build/source/texk/dvipdf-x/xsrc/pdfobj.c
new file mode 100644
index 00000000000..30a9b6bdb3b
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pdfobj.c
@@ -0,0 +1,3170 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2007-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <ctype.h>
+#include <string.h>
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+#include "mfileio.h"
+#include "dpxutil.h"
+#include "pdflimits.h"
+#include "pdfencrypt.h"
+#include "pdfparse.h"
+
+#ifdef HAVE_ZLIB
+#include <zlib.h>
+#endif /* HAVE_ZLIB */
+
+#include "pdfobj.h"
+#include "pdfdev.h"
+
+#define STREAM_ALLOC_SIZE 4096u
+#define ARRAY_ALLOC_SIZE 256
+#define IND_OBJECTS_ALLOC_SIZE 512
+
+#define OBJ_NO_OBJSTM (1 << 0)
+/* Objects with this flag will not be put into an object stream.
+ For instance, all stream objects have this flag set. */
+#define OBJ_NO_ENCRYPT (1 << 1)
+/* Objects with this flag will not be encrypted.
+ This implies OBJ_NO_OBJSTM if encryption is turned on. */
+
+/* Any of these types can be represented as follows */
+struct pdf_obj
+{
+ int type;
+
+ unsigned long label; /* Only used for indirect objects
+ all other "label" to zero */
+ unsigned short generation; /* Only used if "label" is used */
+ unsigned refcount; /* Number of links to this object */
+ int flags;
+ void *data;
+};
+
+struct pdf_boolean
+{
+ char value;
+};
+
+struct pdf_number
+{
+ double value;
+};
+
+struct pdf_string
+{
+ unsigned char *string;
+ unsigned short length;
+};
+
+struct pdf_name
+{
+ char *name;
+};
+
+struct pdf_array
+{
+ unsigned long max;
+ unsigned long size;
+ struct pdf_obj **values;
+};
+
+struct pdf_dict
+{
+ struct pdf_obj *key;
+ struct pdf_obj *value;
+ struct pdf_dict *next;
+};
+
+struct pdf_stream
+{
+ struct pdf_obj *dict;
+ unsigned char *stream;
+ long *objstm_data; /* used for object streams */
+ unsigned long stream_length;
+ unsigned long max_length;
+ unsigned char _flags;
+};
+
+struct pdf_indirect
+{
+ pdf_file *pf;
+ unsigned long label;
+ unsigned short generation;
+};
+
+typedef void pdf_null;
+typedef struct pdf_boolean pdf_boolean;
+typedef struct pdf_number pdf_number;
+typedef struct pdf_string pdf_string;
+typedef struct pdf_name pdf_name;
+typedef struct pdf_array pdf_array;
+typedef struct pdf_dict pdf_dict;
+typedef struct pdf_stream pdf_stream;
+typedef struct pdf_indirect pdf_indirect;
+
+static FILE *pdf_output_file = NULL;
+
+static long pdf_output_file_position = 0;
+static long pdf_output_line_position = 0;
+static long compression_saved = 0;
+
+#define FORMAT_BUF_SIZE 4096
+static char format_buffer[FORMAT_BUF_SIZE];
+
+typedef struct xref_entry
+{
+ unsigned char type; /* object storage type */
+ unsigned long field2; /* offset in file or object stream */
+ unsigned short field3; /* generation or index */
+ pdf_obj *direct; /* used for imported objects */
+ pdf_obj *indirect; /* used for imported objects */
+} xref_entry;
+
+static xref_entry *output_xref;
+
+static unsigned long pdf_max_ind_objects;
+static unsigned long next_label;
+
+static unsigned long startxref;
+
+struct pdf_file
+{
+ FILE *file;
+ pdf_obj *trailer;
+ xref_entry *xref_table;
+ long num_obj;
+ long file_size;
+ int version;
+};
+
+static pdf_obj *output_stream;
+
+#define OBJSTM_MAX_OBJS 200
+/* the limit is only 100 for linearized PDF */
+
+static int enc_mode;
+static int doc_enc_mode;
+
+static pdf_obj *trailer_dict;
+static pdf_obj *xref_stream;
+
+/* Internal static routines */
+
+static void pdf_flush_obj (pdf_obj *object, FILE *file);
+static void pdf_label_obj (pdf_obj *object);
+static void pdf_write_obj (pdf_obj *object, FILE *file);
+
+static void set_objstm_data (pdf_obj *objstm, long *data);
+static long *get_objstm_data (pdf_obj *objstm);
+static void release_objstm (pdf_obj *objstm);
+
+static void pdf_out_char (FILE *file, char c);
+static void pdf_out (FILE *file, const void *buffer, long length);
+
+static void release_indirect (pdf_indirect *data);
+static void write_indirect (pdf_indirect *indirect, FILE *file);
+
+static void release_boolean (pdf_obj *data);
+static void write_boolean (pdf_boolean *data, FILE *file);
+
+static void release_null (pdf_null *data);
+static void write_null (pdf_null *data, FILE *file);
+
+static void release_number (pdf_number *number);
+static void write_number (pdf_number *number, FILE *file);
+
+static void write_string (pdf_string *str, FILE *file);
+static void release_string (pdf_string *str);
+
+static void write_name (pdf_name *name, FILE *file);
+static void release_name (pdf_name *name);
+
+static void write_array (pdf_array *array, FILE *file);
+static void release_array (pdf_array *array);
+
+static void write_dict (pdf_dict *dict, FILE *file);
+static void release_dict (pdf_dict *dict);
+
+static void write_stream (pdf_stream *stream, FILE *file);
+static void release_stream (pdf_stream *stream);
+
+static int verbose = 0;
+static char compression_level = 9;
+
+void
+pdf_set_compression (int level)
+{
+#ifndef HAVE_ZLIB
+ ERROR("You don't have compression compiled in. Possibly libz wasn't found by configure.");
+#else
+#ifndef HAVE_ZLIB_COMPRESS2
+ if (level != 0)
+ WARN("Unable to set compression level -- your zlib doesn't have compress2().");
+#endif
+ if (level >= 0 && level <= 9)
+ compression_level = level;
+ else {
+ ERROR("set_compression: invalid compression level: %d", level);
+ }
+#endif /* !HAVE_ZLIB */
+
+ return;
+}
+
+static unsigned pdf_version = PDF_VERSION_DEFAULT;
+
+void
+pdf_set_version (unsigned version)
+{
+ /* Don't forget to update CIDFont_stdcc_def[] in cid.c too! */
+ if (version >= PDF_VERSION_MIN && version <= PDF_VERSION_MAX) {
+ pdf_version = version;
+ }
+}
+
+unsigned
+pdf_get_version (void)
+{
+ return pdf_version;
+}
+
+int
+pdf_obj_get_verbose(void)
+{
+ return verbose;
+}
+
+void
+pdf_obj_set_verbose(void)
+{
+ verbose++;
+}
+
+static pdf_obj *current_objstm = NULL;
+static int do_objstm;
+
+static void
+add_xref_entry (unsigned long label, unsigned char type, unsigned long field2, unsigned short field3)
+{
+ if (label >= pdf_max_ind_objects) {
+ pdf_max_ind_objects = (label/IND_OBJECTS_ALLOC_SIZE+1)*IND_OBJECTS_ALLOC_SIZE;
+ output_xref = RENEW(output_xref, pdf_max_ind_objects, xref_entry);
+ }
+
+ output_xref[label].type = type;
+ output_xref[label].field2 = field2;
+ output_xref[label].field3 = field3;
+ output_xref[label].direct = NULL;
+ output_xref[label].indirect = NULL;
+}
+
+#define BINARY_MARKER "%\344\360\355\370\n"
+void
+pdf_out_init (const char *filename, int do_encryption)
+{
+ char v;
+
+ output_xref = NULL;
+ pdf_max_ind_objects = 0;
+ add_xref_entry(0, 0, 0, 0xffff);
+ next_label = 1;
+
+ if (pdf_version >= 5) {
+ xref_stream = pdf_new_stream(STREAM_COMPRESS);
+ xref_stream->flags |= OBJ_NO_ENCRYPT;
+ trailer_dict = pdf_stream_dict(xref_stream);
+ pdf_add_dict(trailer_dict, pdf_new_name("Type"), pdf_new_name("XRef"));
+ do_objstm = 1;
+ } else {
+ xref_stream = NULL;
+ trailer_dict = pdf_new_dict();
+ do_objstm = 0;
+ }
+
+ output_stream = NULL;
+
+ if (filename == NULL) { /* no filename: writing to stdout */
+#ifdef WIN32
+ setmode(fileno(stdout), _O_BINARY);
+#endif
+ pdf_output_file = stdout;
+ }
+ else
+ pdf_output_file = MFOPEN(filename, FOPEN_WBIN_MODE);
+
+ if (!pdf_output_file) {
+ if (strlen(filename) < 128)
+ ERROR("Unable to open \"%s\".", filename);
+ else
+ ERROR("Unable to open file.");
+ }
+ pdf_out(pdf_output_file, "%PDF-1.", strlen("%PDF-1."));
+ v = '0' + pdf_version;
+ pdf_out(pdf_output_file, &v, 1);
+ pdf_out(pdf_output_file, "\n", 1);
+ pdf_out(pdf_output_file, BINARY_MARKER, strlen(BINARY_MARKER));
+
+ enc_mode = 0;
+ doc_enc_mode = do_encryption;
+}
+
+static void
+dump_xref_table (void)
+{
+ long length;
+ unsigned long i;
+
+ pdf_out(pdf_output_file, "xref\n", 5);
+
+ length = sprintf(format_buffer, "%d %lu\n", 0, next_label);
+ pdf_out(pdf_output_file, format_buffer, length);
+
+ /*
+ * Every space counts. The space after the 'f' and 'n' is * *essential*.
+ * The PDF spec says the lines must be 20 characters long including the
+ * end of line character.
+ */
+ for (i = 0; i < next_label; i++) {
+ unsigned char type = output_xref[i].type;
+ if (type > 1)
+ ERROR("object type %hu not allowed in xref table", type);
+ length = sprintf(format_buffer, "%010lu %05hu %c \n",
+ output_xref[i].field2, output_xref[i].field3,
+ type ? 'n' : 'f');
+ pdf_out(pdf_output_file, format_buffer, length);
+ }
+}
+
+static void
+dump_trailer_dict (void)
+{
+ pdf_out(pdf_output_file, "trailer\n", 8);
+ enc_mode = 0;
+ write_dict(trailer_dict->data, pdf_output_file);
+ pdf_release_obj(trailer_dict);
+ pdf_out_char(pdf_output_file, '\n');
+}
+
+/*
+ * output a PDF 1.5 cross-reference stream;
+ * contributed by Matthias Franz (March 21, 2007)
+ */
+static void
+dump_xref_stream (void)
+{
+ unsigned long pos, i;
+ unsigned poslen;
+ unsigned char buf[7] = {0, 0, 0, 0, 0};
+
+ pdf_obj *w;
+
+ /* determine the necessary size of the offset field */
+ pos = startxref; /* maximal offset value */
+ poslen = 1;
+ while (pos >>= 8)
+ poslen++;
+
+ w = pdf_new_array();
+ pdf_add_array(w, pdf_new_number(1)); /* type */
+ pdf_add_array(w, pdf_new_number(poslen)); /* offset (big-endian) */
+ pdf_add_array(w, pdf_new_number(2)); /* generation */
+ pdf_add_dict(trailer_dict, pdf_new_name("W"), w);
+
+ /* We need the xref entry for the xref stream right now */
+ add_xref_entry(next_label-1, 1, startxref, 0);
+
+ for (i = 0; i < next_label; i++) {
+ unsigned j;
+ unsigned short f3;
+ buf[0] = output_xref[i].type;
+ pos = output_xref[i].field2;
+ for (j = poslen; j--; ) {
+ buf[1+j] = (unsigned char) pos;
+ pos >>= 8;
+ }
+ f3 = output_xref[i].field3;
+ buf[poslen+1] = (unsigned char) (f3 >> 8);
+ buf[poslen+2] = (unsigned char) (f3);
+ pdf_add_stream(xref_stream, &buf, poslen+3);
+ }
+
+ pdf_release_obj(xref_stream);
+}
+
+void
+pdf_out_flush (void)
+{
+ if (pdf_output_file) {
+ long length;
+
+ /* Flush current object stream */
+ if (current_objstm) {
+ release_objstm(current_objstm);
+ current_objstm =NULL;
+ }
+
+ /*
+ * Label xref stream - we need the number of correct objects
+ * for the xref stream dictionary (= trailer).
+ * Labelling it in pdf_out_init (with 1) does not work (why?).
+ */
+ if (xref_stream)
+ pdf_label_obj(xref_stream);
+
+ /* Record where this xref is for trailer */
+ startxref = pdf_output_file_position;
+
+ pdf_add_dict(trailer_dict, pdf_new_name("Size"),
+ pdf_new_number(next_label));
+
+ if (xref_stream)
+ dump_xref_stream();
+ else {
+ dump_xref_table();
+ dump_trailer_dict();
+ }
+
+ /* Done with xref table */
+ RELEASE(output_xref);
+
+ pdf_out(pdf_output_file, "startxref\n", 10);
+ length = sprintf(format_buffer, "%lu\n", startxref);
+ pdf_out(pdf_output_file, format_buffer, length);
+ pdf_out(pdf_output_file, "%%EOF\n", 6);
+
+ MESG("\n");
+ if (verbose) {
+ if (compression_level > 0) {
+ MESG("Compression saved %ld bytes%s\n", compression_saved,
+ pdf_version < 5 ? ". Try \"-V 5\" for better compression" : "");
+ }
+ }
+ MESG("%ld bytes written", pdf_output_file_position);
+
+ MFCLOSE(pdf_output_file);
+ }
+}
+
+void
+pdf_error_cleanup (void)
+{
+ /*
+ * This routine is the cleanup required for an abnormal exit.
+ * For now, simply close the file.
+ */
+ if (pdf_output_file)
+ MFCLOSE(pdf_output_file);
+}
+
+
+void
+pdf_set_root (pdf_obj *object)
+{
+ if (pdf_add_dict(trailer_dict, pdf_new_name("Root"), pdf_ref_obj(object))) {
+ ERROR("Root object already set!");
+ }
+ /* Adobe Readers don't like a document catalog inside an encrypted
+ * object stream, although the PDF v1.5 spec seems to allow this.
+ * Note that we don't set OBJ_NO_ENCRYPT since the name dictionary in
+ * a document catalog may contain strings, which should be encrypted.
+ */
+ if (doc_enc_mode)
+ object->flags |= OBJ_NO_OBJSTM;
+}
+
+void
+pdf_set_info (pdf_obj *object)
+{
+ if (pdf_add_dict(trailer_dict, pdf_new_name("Info"), pdf_ref_obj(object))) {
+ ERROR ("Info object already set!");
+ }
+}
+
+void
+pdf_set_encrypt (pdf_obj *encrypt, pdf_obj *id)
+{
+ if (pdf_add_dict(trailer_dict, pdf_new_name("Encrypt"), pdf_ref_obj(encrypt))) {
+ ERROR("Encrypt object already set!");
+ }
+ encrypt->flags |= OBJ_NO_ENCRYPT;
+
+ pdf_add_dict(trailer_dict, pdf_new_name("ID"), id);
+}
+
+static
+void pdf_out_char (FILE *file, char c)
+{
+ if (output_stream && file == pdf_output_file)
+ pdf_add_stream(output_stream, &c, 1);
+ else {
+ fputc(c, file);
+ /* Keep tallys for xref table *only* if writing a pdf file. */
+ if (file == pdf_output_file) {
+ pdf_output_file_position += 1;
+ if (c == '\n')
+ pdf_output_line_position = 0;
+ else
+ pdf_output_line_position += 1;
+ }
+ }
+}
+
+static char xchar[] = "0123456789abcdef";
+
+#define pdf_out_xchar(f,c) do {\
+ pdf_out_char((f), xchar[((c) >> 4) & 0x0f]);\
+ pdf_out_char((f), xchar[(c) & 0x0f]);\
+} while (0)
+
+static
+void pdf_out (FILE *file, const void *buffer, long length)
+{
+ if (output_stream && file == pdf_output_file)
+ pdf_add_stream(output_stream, buffer, length);
+ else {
+ fwrite(buffer, 1, length, file);
+ /* Keep tallys for xref table *only* if writing a pdf file */
+ if (file == pdf_output_file) {
+ pdf_output_file_position += length;
+ pdf_output_line_position += length;
+ /* "foo\nbar\n "... */
+ if (length > 0 &&
+ ((const char *)buffer)[length-1] == '\n')
+ pdf_output_line_position = 0;
+ }
+ }
+}
+
+/* returns 1 if a white-space character is necessary to separate
+ an object of type1 followed by an object of type2 */
+static
+int pdf_need_white (int type1, int type2)
+{
+ return !(type1 == PDF_STRING || type1 == PDF_ARRAY || type1 == PDF_DICT ||
+ type2 == PDF_STRING || type2 == PDF_NAME ||
+ type2 == PDF_ARRAY || type2 == PDF_DICT);
+}
+
+static
+void pdf_out_white (FILE *file)
+{
+ if (file == pdf_output_file && pdf_output_line_position >= 80) {
+ pdf_out_char(file, '\n');
+ } else {
+ pdf_out_char(file, ' ');
+ }
+}
+
+#define TYPECHECK(o,t) if (!(o) || (o)->type != (t)) {\
+ ERROR("typecheck: Invalid object type: %d %d (line %d)", (o) ? (o)->type : -1, (t), __LINE__);\
+}
+
+#define INVALIDOBJ(o) ((o) == NULL || (o)->type <= 0 || (o)->type > PDF_INDIRECT)
+
+pdf_obj *
+pdf_new_obj(int type)
+{
+ pdf_obj *result;
+
+ if (type > PDF_INDIRECT || type < PDF_UNDEFINED)
+ ERROR("Invalid object type: %d", type);
+
+ result = NEW(1, pdf_obj);
+ result->type = type;
+ result->data = NULL;
+ result->label = 0;
+ result->generation = 0;
+ result->refcount = 1;
+ result->flags = 0;
+
+ return result;
+}
+
+int
+pdf_obj_typeof (pdf_obj *object)
+{
+ if (INVALIDOBJ(object))
+ return PDF_OBJ_INVALID;
+
+ return object->type;
+}
+
+static void
+pdf_label_obj (pdf_obj *object)
+{
+ if (INVALIDOBJ(object))
+ ERROR("pdf_label_obj(): passed invalid object.");
+
+ /*
+ * Don't change label on an already labeled object. Ignore such calls.
+ */
+ if (object->label == 0) {
+ object->label = next_label++;
+ object->generation = 0;
+ }
+}
+
+/*
+ * This doesn't really copy the object, but allows it to be used without
+ * fear that somebody else will free it.
+ */
+pdf_obj *
+pdf_link_obj (pdf_obj *object)
+{
+ if (INVALIDOBJ(object))
+ ERROR("pdf_link_obj(): passed invalid object.");
+
+ object->refcount += 1;
+
+ return object;
+}
+
+
+pdf_obj *
+pdf_ref_obj (pdf_obj *object)
+{
+ if (INVALIDOBJ(object))
+ ERROR("pdf_ref_obj(): passed invalid object.");
+
+ if (object->refcount == 0) {
+ MESG("\nTrying to refer already released object!!!\n");
+ pdf_write_obj(object, stderr);
+ ERROR("Cannot continue...");
+ }
+
+ if (PDF_OBJ_INDIRECTTYPE(object)) {
+ return pdf_link_obj(object);
+ } else {
+ if (object->label == 0) {
+ pdf_label_obj(object);
+ }
+ return pdf_new_indirect(NULL, object->label, object->generation);
+ }
+}
+
+static void
+release_indirect (pdf_indirect *data)
+{
+ RELEASE(data);
+}
+
+static void
+write_indirect (pdf_indirect *indirect, FILE *file)
+{
+ long length;
+
+ ASSERT(!indirect->pf);
+
+ length = sprintf(format_buffer, "%lu %hu R", indirect->label, indirect->generation);
+ pdf_out(file, format_buffer, length);
+}
+
+pdf_obj *
+pdf_new_null (void)
+{
+ pdf_obj *result;
+
+ result = pdf_new_obj(PDF_NULL);
+ result->data = NULL;
+
+ return result;
+}
+
+static void
+release_null (pdf_null *obj)
+{
+ return;
+}
+
+static void
+write_null (pdf_null *obj, FILE *file)
+{
+ pdf_out(file, "null", 4);
+}
+
+pdf_obj *
+pdf_new_boolean (char value)
+{
+ pdf_obj *result;
+ pdf_boolean *data;
+
+ result = pdf_new_obj(PDF_BOOLEAN);
+ data = NEW(1, pdf_boolean);
+ data->value = value;
+ result->data = data;
+
+ return result;
+}
+
+static void
+release_boolean (pdf_obj *data)
+{
+ RELEASE (data);
+}
+
+static void
+write_boolean (pdf_boolean *data, FILE *file)
+{
+ if (data->value) {
+ pdf_out(file, "true", 4);
+ } else {
+ pdf_out(file, "false", 5);
+ }
+}
+
+void
+pdf_set_boolean (pdf_obj *object, char value)
+{
+ pdf_boolean *data;
+
+ TYPECHECK(object, PDF_BOOLEAN);
+
+ data = object->data;
+ data->value = value;
+}
+
+char
+pdf_boolean_value (pdf_obj *object)
+{
+ pdf_boolean *data;
+
+ TYPECHECK(object, PDF_BOOLEAN);
+
+ data = object->data;
+
+ return data->value;
+}
+
+pdf_obj *
+pdf_new_number (double value)
+{
+ pdf_obj *result;
+ pdf_number *data;
+
+ result = pdf_new_obj(PDF_NUMBER);
+ data = NEW(1, pdf_number);
+ data->value = value;
+ result->data = data;
+
+ return result;
+}
+
+static void
+release_number (pdf_number *data)
+{
+ RELEASE (data);
+}
+
+static void
+write_number (pdf_number *number, FILE *file)
+{
+ int count;
+
+ count = pdf_sprint_number(format_buffer, number->value);
+
+ pdf_out(file, format_buffer, count);
+}
+
+
+void
+pdf_set_number (pdf_obj *object, double value)
+{
+ pdf_number *data;
+
+ TYPECHECK(object, PDF_NUMBER);
+
+ data = object->data;
+ data->value = value;
+}
+
+double
+pdf_number_value (pdf_obj *object)
+{
+ pdf_number *data;
+
+ TYPECHECK(object, PDF_NUMBER);
+
+ data = object->data;
+
+ return data->value;
+}
+
+pdf_obj *
+pdf_new_string (const void *str, unsigned length)
+{
+ pdf_obj *result;
+ pdf_string *data;
+
+ result = pdf_new_obj(PDF_STRING);
+ data = NEW(1, pdf_string);
+ result->data = data;
+ if (length != 0) {
+ data->length = length;
+ data->string = NEW(length+1, unsigned char);
+ memcpy(data->string, str, length);
+ /* Shouldn't assume NULL terminated. */
+ data->string[length] = '\0';
+ } else {
+ data->length = 0;
+ data->string = NULL;
+ }
+
+ return result;
+}
+
+void *
+pdf_string_value (pdf_obj *object)
+{
+ pdf_string *data;
+
+ TYPECHECK(object, PDF_STRING);
+
+ data = object->data;
+
+ return data->string;
+}
+
+unsigned
+pdf_string_length (pdf_obj *object)
+{
+ pdf_string *data;
+
+ TYPECHECK(object, PDF_STRING);
+
+ data = object->data;
+
+ return (unsigned) (data->length);
+}
+
+/*
+ * This routine escapes non printable characters and control
+ * characters in an output string.
+ */
+int
+pdfobj_escape_str (char *buffer, int bufsize, const unsigned char *s, int len)
+{
+ int result = 0;
+ int i;
+
+ for (i = 0; i < len; i++) {
+ unsigned char ch;
+
+ ch = s[i];
+ if (result > bufsize - 4)
+ ERROR("pdfobj_escape_str: Buffer overflow");
+
+ /*
+ * We always write three octal digits. Optimization only gives few Kb
+ * smaller size for most documents when zlib compressed.
+ */
+ if (ch < 32 || ch > 126) {
+ buffer[result++] = '\\';
+#if 0
+ if (i < len - 1 && !isdigit(s[i+1]))
+ result += sprintf(buffer+result, "%o", ch);
+ else
+ result += sprintf(buffer+result, "%03o", ch);
+#endif
+ result += sprintf(buffer+result, "%03o", ch);
+ } else {
+ switch (ch) {
+ case '(':
+ buffer[result++] = '\\';
+ buffer[result++] = '(';
+ break;
+ case ')':
+ buffer[result++] = '\\';
+ buffer[result++] = ')';
+ break;
+ case '\\':
+ buffer[result++] = '\\';
+ buffer[result++] = '\\';
+ break;
+ default:
+ buffer[result++] = ch;
+ break;
+ }
+ }
+ }
+
+ return result;
+}
+
+static void
+write_string (pdf_string *str, FILE *file)
+{
+ unsigned char *s;
+ char wbuf[FORMAT_BUF_SIZE]; /* Shouldn't use format_buffer[]. */
+ int nescc = 0, i, count;
+
+ s = str->string;
+
+ if (enc_mode)
+ pdf_encrypt_data(s, str->length);
+
+ /*
+ * Count all ASCII non-printable characters.
+ */
+ for (i = 0; i < str->length; i++) {
+ if (!isprint(s[i]))
+ nescc++;
+ }
+ /*
+ * If the string contains much escaped chars, then we write it as
+ * ASCII hex string.
+ */
+ if (nescc > str->length / 3) {
+ pdf_out_char(file, '<');
+ for (i = 0; i < str->length; i++) {
+ pdf_out_xchar(file, s[i]);
+ }
+ pdf_out_char(file, '>');
+ } else {
+ pdf_out_char(file, '(');
+ /*
+ * This section of code probably isn't speed critical. Escaping the
+ * characters in the string one at a time may seem slow, but it's
+ * safe if the formatted string length exceeds FORMAT_BUF_SIZE.
+ * Occasionally you see some long strings in PDF. pdfobj_escape_str
+ * is also used for strings of text with no kerning. These must be
+ * handled as quickly as possible since there are so many of them.
+ */
+ for (i = 0; i < str->length; i++) {
+ count = pdfobj_escape_str(wbuf, FORMAT_BUF_SIZE, &(s[i]), 1);
+ pdf_out(file, wbuf, count);
+ }
+ pdf_out_char(file, ')');
+ }
+}
+
+static void
+release_string (pdf_string *data)
+{
+ if (data->string != NULL) {
+ RELEASE(data->string);
+ data->string = NULL;
+ }
+ RELEASE(data);
+}
+
+void
+pdf_set_string (pdf_obj *object, unsigned char *str, unsigned length)
+{
+ pdf_string *data;
+
+ TYPECHECK(object, PDF_STRING);
+
+ data = object->data;
+ if (data->string != 0) {
+ RELEASE(data->string);
+ }
+ if (length != 0) {
+ data->length = length;
+ data->string = NEW(length + 1, unsigned char);
+ memcpy(data->string, str, length);
+ data->string[length] = '\0';
+ } else {
+ data->length = 0;
+ data->string = NULL;
+ }
+}
+
+/* Name does *not* include the /. */
+pdf_obj *
+pdf_new_name (const char *name)
+{
+ pdf_obj *result;
+ unsigned length;
+ pdf_name *data;
+
+ result = pdf_new_obj(PDF_NAME);
+ data = NEW (1, pdf_name);
+ result->data = data;
+ length = strlen(name);
+ if (length != 0) {
+ data->name = NEW(length+1, char);
+ memcpy(data->name, name, length);
+ data->name[length] = '\0';
+ } else {
+ data->name = NULL;
+ }
+
+ return result;
+}
+
+static void
+write_name (pdf_name *name, FILE *file)
+{
+ char *s;
+ int i, length;
+
+ s = name->name;
+ length = name->name ? strlen(name->name) : 0;
+ /*
+ * From PDF Reference, 3rd ed., p.33:
+ *
+ * Beginning with PDF 1.2, any character except null (character code 0)
+ * may be included in a name by writing its 2-digit hexadecimal code,
+ * preceded bythe number sign character (#); see implementation notes 3
+ * and 4 in Appendix H. This syntax is required in order to represent
+ * any of the delimiter or white-space characters or the number sign
+ * character itself; it is recommended but not required for characters
+ * whose codes are outside the range 33 (!) to 126 (~).
+ */
+#ifndef is_delim
+ /* Avoid '{' and '}' for PostScript compatibility? */
+#define is_delim(c) ((c) == '(' || (c) == '/' || \
+ (c) == '<' || (c) == '>' || \
+ (c) == '[' || (c) == ']' || \
+ (c) == '{' || (c) == '}' || \
+ (c) == '%')
+#endif
+ pdf_out_char(file, '/');
+ for (i = 0; i < length; i++) {
+ if (s[i] < '!' || s[i] > '~' || s[i] == '#' || is_delim(s[i])) {
+ /* ^ "space" is here. */
+ pdf_out_char (file, '#');
+ pdf_out_xchar(file, s[i]);
+ } else {
+ pdf_out_char (file, s[i]);
+ }
+ }
+}
+
+static void
+release_name (pdf_name *data)
+{
+ if (data->name != NULL) {
+ RELEASE(data->name);
+ data->name = NULL;
+ }
+ RELEASE(data);
+}
+
+void
+pdf_set_name (pdf_obj *object, const char *name)
+{
+ pdf_name *data;
+ unsigned length;
+
+ TYPECHECK(object, PDF_NAME);
+
+ length = strlen(name);
+ data = object->data;
+ if (data->name != NULL) {
+ RELEASE(data->name);
+ }
+ if (length != 0) {
+ data->name = NEW(length+1, char);
+ memcpy(data->name, name, length);
+ data->name[length] = 0;
+ } else {
+ data->name = NULL;
+ }
+}
+
+char *
+pdf_name_value (pdf_obj *object)
+{
+ pdf_name *data;
+
+ TYPECHECK(object, PDF_NAME);
+
+ data = object->data;
+
+ return data->name;
+}
+
+/*
+ * We do not have pdf_name_length() since '\0' is not allowed
+ * in PDF name object.
+ */
+
+pdf_obj *
+pdf_new_array (void)
+{
+ pdf_obj *result;
+ pdf_array *data;
+
+ result = pdf_new_obj(PDF_ARRAY);
+ data = NEW(1, pdf_array);
+ data->values = NULL;
+ data->max = 0;
+ data->size = 0;
+ result->data = data;
+
+ return result;
+}
+
+static void
+write_array (pdf_array *array, FILE *file)
+{
+ pdf_out_char(file, '[');
+ if (array->size > 0) {
+ unsigned long i;
+ int type1 = PDF_UNDEFINED, type2;
+
+ for (i = 0; i < array->size; i++) {
+ if (array->values[i]) {
+ type2 = array->values[i]->type;
+ if (type1 != PDF_UNDEFINED && pdf_need_white(type1, type2))
+ pdf_out_white(file);
+ type1 = type2;
+ pdf_write_obj(array->values[i], file);
+ } else
+ WARN("PDF array element #ld undefined.", i);
+ }
+ }
+ pdf_out_char(file, ']');
+}
+
+pdf_obj *
+pdf_get_array (pdf_obj *array, long idx)
+{
+ pdf_obj *result = NULL;
+ pdf_array *data;
+
+ TYPECHECK(array, PDF_ARRAY);
+
+ data = array->data;
+ if (idx < 0)
+ result = data->values[idx + data->size];
+ else if (idx < data->size) {
+ result = data->values[idx];
+ }
+
+ return result;
+}
+
+unsigned int
+pdf_array_length (pdf_obj *array)
+{
+ pdf_array *data;
+
+ TYPECHECK(array, PDF_ARRAY);
+
+ data = (pdf_array *) array->data;
+
+ return (unsigned int) data->size;
+}
+
+static void
+release_array (pdf_array *data)
+{
+ unsigned long i;
+
+ if (data->values) {
+ for (i = 0; i < data->size; i++) {
+ pdf_release_obj(data->values[i]);
+ data->values[i] = NULL;
+ }
+ RELEASE(data->values);
+ data->values = NULL;
+ }
+ RELEASE(data);
+}
+
+/*
+ * The name pdf_add_array is misleading. It behaves differently than
+ * pdf_add_dict(). This should be pdf_push_array().
+ */
+void
+pdf_add_array (pdf_obj *array, pdf_obj *object)
+{
+ pdf_array *data;
+
+ TYPECHECK(array, PDF_ARRAY);
+
+ data = array->data;
+ if (data->size >= data->max) {
+ data->max += ARRAY_ALLOC_SIZE;
+ data->values = RENEW(data->values, data->max, pdf_obj *);
+ }
+ data->values[data->size] = object;
+ data->size++;
+
+ return;
+}
+
+#if 0
+void
+pdf_put_array (pdf_obj *array, unsigned idx, pdf_obj *object)
+{
+ pdf_array *data;
+ long i;
+
+ TYPECHECK(array, PDF_ARRAY);
+
+ data = array->data;
+ if (idx + 1 > data->max) {
+ data->max += ARRAY_ALLOC_SIZE;
+ data->values = RENEW(data->values, data->max, pdf_obj *);
+ }
+ /*
+ * Rangecheck error in PostScript interpreters if
+ * idx > data->size - 1. But pdf_new_array() doesn't set
+ * array size, pdf_add_array() dynamically increases size
+ * of array. This might confusing...
+ */
+ if (idx + 1 > data->size) {
+ for (i = data->size; i < idx; i++)
+ data->values[i] = pdf_new_null(); /* release_array() won't work without this */
+ data->values[idx] = object;
+ data->size = idx + 1;
+ } else {
+ if (data->values[idx])
+ pdf_release_obj(data->values[idx]);
+ data->values[idx] = object;
+ }
+}
+
+/* Easily leaks memory... */
+pdf_obj *
+pdf_shift_array (pdf_obj *array)
+{
+ pdf_obj *result = NULL;
+ pdf_array *data;
+
+ TYPECHECK(array, PDF_ARRAY);
+
+ data = array->data;
+ if (data->size > 0) {
+ int i;
+
+ result = data->values[0];
+ for (i = 1; i < data->size; i++)
+ data->values[i-1] = data->values[i];
+ data->size--;
+ }
+
+ return result;
+}
+#endif /* 0 */
+
+/* Prepend an object to an array */
+void
+pdf_unshift_array (pdf_obj *array, pdf_obj *object)
+{
+ pdf_array *data;
+ int i;
+
+ TYPECHECK(array, PDF_ARRAY);
+
+ data = array->data;
+ if (data->size >= data->max) {
+ data->max += ARRAY_ALLOC_SIZE;
+ data->values = RENEW(data->values, data->max, pdf_obj *);
+ }
+ for (i = 0; i < data->size; i++)
+ data->values[i+1] = data->values[i];
+ data->values[0] = object;
+ data->size++;
+}
+
+#if 0
+pdf_obj *
+pdf_pop_array (pdf_obj *array)
+{
+ pdf_obj *result;
+ pdf_array *data;
+
+ TYPECHECK(array, PDF_ARRAY);
+
+ data = array->data;
+ if (data->size > 0) {
+ result = data->values[data->size - 1];
+ data->size--;
+ } else {
+ result = NULL;
+ }
+
+ return result;
+}
+#endif /* 0 */
+
+static void
+write_dict (pdf_dict *dict, FILE *file)
+{
+ pdf_out (file, "<<\n", 3); /* dropping \n saves few kb. */
+ while (dict->key != NULL) {
+ pdf_write_obj(dict->key, file);
+ if (pdf_need_white(PDF_NAME, (dict->value)->type)) {
+ pdf_out_white(file);
+ }
+ pdf_write_obj(dict->value, file);
+ pdf_out_char (file, '\n'); /* removing this saves few kb. */
+ dict = dict->next;
+ }
+ pdf_out(file, ">>", 2);
+}
+
+pdf_obj *
+pdf_new_dict (void)
+{
+ pdf_obj *result;
+ pdf_dict *data;
+
+ result = pdf_new_obj(PDF_DICT);
+ data = NEW(1, pdf_dict);
+ data->key = NULL;
+ data->value = NULL;
+ data->next = NULL;
+ result->data = data;
+
+ return result;
+}
+
+static void
+release_dict (pdf_dict *data)
+{
+ pdf_dict *next;
+
+ while (data != NULL && data->key != NULL) {
+ pdf_release_obj(data->key);
+ pdf_release_obj(data->value);
+ data->key = NULL;
+ data->value = NULL;
+ next = data->next;
+ RELEASE(data);
+ data = next;
+ }
+ RELEASE(data);
+}
+
+/* Array is ended by a node with NULL this pointer */
+/* pdf_add_dict returns 0 if the key is new and non-zero otherwise */
+int
+pdf_add_dict (pdf_obj *dict, pdf_obj *key, pdf_obj *value)
+{
+ pdf_dict *data, *new_node;
+
+ TYPECHECK(dict, PDF_DICT);
+ TYPECHECK(key, PDF_NAME);
+
+ /* It seems that NULL is sometimes used for null object... */
+ if (value != NULL && INVALIDOBJ(value))
+ ERROR("pdf_add_dict(): Passed invalid value");
+
+ /* If this key already exists, simply replace the value */
+ for (data = dict->data; data->key != NULL; data = data->next) {
+ if (!strcmp(pdf_name_value(key), pdf_name_value(data->key))) {
+ /* Release the old value */
+ pdf_release_obj(data->value);
+ /* Release the new key (we don't need it) */
+ pdf_release_obj(key);
+ data->value = value;
+ return 1;
+ }
+ }
+ /*
+ * We didn't find the key. We build a new "end" node and add
+ * the new key just before the end
+ */
+ new_node = NEW (1, pdf_dict);
+ new_node->key = NULL;
+ new_node->value = NULL;
+ new_node->next = NULL;
+ data->next = new_node;
+ data->key = key;
+ data->value = value;
+ return 0;
+}
+
+#if 0
+void
+pdf_put_dict (pdf_obj *dict, const char *key, pdf_obj *value)
+{
+ pdf_dict *data;
+
+ TYPECHECK(dict, PDF_DICT);
+
+ if (!key) {
+ ERROR("pdf_put_dict(): Passed invalid key.");
+ }
+ /* It seems that NULL is sometimes used for null object... */
+ if (value != NULL && INVALIDOBJ(value)) {
+ ERROR("pdf_add_dict(): Passed invalid value.");
+ }
+
+ data = dict->data;
+
+ while (data->key != NULL) {
+ if (!strcmp(key, pdf_name_value(data->key))) {
+ pdf_release_obj(data->value);
+ data->value = value;
+ break;
+ }
+ data = data->next;
+ }
+
+ /*
+ * If we didn't find the key, build a new "end" node and add
+ * the new key just before the end
+ */
+ if (data->key == NULL) {
+ pdf_dict *new_node;
+
+ new_node = NEW (1, pdf_dict);
+ new_node->key = NULL;
+ new_node->value = NULL;
+ new_node->next = NULL;
+ data->next = new_node;
+ data->key = pdf_new_name(key);
+ data->value = value;
+ }
+}
+#endif /* 0 */
+
+/* pdf_merge_dict makes a link for each item in dict2 before stealing it */
+void
+pdf_merge_dict (pdf_obj *dict1, pdf_obj *dict2)
+{
+ pdf_dict *data;
+
+ TYPECHECK(dict1, PDF_DICT);
+ TYPECHECK(dict2, PDF_DICT);
+
+ data = dict2->data;
+ while (data->key != NULL) {
+ pdf_add_dict(dict1, pdf_link_obj(data->key), pdf_link_obj(data->value));
+ data = data->next;
+ }
+}
+
+int
+pdf_foreach_dict (pdf_obj *dict,
+ int (*proc) (pdf_obj *, pdf_obj *, void *), void *pdata)
+{
+ int error = 0;
+ pdf_dict *data;
+
+ ASSERT(proc);
+
+ TYPECHECK(dict, PDF_DICT);
+
+ data = dict->data;
+ while (!error &&
+ data->key != NULL) {
+ error = proc(data->key, data->value, pdata);
+ data = data->next;
+ }
+
+ return error;
+}
+
+#define pdf_match_name(o,s) ((o) && (s) && !strcmp(((pdf_name *)(o)->data)->name, (s)))
+pdf_obj *
+pdf_lookup_dict (pdf_obj *dict, const char *name)
+{
+ pdf_dict *data;
+
+ ASSERT(name);
+
+ TYPECHECK(dict, PDF_DICT);
+
+ data = dict->data;
+ while (data->key != NULL) {
+ if (!strcmp(name, pdf_name_value(data->key))) {
+ return data->value;
+ }
+ data = data->next;
+ }
+
+ return NULL;
+}
+
+/* Returns array of dictionary keys */
+pdf_obj *
+pdf_dict_keys (pdf_obj *dict)
+{
+ pdf_obj *keys;
+ pdf_dict *data;
+
+ TYPECHECK(dict, PDF_DICT);
+
+ keys = pdf_new_array();
+ for (data = dict->data; (data &&
+ data->key != NULL); data = data->next) {
+ /* We duplicate name object rather than linking keys.
+ * If we forget to free keys, broken PDF is generated.
+ */
+ pdf_add_array(keys, pdf_new_name(pdf_name_value(data->key)));
+ }
+
+ return keys;
+}
+
+void
+pdf_remove_dict (pdf_obj *dict, const char *name)
+{
+ pdf_dict *data, **data_p;
+
+ TYPECHECK(dict, PDF_DICT);
+
+ data = dict->data;
+ data_p = (pdf_dict **) (void *) &(dict->data);
+ while (data->key != NULL) {
+ if (pdf_match_name(data->key, name)) {
+ pdf_release_obj(data->key);
+ pdf_release_obj(data->value);
+ *data_p = data->next;
+ RELEASE(data);
+ break;
+ }
+ data_p = &(data->next);
+ data = data->next;
+ }
+}
+
+pdf_obj *
+pdf_new_stream (int flags)
+{
+ pdf_obj *result;
+ pdf_stream *data;
+
+ result = pdf_new_obj(PDF_STREAM);
+ data = NEW(1, pdf_stream);
+ /*
+ * Although we are using an arbitrary pdf_object here, it must have
+ * type=PDF_DICT and cannot be an indirect reference. This will be
+ * checked by the output routine.
+ */
+ data->dict = pdf_new_dict();
+ data->_flags = flags;
+ data->stream = NULL;
+ data->stream_length = 0;
+ data->max_length = 0;
+ data->objstm_data = NULL;
+
+ result->data = data;
+ result->flags |= OBJ_NO_OBJSTM;
+
+ return result;
+}
+
+static void
+write_stream (pdf_stream *stream, FILE *file)
+{
+ unsigned char *filtered;
+ unsigned long filtered_length;
+ unsigned long buffer_length;
+ unsigned char *buffer;
+
+ /*
+ * Always work from a copy of the stream. All filters read from
+ * "filtered" and leave their result in "filtered".
+ */
+#if 0
+ filtered = NEW(stream->stream_length + 1, unsigned char);
+#endif
+ filtered = NEW(stream->stream_length, unsigned char);
+ memcpy(filtered, stream->stream, stream->stream_length);
+ filtered_length = stream->stream_length;
+
+#if 0
+ if (stream->stream_length < 10)
+ stream->_flags &= ^STREAM_COMPRESS;
+#endif
+
+#ifdef HAVE_ZLIB
+ /* Apply compression filter if requested */
+ if (stream->stream_length > 0 &&
+ (stream->_flags & STREAM_COMPRESS) &&
+ compression_level > 0) {
+
+ pdf_obj *filters = pdf_lookup_dict(stream->dict, "Filter");
+
+ buffer_length = filtered_length + filtered_length/1000 + 14;
+ buffer = NEW(buffer_length, unsigned char);
+ {
+ pdf_obj *filter_name = pdf_new_name("FlateDecode");
+
+ if (filters)
+ /*
+ * FlateDecode is the first filter to be applied to the stream.
+ */
+ pdf_unshift_array(filters, filter_name);
+ else
+ /*
+ * Adding the filter as a name instead of a one-element array
+ * is crucial because otherwise Adobe Reader cannot read the
+ * cross-reference stream any more, cf. the PDF v1.5 Errata.
+ */
+ pdf_add_dict(stream->dict, pdf_new_name("Filter"), filter_name);
+ }
+#ifdef HAVE_ZLIB_COMPRESS2
+ if (compress2(buffer, &buffer_length, filtered,
+ filtered_length, compression_level)) {
+ ERROR("Zlib error");
+ }
+#else
+ if (compress(buffer, &buffer_length, filtered,
+ filtered_length)) {
+ ERROR ("Zlib error");
+ }
+#endif /* HAVE_ZLIB_COMPRESS2 */
+ RELEASE(filtered);
+ compression_saved += filtered_length - buffer_length
+ - (filters ? strlen("/FlateDecode "): strlen("/Filter/FlateDecode\n"));
+
+ filtered = buffer;
+ filtered_length = buffer_length;
+ }
+#endif /* HAVE_ZLIB */
+
+#if 0
+ /*
+ * An optional end-of-line marker preceding the "endstream" is
+ * not part of stream data. See, PDF Reference 4th ed., p. 38.
+ */
+ /* Add a '\n' if the last character wasn't one */
+ if (filtered_length > 0 &&
+ filtered[filtered_length-1] != '\n') {
+ filtered[filtered_length] = '\n';
+ filtered_length++;
+ }
+#endif
+ pdf_add_dict(stream->dict,
+ pdf_new_name("Length"), pdf_new_number(filtered_length));
+
+ pdf_write_obj(stream->dict, file);
+
+ pdf_out(file, "\nstream\n", 8);
+
+ if (enc_mode)
+ pdf_encrypt_data(filtered, filtered_length);
+
+ if (filtered_length > 0) {
+ pdf_out(file, filtered, filtered_length);
+ }
+ RELEASE(filtered);
+
+ /*
+ * This stream length "object" gets reset every time write_stream is
+ * called for the stream object.
+ * If this stream gets written more than once with different
+ * filters, this could be a problem.
+ */
+
+ pdf_out(file, "\n", 1);
+ pdf_out(file, "endstream", 9);
+}
+
+static void
+release_stream (pdf_stream *stream)
+{
+ pdf_release_obj(stream->dict);
+ stream->dict = NULL;
+
+ if (stream->stream) {
+ RELEASE(stream->stream);
+ stream->stream = NULL;
+ }
+
+ if (stream->objstm_data) {
+ RELEASE(stream->objstm_data);
+ stream->objstm_data = NULL;
+ }
+
+ RELEASE(stream);
+}
+
+pdf_obj *
+pdf_stream_dict (pdf_obj *stream)
+{
+ pdf_stream *data;
+
+ TYPECHECK(stream, PDF_STREAM);
+
+ data = stream->data;
+
+ return data->dict;
+}
+
+const void *
+pdf_stream_dataptr (pdf_obj *stream)
+{
+ pdf_stream *data;
+
+ TYPECHECK(stream, PDF_STREAM);
+
+ data = stream->data;
+
+ return (const void *) data->stream;
+}
+
+long
+pdf_stream_length (pdf_obj *stream)
+{
+ pdf_stream *data;
+
+ TYPECHECK(stream, PDF_STREAM);
+
+ data = stream->data;
+
+ return (long) data->stream_length;
+}
+
+static void
+set_objstm_data (pdf_obj *objstm, long *data) {
+ TYPECHECK(objstm, PDF_STREAM);
+
+ ((pdf_stream *) objstm->data)->objstm_data = data;
+}
+
+static long *
+get_objstm_data (pdf_obj *objstm) {
+ TYPECHECK(objstm, PDF_STREAM);
+
+ return ((pdf_stream *) objstm->data)->objstm_data;
+}
+
+void
+pdf_add_stream (pdf_obj *stream, const void *stream_data, long length)
+{
+ pdf_stream *data;
+
+ TYPECHECK(stream, PDF_STREAM);
+
+ if (length < 1)
+ return;
+ data = stream->data;
+ if (data->stream_length + length > data->max_length) {
+ data->max_length += length + STREAM_ALLOC_SIZE;
+ data->stream = RENEW(data->stream, data->max_length, unsigned char);
+ }
+ memcpy(data->stream + data->stream_length, stream_data, length);
+ data->stream_length += length;
+}
+
+#if HAVE_ZLIB
+#define WBUF_SIZE 4096
+int
+pdf_add_stream_flate (pdf_obj *dst, const void *data, long len)
+{
+ z_stream z;
+ Bytef wbuf[WBUF_SIZE];
+
+ z.zalloc = Z_NULL; z.zfree = Z_NULL; z.opaque = Z_NULL;
+
+ z.next_in = (Bytef *) data; z.avail_in = len;
+ z.next_out = (Bytef *) wbuf; z.avail_out = WBUF_SIZE;
+
+ if (inflateInit(&z) != Z_OK) {
+ WARN("inflateInit() failed.");
+ return -1;
+ }
+
+ for (;;) {
+ int status;
+ status = inflate(&z, Z_NO_FLUSH);
+ if (status == Z_STREAM_END)
+ break;
+ else if (status != Z_OK) {
+ WARN("inflate() failed. Broken PDF file?");
+ inflateEnd(&z);
+ return -1;
+ }
+
+ if (z.avail_out == 0) {
+ pdf_add_stream(dst, wbuf, WBUF_SIZE);
+ z.next_out = wbuf;
+ z.avail_out = WBUF_SIZE;
+ }
+ }
+
+ if (WBUF_SIZE - z.avail_out > 0)
+ pdf_add_stream(dst, wbuf, WBUF_SIZE - z.avail_out);
+
+ return (inflateEnd(&z) == Z_OK ? 0 : -1);
+}
+#endif
+
+
+int
+pdf_concat_stream (pdf_obj *dst, pdf_obj *src)
+{
+ const char *stream_data;
+ long stream_length;
+ pdf_obj *stream_dict;
+ pdf_obj *filter;
+
+ if (!PDF_OBJ_STREAMTYPE(dst) || !PDF_OBJ_STREAMTYPE(src))
+ ERROR("Invalid type.");
+
+ stream_data = pdf_stream_dataptr(src);
+ stream_length = pdf_stream_length (src);
+ stream_dict = pdf_stream_dict (src);
+
+ if (pdf_lookup_dict(stream_dict, "DecodeParms")) {
+ WARN("Streams with DecodeParams not supported.");
+ return -1;
+ }
+
+ filter = pdf_lookup_dict(stream_dict, "Filter");
+ if (!filter) {
+ pdf_add_stream(dst, stream_data, stream_length);
+ return 0;
+#if HAVE_ZLIB
+ } else {
+ char *filter_name;
+ if (PDF_OBJ_NAMETYPE(filter)) {
+ filter_name = pdf_name_value(filter);
+ if (filter_name && !strcmp(filter_name, "FlateDecode"))
+ return pdf_add_stream_flate(dst, stream_data, stream_length);
+ else {
+ WARN("DecodeFilter \"%s\" not supported.", filter_name);
+ return -1;
+ }
+ } else if (PDF_OBJ_ARRAYTYPE(filter)) {
+ if (pdf_array_length(filter) > 1) {
+ WARN("Multiple DecodeFilter not supported.");
+ return -1;
+ } else {
+ filter_name = pdf_name_value(pdf_get_array(filter, 0));
+ if (filter_name && !strcmp(filter_name, "FlateDecode"))
+ return pdf_add_stream_flate(dst, stream_data, stream_length);
+ else {
+ WARN("DecodeFilter \"%s\" not supported.", filter_name);
+ return -1;
+ }
+ }
+ } else
+ ERROR("Broken PDF file?");
+#endif /* HAVE_ZLIB */
+ }
+
+ return -1;
+}
+
+static pdf_obj *
+pdf_stream_uncompress (pdf_obj *src) {
+ pdf_obj *dst = pdf_new_stream(0);
+
+ TYPECHECK(src, PDF_STREAM);
+
+ pdf_merge_dict(pdf_stream_dict(dst), pdf_stream_dict(src));
+ pdf_remove_dict(pdf_stream_dict(dst), "Length");
+ pdf_concat_stream(dst, src);
+
+ return dst;
+}
+
+#if 0
+void
+pdf_stream_set_flags (pdf_obj *stream, int flags)
+{
+ pdf_stream *data;
+
+ TYPECHECK(stream, PDF_STREAM);
+
+ data = stream->data;
+ data->_flags = flags;
+}
+
+int
+pdf_stream_get_flags (pdf_obj *stream)
+{
+ pdf_stream *data;
+
+ TYPECHECK(stream, PDF_STREAM);
+
+ data = stream->data;
+
+ return data->_flags;
+}
+#endif /* 0 */
+
+static void
+pdf_write_obj (pdf_obj *object, FILE *file)
+{
+ if (object == NULL) {
+ write_null(NULL, file);
+ return;
+ }
+
+ if (INVALIDOBJ(object))
+ ERROR("pdf_write_obj: Invalid object, type = %d\n", object->type);
+
+ if (file == stderr)
+ fprintf(stderr, "{%d}", object->refcount);
+
+ switch (object->type) {
+ case PDF_BOOLEAN:
+ write_boolean(object->data, file);
+ break;
+ case PDF_NUMBER:
+ write_number (object->data, file);
+ break;
+ case PDF_STRING:
+ write_string (object->data, file);
+ break;
+ case PDF_NAME:
+ write_name(object->data, file);
+ break;
+ case PDF_ARRAY:
+ write_array(object->data, file);
+ break;
+ case PDF_DICT:
+ write_dict (object->data, file);
+ break;
+ case PDF_STREAM:
+ write_stream(object->data, file);
+ break;
+ case PDF_NULL:
+ write_null(NULL, file);
+ break;
+ case PDF_INDIRECT:
+ write_indirect(object->data, file);
+ break;
+ }
+}
+
+/* Write the object to the file */
+static void
+pdf_flush_obj (pdf_obj *object, FILE *file)
+{
+ long length;
+
+ /*
+ * Record file position
+ */
+ add_xref_entry(object->label, 1,
+ pdf_output_file_position, object->generation);
+ length = sprintf(format_buffer, "%lu %hu obj\n", object->label, object->generation);
+ enc_mode = doc_enc_mode && !(object->flags & OBJ_NO_ENCRYPT);
+ pdf_enc_set_label(object->label);
+ pdf_enc_set_generation(object->generation);
+ pdf_out(file, format_buffer, length);
+ pdf_write_obj(object, file);
+ pdf_out(file, "\nendobj\n", 8);
+}
+
+static long
+pdf_add_objstm (pdf_obj *objstm, pdf_obj *object)
+{
+ long *data, pos;
+
+ TYPECHECK(objstm, PDF_STREAM);
+
+ data = get_objstm_data(objstm);
+ pos = ++data[0];
+
+ data[2*pos] = object->label;
+ data[2*pos+1] = pdf_stream_length(objstm);
+
+ add_xref_entry(object->label, 2, objstm->label, pos-1);
+
+ /* redirect output into objstm */
+ output_stream = objstm;
+ enc_mode = 0;
+ pdf_write_obj(object, pdf_output_file);
+ pdf_out_char(pdf_output_file, '\n');
+ output_stream = NULL;
+
+ return pos;
+}
+
+static void
+release_objstm (pdf_obj *objstm)
+{
+ long *data = get_objstm_data(objstm);
+ long pos = data[0];
+ pdf_obj *dict;
+ pdf_stream *stream;
+ unsigned char *old_buf;
+ unsigned long old_length;
+ stream = (pdf_stream *) objstm->data;
+
+ /* Precede stream data by offset table */
+ old_buf = stream->stream;
+ old_length = stream->stream_length;
+ /* Reserve 22 bytes for each entry (two 10 digit numbers plus two spaces) */
+ stream->stream = NEW(old_length + 22*pos, unsigned char);
+ stream->stream_length = 0;
+
+ {
+ long i = 2*pos, *val = data+2;
+ while (i--) {
+ long length = sprintf(format_buffer, "%ld ", *(val++));
+ pdf_add_stream(objstm, format_buffer, length);
+ }
+ }
+
+ dict = pdf_stream_dict(objstm);
+ pdf_add_dict(dict, pdf_new_name("Type"), pdf_new_name("ObjStm"));
+ pdf_add_dict(dict, pdf_new_name("N"), pdf_new_number(pos));
+ pdf_add_dict(dict, pdf_new_name("First"), pdf_new_number(stream->stream_length));
+
+ pdf_add_stream(objstm, old_buf, old_length);
+ RELEASE(old_buf);
+ pdf_release_obj(objstm);
+}
+
+void
+pdf_release_obj (pdf_obj *object)
+{
+ if (object == NULL)
+ return;
+ if (INVALIDOBJ(object) || object->refcount <= 0) {
+ MESG("\npdf_release_obj: object=%p, type=%d, refcount=%d\n",
+ object, object->type, object->refcount);
+ pdf_write_obj(object, stderr);
+ ERROR("pdf_release_obj: Called with invalid object.");
+ }
+ object->refcount -= 1;
+ if (object->refcount == 0) {
+ /*
+ * Nothing is using this object so it's okay to remove it.
+ * Nonzero "label" means object needs to be written before it's destroyed.
+ */
+ if (object->label && pdf_output_file != NULL) {
+ if (!do_objstm || object->flags & OBJ_NO_OBJSTM
+ || (doc_enc_mode && object->flags & OBJ_NO_ENCRYPT)
+ || object->generation)
+ pdf_flush_obj(object, pdf_output_file);
+ else {
+ if (!current_objstm) {
+ long *data = NEW(2*OBJSTM_MAX_OBJS+2, long);
+ data[0] = data[1] = 0;
+ current_objstm = pdf_new_stream(STREAM_COMPRESS);
+ set_objstm_data(current_objstm, data);
+ pdf_label_obj(current_objstm);
+ }
+ if (pdf_add_objstm(current_objstm, object) == OBJSTM_MAX_OBJS) {
+ release_objstm(current_objstm);
+ current_objstm = NULL;
+ }
+ }
+ }
+ switch (object->type) {
+ case PDF_BOOLEAN:
+ release_boolean(object->data);
+ break;
+ case PDF_NULL:
+ release_null(object->data);
+ break;
+ case PDF_NUMBER:
+ release_number(object->data);
+ break;
+ case PDF_STRING:
+ release_string(object->data);
+ break;
+ case PDF_NAME:
+ release_name(object->data);
+ break;
+ case PDF_ARRAY:
+ release_array(object->data);
+ break;
+ case PDF_DICT:
+ release_dict(object->data);
+ break;
+ case PDF_STREAM:
+ release_stream(object->data);
+ break;
+ case PDF_INDIRECT:
+ release_indirect(object->data);
+ break;
+ }
+ /* This might help detect freeing already freed objects */
+ object->type = -1;
+ object->data = NULL;
+ RELEASE(object);
+ }
+}
+
+/* Copy object data without changing object label. */
+void
+pdf_copy_object (pdf_obj *dst, pdf_obj *src)
+{
+ if (!dst || !src)
+ return;
+
+ switch (dst->type) {
+ case PDF_BOOLEAN: release_boolean(dst->data); break;
+ case PDF_NULL: release_null(dst->data); break;
+ case PDF_NUMBER: release_number(dst->data); break;
+ case PDF_STRING: release_string(dst->data); break;
+ case PDF_NAME: release_name(dst->data); break;
+ case PDF_ARRAY: release_array(dst->data); break;
+ case PDF_DICT: release_dict(dst->data); break;
+ case PDF_STREAM: release_stream(dst->data); break;
+ case PDF_INDIRECT: release_indirect(dst->data); break;
+ }
+
+ dst->type = src->type;
+ switch (src->type) {
+ case PDF_BOOLEAN:
+ dst->data = NEW(1, pdf_boolean);
+ pdf_set_boolean(dst, pdf_boolean_value(src));
+ break;
+ case PDF_NULL:
+ dst->data = NULL;
+ break;
+ case PDF_NUMBER:
+ dst->data = NEW(1, pdf_number);
+ pdf_set_number(dst, pdf_number_value(src));
+ break;
+ case PDF_STRING:
+ dst->data = NEW(1, pdf_string);
+ pdf_set_string(dst,
+ pdf_string_value(src),
+ pdf_string_length(src));
+ break;
+ case PDF_NAME:
+ dst->data = NEW(1, pdf_name);
+ pdf_set_name(dst, pdf_name_value(src));
+ break;
+ case PDF_ARRAY:
+ {
+ pdf_array *data;
+ unsigned long i;
+
+ dst->data = data = NEW(1, pdf_array);
+ data->size = 0;
+ data->max = 0;
+ data->values = NULL;
+ for (i = 0; i < pdf_array_length(src); i++) {
+ pdf_add_array(dst, pdf_link_obj(pdf_get_array(src, i)));
+ }
+ }
+ break;
+ case PDF_DICT:
+ {
+ pdf_dict *data;
+
+ dst->data = data = NEW(1, pdf_dict);
+ data->key = NULL;
+ data->value = NULL;
+ data->next = NULL;
+ pdf_merge_dict(dst, src);
+ }
+ break;
+ case PDF_STREAM:
+ {
+ pdf_stream *data;
+
+ dst->data = data = NEW(1, pdf_stream);
+ data->dict = pdf_new_dict();
+ data->_flags = ((pdf_stream *)src->data)->_flags;
+ data->stream_length = 0;
+ data->max_length = 0;
+
+ pdf_add_stream(dst, pdf_stream_dataptr(src), pdf_stream_length(src));
+ pdf_merge_dict(data->dict, pdf_stream_dict(src));
+ }
+ break;
+ case PDF_INDIRECT:
+ {
+ pdf_indirect *data;
+
+ dst->data = data = NEW(1, pdf_indirect);
+ data->pf = ((pdf_indirect *) (src->data))->pf;
+ data->label = ((pdf_indirect *) (src->data))->label;
+ data->generation = ((pdf_indirect *) (src->data))->generation;
+ }
+ break;
+ }
+
+ return;
+}
+
+static int
+backup_line (FILE *pdf_input_file)
+{
+ int ch = -1;
+
+ /*
+ * Note: this code should work even if \r\n is eol. It could fail on a
+ * machine where \n is eol and there is a \r in the stream --- Highly
+ * unlikely in the last few bytes where this is likely to be used.
+ */
+ if (tell_position(pdf_input_file) > 1)
+ do {
+ seek_relative (pdf_input_file, -2);
+ } while (tell_position(pdf_input_file) > 0 &&
+ (ch = fgetc(pdf_input_file)) >= 0 &&
+ (ch != '\n' && ch != '\r' ));
+ if (ch < 0) {
+ return 0;
+ }
+
+ return 1;
+}
+
+static long
+find_xref (FILE *pdf_input_file)
+{
+ long xref_pos;
+ int tries = 10;
+
+ do {
+ long currentpos;
+
+ if (!backup_line(pdf_input_file)) {
+ tries = 0;
+ break;
+ }
+ currentpos = tell_position(pdf_input_file);
+ fread(work_buffer, sizeof(char), strlen("startxref"), pdf_input_file);
+ seek_absolute(pdf_input_file, currentpos);
+ tries--;
+ } while (tries > 0 &&
+ strncmp(work_buffer, "startxref", strlen("startxref")));
+ if (tries <= 0)
+ return 0;
+
+ /* Skip rest of this line */
+ mfgets(work_buffer, WORK_BUFFER_SIZE, pdf_input_file);
+ /* Next line of input file should contain actual xref location */
+ mfgets(work_buffer, WORK_BUFFER_SIZE, pdf_input_file);
+
+ {
+ const char *start, *end;
+ char *number;
+
+ start = work_buffer;
+ end = start + strlen(work_buffer);
+ skip_white(&start, end);
+ number = parse_number(&start, end);
+ xref_pos = (long) atof(number);
+ RELEASE(number);
+ }
+
+ return xref_pos;
+}
+
+/*
+ * This routine must be called with the file pointer located
+ * at the start of the trailer.
+ */
+static pdf_obj *
+parse_trailer (pdf_file *pf)
+{
+ pdf_obj *result;
+ /*
+ * Fill work_buffer and hope trailer fits. This should
+ * be made a bit more robust sometime.
+ */
+ if (fread(work_buffer, sizeof(char),
+ WORK_BUFFER_SIZE, pf->file) == 0 ||
+ strncmp(work_buffer, "trailer", strlen("trailer"))) {
+ WARN("No trailer. Are you sure this is a PDF file?");
+ WARN("buffer:\n->%s<-\n", work_buffer);
+ result = NULL;
+ } else {
+ const char *p = work_buffer + strlen("trailer");
+ skip_white(&p, work_buffer + WORK_BUFFER_SIZE);
+ result = parse_pdf_dict(&p, work_buffer + WORK_BUFFER_SIZE, pf);
+ }
+
+ return result;
+}
+
+/*
+ * This routine tries to estimate an upper bound for character position
+ * of the end of the object, so it knows how big the buffer must be.
+ * The parsing routines require that the entire object be read into
+ * memory. It would be a major pain to rewrite them. The worst case
+ * is that an object before an xref table will grab the whole table
+ * :-(
+ */
+static long
+next_object_offset (pdf_file *pf, unsigned long obj_num)
+{
+ long next = pf->file_size; /* Worst case */
+ long i, curr;
+
+ curr = pf->xref_table[obj_num].field2;
+ /* Check all other type 1 objects to find next one */
+ for (i = 0; i < pf->num_obj; i++) {
+ if (pf->xref_table[i].type == 1 &&
+ pf->xref_table[i].field2 > curr &&
+ pf->xref_table[i].field2 < next)
+ next = pf->xref_table[i].field2;
+ }
+
+ return next;
+}
+
+#define checklabel(pf, n, g) ((n) > 0 && (n) < (pf)->num_obj && ( \
+ ((pf)->xref_table[(n)].type == 1 && (pf)->xref_table[(n)].field3 == (g)) || \
+ ((pf)->xref_table[(n)].type == 2 && !(g))))
+
+pdf_obj *
+pdf_new_indirect (pdf_file *pf, unsigned long obj_num, unsigned short obj_gen)
+{
+ pdf_obj *result;
+ pdf_indirect *indirect;
+
+ indirect = NEW(1, pdf_indirect);
+ indirect->pf = pf;
+ indirect->label = obj_num;
+ indirect->generation = obj_gen;
+
+ result = pdf_new_obj(PDF_INDIRECT);
+ result->data = indirect;
+
+ return result;
+}
+
+static pdf_obj *
+pdf_read_object (unsigned long obj_num, unsigned short obj_gen,
+ pdf_file *pf, long offset, long limit)
+{
+ long length;
+ char *buffer;
+ const char *p, *endptr;
+ pdf_obj *result;
+
+ length = limit - offset;
+
+ if (length <= 0)
+ return NULL;
+
+ buffer = NEW(length + 1, char);
+
+ seek_absolute(pf->file, offset);
+ fread(buffer, sizeof(char), length, pf->file);
+
+ p = buffer;
+ endptr = p + length;
+
+ /* Check for obj_num and obj_gen */
+ {
+ const char *q = p; /* <== p */
+ char *sp;
+ unsigned long n, g;
+
+ skip_white(&q, endptr);
+ sp = parse_unsigned(&q, endptr);
+ if (!sp) {
+ RELEASE(buffer);
+ return NULL;
+ }
+ n = strtoul(sp, NULL, 10);
+ RELEASE(sp);
+
+ skip_white(&q, endptr);
+ sp = parse_unsigned(&q, endptr);
+ if (!sp) {
+ RELEASE(buffer);
+ return NULL;
+ }
+ g = strtoul(sp, NULL, 10);
+ RELEASE(sp);
+
+ if (obj_num && (n != obj_num || g != obj_gen)) {
+ RELEASE(buffer);
+ return NULL;
+ }
+
+ p = q; /* ==> p */
+ }
+
+
+ skip_white(&p, endptr);
+ if (memcmp(p, "obj", strlen("obj"))) {
+ WARN("Didn't find \"obj\".");
+ RELEASE(buffer);
+ return NULL;
+ }
+ p += strlen("obj");
+
+ result = parse_pdf_object(&p, endptr, pf);
+
+ skip_white(&p, endptr);
+ if (memcmp(p, "endobj", strlen("endobj"))) {
+ WARN("Didn't find \"endobj\".");
+ if (result)
+ pdf_release_obj(result);
+ result = NULL;
+ }
+ RELEASE(buffer);
+
+ return result;
+}
+
+static pdf_obj *
+read_objstm (pdf_file *pf, unsigned long num)
+{
+ unsigned long offset = pf->xref_table[num].field2;
+ unsigned short gen = pf->xref_table[num].field3;
+ long limit = next_object_offset(pf, num), n, first, *header = NULL;
+ char *data = NULL, *q;
+ const char *p, *endptr;
+ int i;
+
+ pdf_obj *objstm, *dict, *type, *n_obj, *first_obj;
+
+ objstm = pdf_read_object(num, gen, pf, offset, limit);
+
+ if (!PDF_OBJ_STREAMTYPE(objstm))
+ goto error;
+
+ {
+ pdf_obj *tmp = pdf_stream_uncompress(objstm);
+ if (!tmp)
+ goto error;
+ pdf_release_obj(objstm);
+ objstm = tmp;
+ }
+
+ dict = pdf_stream_dict(objstm);
+
+ type = pdf_lookup_dict(dict, "Type");
+ if (!PDF_OBJ_NAMETYPE(type) ||
+ strcmp(pdf_name_value(type), "ObjStm"))
+ goto error;
+
+ n_obj = pdf_lookup_dict(dict, "N");
+ if (!PDF_OBJ_NUMBERTYPE(n_obj))
+ goto error;
+ n = (long) pdf_number_value(n_obj);
+
+ first_obj = pdf_lookup_dict(dict, "First");
+ if (!PDF_OBJ_NUMBERTYPE(first_obj))
+ goto error;
+ first = (long) pdf_number_value(first_obj);
+ /* reject object streams without object data */
+ if (first >= pdf_stream_length(objstm))
+ goto error;
+
+ header = NEW(2*(n+1), long);
+ set_objstm_data(objstm, header);
+ *(header++) = n;
+ *(header++) = first;
+
+ /* avoid parsing beyond offset table */
+ data = NEW(first + 1, char);
+ memcpy(data, pdf_stream_dataptr(objstm), first);
+ data[first] = 0;
+
+ p = data;
+ endptr = p + first;
+ i = 2*n;
+ while (i--) {
+ *(header++) = strtoul(p, &q, 10);
+ if (q == p)
+ goto error;
+ p = q;
+ }
+
+ /* Any garbage after last entry? */
+ skip_white(&p, endptr);
+ if (p != endptr)
+ goto error;
+ RELEASE(data);
+
+ return pf->xref_table[num].direct = objstm;
+
+ error:
+ WARN("Cannot parse object stream.");
+ if (data)
+ RELEASE(data);
+ if (objstm)
+ pdf_release_obj(objstm);
+ return NULL;
+}
+
+/* Label without corresponding object definition are replaced by the
+ * null object, as required by the PDF spec. This is important to parse
+ * several cross-reference sections.
+ */
+static pdf_obj *
+pdf_get_object (pdf_file *pf, unsigned long obj_num, unsigned short obj_gen)
+{
+ pdf_obj *result;
+
+ if (!checklabel(pf, obj_num, obj_gen)) {
+ WARN("Trying to read nonexistent or deleted object: %lu %u",
+ obj_num, obj_gen);
+ return pdf_new_null();
+ }
+
+ if ((result = pf->xref_table[obj_num].direct)) {
+ return pdf_link_obj(result);
+ }
+
+ if (pf->xref_table[obj_num].type == 1) {
+ /* type == 1 */
+ unsigned long offset;
+ long limit;
+ offset = pf->xref_table[obj_num].field2;
+ limit = next_object_offset(pf, obj_num);
+ result = pdf_read_object(obj_num, obj_gen, pf, offset, limit);
+ } else {
+ /* type == 2 */
+ unsigned long objstm_num = pf->xref_table[obj_num].field2;
+ unsigned short index = pf->xref_table[obj_num].field3;
+ pdf_obj *objstm;
+ long *data, n, first, length;
+ const char *p, *q;
+
+ if (objstm_num >= pf->num_obj ||
+ pf->xref_table[objstm_num].type != 1 ||
+ !((objstm = pf->xref_table[objstm_num].direct) ||
+ (objstm = read_objstm(pf, objstm_num))))
+ goto error;
+
+ data = get_objstm_data(objstm);
+ n = *(data++);
+ first = *(data++);
+
+ if (index >= n || data[2*index] != obj_num)
+ goto error;
+
+ length = pdf_stream_length(objstm);
+ p = (const char *) pdf_stream_dataptr(objstm) + first + data[2*index+1];
+ q = p + (index == n-1 ? length : first+data[2*index+3]);
+ result = parse_pdf_object(&p, q, pf);
+ if (!result)
+ goto error;
+ }
+
+ /* Make sure the caller doesn't free this object */
+ pf->xref_table[obj_num].direct = pdf_link_obj(result);
+
+ return result;
+
+ error:
+ WARN("Could not read object from object stream.");
+ return pdf_new_null();
+}
+
+#define OBJ_FILE(o) (((pdf_indirect *)((o)->data))->pf)
+#define OBJ_NUM(o) (((pdf_indirect *)((o)->data))->label)
+#define OBJ_GEN(o) (((pdf_indirect *)((o)->data))->generation)
+
+/* pdf_deref_obj always returns a link instead of the original */
+/* It never return the null object, but the NULL pointer instead */
+pdf_obj *
+pdf_deref_obj (pdf_obj *obj)
+{
+ if (obj)
+ obj = pdf_link_obj(obj);
+
+ while (PDF_OBJ_INDIRECTTYPE(obj)) {
+ pdf_file *pf = OBJ_FILE(obj);
+ unsigned long obj_num = OBJ_NUM(obj);
+ unsigned short obj_gen = OBJ_GEN(obj);
+ if (!pf)
+ ERROR("Tried to deref a non-file object");
+ pdf_release_obj(obj);
+ obj = pdf_get_object(pf, obj_num, obj_gen);
+ }
+
+ if (PDF_OBJ_NULLTYPE(obj)) {
+ pdf_release_obj(obj);
+ return NULL;
+ } else
+ return obj;
+}
+
+static void
+extend_xref (pdf_file *pf, long new_size)
+{
+ unsigned long i;
+
+ pf->xref_table = RENEW(pf->xref_table, new_size, xref_entry);
+ for (i = pf->num_obj; i < new_size; i++) {
+ pf->xref_table[i].direct = NULL;
+ pf->xref_table[i].indirect = NULL;
+ pf->xref_table[i].type = 0;
+ pf->xref_table[i].field3 = 0;
+ pf->xref_table[i].field2 = 0L;
+ }
+ pf->num_obj = new_size;
+}
+
+static int
+parse_xref_table (pdf_file *pf, long xref_pos)
+{
+ FILE *pdf_input_file = pf->file;
+ unsigned long first, size;
+ unsigned long i, offset;
+ unsigned int obj_gen;
+ char flag;
+ int r;
+
+ /*
+ * This routine reads one xref segment. It may be called multiple times
+ * on the same file. xref tables sometimes come in pieces.
+ */
+
+ seek_absolute(pf->file, xref_pos);
+
+ mfgets(work_buffer, WORK_BUFFER_SIZE, pdf_input_file);
+ if (memcmp(work_buffer, "xref", strlen("xref"))) {
+ /* Might be an xref stream and not an xref table */
+ return 0;
+ }
+ /* Next line in file has first item and size of table */
+ for (;;) {
+ unsigned long current_pos;
+
+ current_pos = tell_position(pdf_input_file);
+ if (mfgets(work_buffer, WORK_BUFFER_SIZE, pdf_input_file) == NULL) {
+ WARN("Premature end of PDF file while parsing xref table.");
+ return -1;
+ }
+ if (!strncmp(work_buffer, "trailer", strlen ("trailer"))) {
+ /*
+ * Backup... This is ugly, but it seems like the safest thing to
+ * do. It is possible the trailer dictionary starts on the same
+ * logical line as the word trailer. In that case, the mfgets
+ * call might have started to read the trailer dictionary and
+ * parse_trailer would fail.
+ */
+ seek_absolute(pdf_input_file, current_pos);
+ break;
+ }
+ sscanf(work_buffer, "%lu %lu", &first, &size);
+ if (pf->num_obj < first + size) {
+ extend_xref(pf, first + size);
+ }
+
+ for (i = first; i < first + size; i++) {
+ fread(work_buffer, sizeof(char), 20, pdf_input_file);
+ /*
+ * Don't overwrite positions that have already been set by a
+ * modified xref table. We are working our way backwards
+ * through the reference table, so we only set "position"
+ * if it hasn't been set yet.
+ */
+ work_buffer[19] = 0;
+ offset = 0UL; obj_gen = 0; flag = 0;
+ r = sscanf(work_buffer, "%010lu %05u %c", &offset, &obj_gen, &flag);
+ if ( r != 3 ||
+ ((flag != 'n' && flag != 'f') ||
+ (flag == 'n' &&
+ (offset >= pf->file_size || (offset > 0 && offset < 4))))) {
+ WARN("Invalid xref table entry [%lu]. PDF file is corrupt...", i);
+ return -1;
+ }
+ if (!pf->xref_table[i].field2) {
+ pf->xref_table[i].type = (flag == 'n');
+ pf->xref_table[i].field2 = offset;
+ pf->xref_table[i].field3 = obj_gen;
+ }
+ }
+ }
+
+ return 1;
+}
+
+static unsigned long
+parse_xrefstm_field (const char **p, int length, unsigned long def)
+{
+ unsigned long val = 0;
+
+ if (!length)
+ return def;
+
+ while (length--) {
+ val <<= 8;
+ val |= (unsigned char) *((*p)++);
+ }
+
+ return val;
+}
+
+static int
+parse_xrefstm_subsec (pdf_file *pf,
+ const char **p, long *length,
+ int *W, int wsum,
+ long first, long size) {
+ xref_entry *e;
+
+ if ((*length -= wsum*size) < 0)
+ return -1;
+
+ if (pf->num_obj < first+size)
+ extend_xref(pf, first+size); /* TODO: change! why? */
+
+ e = pf->xref_table + first;
+ while (size--) {
+ unsigned char type;
+ unsigned long field2;
+ unsigned short field3;
+
+ type = (unsigned char) parse_xrefstm_field(p, W[0], 1);
+ if (type > 2)
+ WARN("Unknown cross-reference stream entry type.");
+ else if (!W[1] || (type != 1 && !W[2]))
+ return -1;
+
+ field2 = (unsigned long) parse_xrefstm_field(p, W[1], 0);
+ field3 = (unsigned short) parse_xrefstm_field(p, W[2], 0);
+
+ if (!e->field2) {
+ e->type = type;
+ e->field2 = field2;
+ e->field3 = field3;
+ }
+ e++;
+ }
+
+ return 0;
+}
+
+static int
+parse_xref_stream (pdf_file *pf, long xref_pos, pdf_obj **trailer)
+{
+ pdf_obj *xrefstm, *size_obj, *W_obj, *index;
+ unsigned long size;
+ long length;
+ int W[3], i, wsum = 0;
+ const char *p;
+
+ xrefstm = pdf_read_object(0, 0, pf, xref_pos, pf->file_size);
+ if (!PDF_OBJ_STREAMTYPE(xrefstm))
+ goto error;
+
+ {
+ pdf_obj *tmp = pdf_stream_uncompress(xrefstm);
+ if (!tmp)
+ goto error;
+ pdf_release_obj(xrefstm);
+ xrefstm = tmp;
+ }
+
+ *trailer = pdf_link_obj(pdf_stream_dict(xrefstm));
+
+ size_obj = pdf_lookup_dict(*trailer, "Size");
+ if (!PDF_OBJ_NUMBERTYPE(size_obj))
+ goto error;
+ size = (unsigned long) pdf_number_value(size_obj);
+
+ length = pdf_stream_length(xrefstm);
+
+ W_obj = pdf_lookup_dict(*trailer, "W");
+ if (!PDF_OBJ_ARRAYTYPE(W_obj) || pdf_array_length(W_obj) != 3)
+ goto error;
+
+ for (i = 0; i < 3; i++) {
+ pdf_obj *tmp = pdf_get_array(W_obj, i);
+ if (!PDF_OBJ_NUMBERTYPE(tmp))
+ goto error;
+ wsum += (W[i] = (int) pdf_number_value(tmp));
+ }
+
+ p = pdf_stream_dataptr(xrefstm);
+
+ index = pdf_lookup_dict(*trailer, "Index");
+ if (index) {
+ unsigned int index_len;
+ if (!PDF_OBJ_ARRAYTYPE(index) ||
+ ((index_len = pdf_array_length(index)) % 2 ))
+ goto error;
+
+ i = 0;
+ while (i < index_len) {
+ pdf_obj *first = pdf_get_array(index, i++);
+ size_obj = pdf_get_array(index, i++);
+ if (!PDF_OBJ_NUMBERTYPE(first) ||
+ !PDF_OBJ_NUMBERTYPE(size_obj) ||
+ parse_xrefstm_subsec(pf, &p, &length, W, wsum,
+ (long) pdf_number_value(first),
+ (long) pdf_number_value(size_obj)))
+ goto error;
+ }
+ } else if (parse_xrefstm_subsec(pf, &p, &length, W, wsum, 0, size))
+ goto error;
+
+ if (length)
+ WARN("Garbage in xref stream.");
+
+ pdf_release_obj(xrefstm);
+
+ return 1;
+
+ error:
+ WARN("Cannot parse cross-reference stream.");
+ if (xrefstm)
+ pdf_release_obj(xrefstm);
+ if (*trailer) {
+ pdf_release_obj(*trailer);
+ *trailer = NULL;
+ }
+ return 0;
+}
+
+/* TODO: parse Version entry */
+static pdf_obj *
+read_xref (pdf_file *pf)
+{
+ pdf_obj *trailer = NULL, *main_trailer = NULL;
+ long xref_pos;
+
+ if (!(xref_pos = find_xref(pf->file)))
+ goto error;
+
+ while (xref_pos) {
+ pdf_obj *prev;
+
+ int res = parse_xref_table(pf, xref_pos);
+ if (res > 0) {
+ /* cross-reference table */
+ pdf_obj *xrefstm;
+
+ if (!(trailer = parse_trailer(pf)))
+ goto error;
+
+ if (!main_trailer)
+ main_trailer = pdf_link_obj(trailer);
+
+ if ((xrefstm = pdf_lookup_dict(trailer, "XRefStm"))) {
+ pdf_obj *new_trailer = NULL;
+ if (PDF_OBJ_NUMBERTYPE(xrefstm) &&
+ parse_xref_stream(pf, (long) pdf_number_value(xrefstm),
+ &new_trailer))
+ pdf_release_obj(new_trailer);
+ else
+ WARN("Skipping hybrid reference section.");
+ /* Many PDF 1.5 xref streams use DecodeParms, which we cannot
+ parse. This way we can use at least xref tables in hybrid
+ documents. Or should we better stop parsing the file?
+ */
+ }
+
+ } else if (!res && parse_xref_stream(pf, xref_pos, &trailer)) {
+ /* cross-reference stream */
+ if (!main_trailer)
+ main_trailer = pdf_link_obj(trailer);
+ } else
+ goto error;
+
+ if ((prev = pdf_lookup_dict(trailer, "Prev"))) {
+ if (PDF_OBJ_NUMBERTYPE(prev))
+ xref_pos = (long) pdf_number_value(prev);
+ else
+ goto error;
+ } else
+ xref_pos = 0;
+
+ pdf_release_obj(trailer);
+ }
+
+#if 0
+ if (!pdf_lookup_dict(main_trailer, "Root")) {
+ WARN("Trailer doesn't have catalog. Is this a correct PDF file?");
+ goto error;
+ }
+#endif
+
+ return main_trailer;
+
+ error:
+ WARN("Error while parsing PDF file.");
+ if (trailer)
+ pdf_release_obj(trailer);
+ if (main_trailer)
+ pdf_release_obj(main_trailer);
+ return NULL;
+}
+
+static struct ht_table *pdf_files = NULL;
+
+static pdf_file *
+pdf_file_new (FILE *file)
+{
+ pdf_file *pf;
+ ASSERT(file);
+ pf = NEW(1, pdf_file);
+ pf->file = file;
+ pf->trailer = NULL;
+ pf->xref_table = NULL;
+ pf->num_obj = 0;
+ pf->version = 0;
+
+ seek_end(file);
+ pf->file_size = tell_position(file);
+
+ return pf;
+}
+
+static void
+pdf_file_free (pdf_file *pf)
+{
+ unsigned long i;
+
+ if (!pf) {
+ return;
+ }
+
+ for (i = 0; i < pf->num_obj; i++) {
+ if (pf->xref_table[i].direct)
+ pdf_release_obj(pf->xref_table[i].direct);
+ if (pf->xref_table[i].indirect)
+ pdf_release_obj(pf->xref_table[i].indirect);
+ }
+
+ RELEASE(pf->xref_table);
+ pdf_release_obj(pf->trailer);
+
+ RELEASE(pf);
+}
+
+void
+pdf_files_init (void)
+{
+ pdf_files = NEW(1, struct ht_table);
+ ht_init_table(pdf_files, (void (*)(void *)) pdf_file_free);
+}
+
+pdf_obj *
+pdf_file_get_trailer (pdf_file *pf)
+{
+ ASSERT(pf);
+ return pdf_link_obj(pf->trailer);
+}
+
+pdf_file *
+pdf_open (char *ident, FILE *file)
+{
+ pdf_file *pf = NULL;
+
+ ASSERT(pdf_files);
+
+ if (ident)
+ pf = (pdf_file *) ht_lookup_table(pdf_files, ident, strlen(ident));
+
+ if (pf) {
+ pf->file = file;
+ } else {
+ int version = check_for_pdf(file);
+ if (!version) {
+ WARN("pdf_open: Not a PDF 1.[1-5] file.");
+ return NULL;
+ }
+
+ pf = pdf_file_new(file);
+ pf->version = version;
+
+ if (!(pf->trailer = read_xref(pf))) {
+ pdf_file_free(pf);
+ return NULL;
+ }
+
+ if (ident)
+ ht_append_table(pdf_files, ident, strlen(ident), pf);
+ }
+
+ return pf;
+}
+
+void
+pdf_close (pdf_file *pf)
+{
+ if (pf)
+ pf->file = NULL;
+}
+
+void
+pdf_files_close (void)
+{
+ ASSERT(pdf_files);
+ ht_clear_table(pdf_files);
+ RELEASE(pdf_files);
+}
+
+int
+check_for_pdf (FILE *file)
+{
+ int result = 0;
+
+ rewind(file);
+ if (fread(work_buffer, sizeof(char), strlen("%PDF-1.x"), file) ==
+ strlen("%PDF-1.x") &&
+ !strncmp(work_buffer, "%PDF-1.", strlen("%PDF-1."))) {
+ if (work_buffer[7] >= '0' && work_buffer[7] <= '0' + pdf_version)
+ result = 1;
+ else {
+ WARN("Version of PDF file (1.%c) is newer than version limit specification.",
+ work_buffer[7]);
+ }
+ }
+
+ return result;
+}
+
+static int CDECL
+import_dict (pdf_obj *key, pdf_obj *value, void *pdata)
+{
+ pdf_obj *copy;
+ pdf_obj *tmp;
+
+ copy = (pdf_obj *) pdata;
+
+ tmp = pdf_import_object(value);
+ if (!tmp) {
+ return -1;
+ }
+ pdf_add_dict(copy, pdf_link_obj(key), tmp);
+
+ return 0;
+}
+
+static pdf_obj *
+pdf_import_indirect (pdf_obj *object)
+{
+ pdf_file *pf = OBJ_FILE(object);
+ unsigned long obj_num = OBJ_NUM(object);
+ unsigned short obj_gen = OBJ_GEN(object);
+
+ pdf_obj *ref;
+
+ ASSERT(pf);
+
+ if (!checklabel(pf, obj_num, obj_gen)) {
+ WARN("Can't resolve object: %lu %u", obj_num, obj_gen);
+ return pdf_new_null();
+ }
+
+ if ((ref = pf->xref_table[obj_num].indirect)) {
+ return pdf_link_obj(ref);
+ } else {
+ pdf_obj *obj, *tmp;
+
+ obj = pdf_get_object(pf, obj_num, obj_gen);
+ if (!obj) {
+ WARN("Could not read object: %lu %u", obj_num, obj_gen);
+ return NULL;
+ }
+
+ tmp = pdf_import_object(obj);
+
+ pf->xref_table[obj_num].indirect = ref = pdf_ref_obj(tmp);
+
+ pdf_release_obj(tmp);
+ pdf_release_obj(obj);
+
+ return pdf_link_obj(ref);
+ }
+}
+
+/*
+ * pdf_import_object recursively copies the object and those
+ * referenced by it and changes the indirect references so that
+ * they refer to the current output file. New indirect references
+ * are remembered, which avoids duplicating objects when they
+ * are imported several times.
+ */
+pdf_obj *
+pdf_import_object (pdf_obj *object)
+{
+ pdf_obj *imported;
+ pdf_obj *tmp;
+ int i;
+
+ switch (pdf_obj_typeof(object)) {
+
+ case PDF_INDIRECT:
+ if (OBJ_FILE(object)) {
+ imported = pdf_import_indirect(object);
+ } else {
+ imported = pdf_link_obj(object);
+ }
+ break;
+
+ case PDF_STREAM:
+ {
+ pdf_obj *stream_dict;
+
+ tmp = pdf_import_object(pdf_stream_dict(object));
+ if (!tmp)
+ return NULL;
+
+ imported = pdf_new_stream(0);
+ stream_dict = pdf_stream_dict(imported);
+ pdf_merge_dict(stream_dict, tmp);
+ pdf_release_obj(tmp);
+ pdf_add_stream(imported,
+ pdf_stream_dataptr(object),
+ pdf_stream_length(object));
+ }
+ break;
+
+ case PDF_DICT:
+
+ imported = pdf_new_dict();
+ if (pdf_foreach_dict(object, import_dict, imported) < 0) {
+ pdf_release_obj(imported);
+ return NULL;
+ }
+
+ break;
+
+ case PDF_ARRAY:
+
+ imported = pdf_new_array();
+ for (i = 0; i < pdf_array_length(object); i++) {
+ tmp = pdf_import_object(pdf_get_array(object, i));
+ if (!tmp) {
+ pdf_release_obj(imported);
+ return NULL;
+ }
+ pdf_add_array(imported, tmp);
+ }
+ break;
+
+ default:
+ imported = pdf_link_obj(object);
+ }
+
+ return imported;
+}
+
+
+int
+pdf_compare_reference (pdf_obj *ref1, pdf_obj *ref2)
+{
+ pdf_indirect *data1, *data2;
+
+ if (!PDF_OBJ_INDIRECTTYPE(ref1) ||
+ !PDF_OBJ_INDIRECTTYPE(ref2)) {
+ ERROR("Not indirect reference...");
+ }
+
+ data1 = (pdf_indirect *) ref1->data;
+ data2 = (pdf_indirect *) ref2->data;
+
+ if (data1->pf != data2->pf)
+ return (int) (data1->pf - data2->pf);
+ if (data1->label != data2->label)
+ return (int) (data1->label - data2->label);
+ if (data1->generation != data2->generation)
+ return (int) (data1->generation - data2->generation);
+
+ return 0;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/pdfobj.h b/Build/source/texk/dvipdf-x/xsrc/pdfobj.h
new file mode 100644
index 00000000000..036e9f53ef4
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pdfobj.h
@@ -0,0 +1,196 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2007-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _PDFOBJ_H_
+#define _PDFOBJ_H_
+
+#include <stdio.h>
+
+/* Here is the complete list of PDF object types */
+
+#define PDF_BOOLEAN 1
+#define PDF_NUMBER 2
+#define PDF_STRING 3
+#define PDF_NAME 4
+#define PDF_ARRAY 5
+#define PDF_DICT 6
+#define PDF_STREAM 7
+#define PDF_NULL 8
+#define PDF_INDIRECT 9
+
+#define PDF_OBJ_INVALID 0
+#define PDF_UNDEFINED PDF_OBJ_INVALID
+
+#define STREAM_COMPRESS (1 << 0)
+
+typedef struct pdf_obj pdf_obj;
+typedef struct pdf_file pdf_file;
+
+/* External interface to pdf routines */
+
+extern int pdf_obj_get_verbose (void);
+extern void pdf_obj_set_verbose (void);
+extern void pdf_error_cleanup (void);
+
+extern void pdf_out_init (const char *filename, int do_encryption);
+extern void pdf_out_flush (void);
+extern void pdf_set_version (unsigned version);
+extern unsigned pdf_get_version (void);
+
+extern pdf_obj *pdf_new_obj (int type);
+extern void pdf_release_obj (pdf_obj *object);
+extern int pdf_obj_typeof (pdf_obj *object);
+
+#define PDF_OBJ_NUMBERTYPE(o) ((o) && pdf_obj_typeof((o)) == PDF_NUMBER)
+#define PDF_OBJ_BOOLEANTYPE(o) ((o) && pdf_obj_typeof((o)) == PDF_BOOLEAN)
+#define PDF_OBJ_STRINGTYPE(o) ((o) && pdf_obj_typeof((o)) == PDF_STRING)
+#define PDF_OBJ_NAMETYPE(o) ((o) && pdf_obj_typeof((o)) == PDF_NAME)
+#define PDF_OBJ_ARRAYTYPE(o) ((o) && pdf_obj_typeof((o)) == PDF_ARRAY)
+#define PDF_OBJ_NULLTYPE(o) ((o) && pdf_obj_typeof((o)) == PDF_NULL)
+#define PDF_OBJ_DICTTYPE(o) ((o) && pdf_obj_typeof((o)) == PDF_DICT)
+#define PDF_OBJ_STREAMTYPE(o) ((o) && pdf_obj_typeof((o)) == PDF_STREAM)
+#define PDF_OBJ_INDIRECTTYPE(o) ((o) && pdf_obj_typeof((o)) == PDF_INDIRECT)
+
+#define PDF_OBJ_TYPEOF(o) pdf_obj_typeof((o))
+
+
+extern pdf_obj *pdf_ref_obj (pdf_obj *object);
+extern pdf_obj *pdf_link_obj (pdf_obj *object);
+
+extern pdf_obj *pdf_new_null (void);
+
+extern pdf_obj *pdf_new_boolean (char value);
+extern void pdf_set_boolean (pdf_obj *object, char value);
+extern char pdf_boolean_value (pdf_obj *object);
+
+extern pdf_obj *pdf_new_number (double value);
+extern void pdf_set_number (pdf_obj *object, double value);
+extern double pdf_number_value (pdf_obj *number);
+
+extern pdf_obj *pdf_new_string (const void *str, unsigned length);
+extern void pdf_set_string (pdf_obj *object, unsigned char *str, unsigned length);
+extern void *pdf_string_value (pdf_obj *object);
+extern unsigned pdf_string_length (pdf_obj *object);
+
+/* Name does not include the / */
+extern pdf_obj *pdf_new_name (const char *name);
+extern void pdf_set_name (pdf_obj *object, const char *name);
+extern char *pdf_name_value (pdf_obj *object);
+
+extern pdf_obj *pdf_new_array (void);
+/* pdf_add_dict requires key but pdf_add_array does not.
+ * pdf_add_array always append elements to array.
+ * They should be pdf_put_array(array, idx, element) and
+ * pdf_put_dict(dict, key, value)
+ */
+extern void pdf_add_array (pdf_obj *array, pdf_obj *object);
+#if 0
+extern void pdf_put_array (pdf_obj *array, unsigned idx, pdf_obj *object);
+#endif /* 0 */
+extern pdf_obj *pdf_get_array (pdf_obj *array, long idx);
+extern unsigned pdf_array_length (pdf_obj *array);
+
+extern void pdf_unshift_array (pdf_obj *array, pdf_obj *object);
+#if 0
+extern pdf_obj *pdf_shift_array (pdf_obj *array);
+extern pdf_obj *pdf_pop_array (pdf_obj *array);
+#endif /* 0 */
+
+extern pdf_obj *pdf_new_dict (void);
+extern void pdf_remove_dict (pdf_obj *dict, const char *key);
+extern void pdf_merge_dict (pdf_obj *dict1, pdf_obj *dict2);
+extern pdf_obj *pdf_lookup_dict (pdf_obj *dict, const char *key);
+extern pdf_obj *pdf_dict_keys (pdf_obj *dict);
+
+/* pdf_add_dict() want pdf_obj as key, however, key must always be name
+ * object and pdf_lookup_dict() and pdf_remove_dict() uses const char as
+ * key. This strange difference seems come from pdfdoc that first allocate
+ * name objects frequently used (maybe 1000 times) such as /Type and does
+ * pdf_link_obj() it rather than allocate/free-ing them each time. But I
+ * already removed that.
+ */
+extern int pdf_add_dict (pdf_obj *dict, pdf_obj *key, pdf_obj *value);
+#if 0
+extern void pdf_put_dict (pdf_obj *dict, const char *key, pdf_obj *value);
+#endif /* 0 */
+
+/* Apply proc(key, value, pdata) for each key-value pairs in dict, stop if proc()
+ * returned non-zero value (and that value is returned). PDF object is passed for
+ * key to allow modification (fix) of key.
+ */
+extern int pdf_foreach_dict (pdf_obj *dict,
+ int (*proc) (pdf_obj *, pdf_obj *, void *),
+ void *pdata);
+
+extern pdf_obj *pdf_new_stream (int flags);
+extern void pdf_add_stream (pdf_obj *stream,
+ const void *stream_data_ptr,
+ long stream_data_len);
+#if HAVE_ZLIB
+extern int pdf_add_stream_flate (pdf_obj *stream,
+ const void *stream_data_ptr,
+ long stream_data_len);
+#endif
+extern int pdf_concat_stream (pdf_obj *dst, pdf_obj *src);
+extern pdf_obj *pdf_stream_dict (pdf_obj *stream);
+extern long pdf_stream_length (pdf_obj *stream);
+#if 0
+extern void pdf_stream_set_flags (pdf_obj *stream, int flags);
+extern int pdf_stream_get_flags (pdf_obj *stream);
+#endif /* 0 */
+extern const void *pdf_stream_dataptr (pdf_obj *stream);
+
+#if 0
+extern int pdf_stream_pop_filter (pdf_obj *stream);
+#endif
+
+/* Compare label of two indirect reference object.
+ */
+extern int pdf_compare_reference (pdf_obj *ref1, pdf_obj *ref2);
+
+/* The following routines are not appropriate for pdfobj.
+ */
+
+extern void pdf_set_compression (int level);
+
+extern void pdf_set_info (pdf_obj *obj);
+extern void pdf_set_root (pdf_obj *obj);
+extern void pdf_set_encrypt (pdf_obj *encrypt, pdf_obj *id);
+
+extern void pdf_files_init (void);
+extern void pdf_files_close (void);
+extern int check_for_pdf (FILE *file);
+extern pdf_file *pdf_open (char *ident, FILE *file);
+extern void pdf_close (pdf_file *pf);
+extern pdf_obj *pdf_file_get_trailer (pdf_file *pf);
+
+extern pdf_obj *pdf_deref_obj (pdf_obj *object);
+extern pdf_obj *pdf_import_object (pdf_obj *object);
+
+extern int pdfobj_escape_str (char *buffer, int size, const unsigned char *s, int len);
+
+extern pdf_obj *pdf_new_indirect (pdf_file *pf, unsigned long label, unsigned short generation);
+extern void pdf_copy_object (pdf_obj *dst, pdf_obj *src);
+
+#endif /* _PDFOBJ_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/pdfparse.c b/Build/source/texk/dvipdf-x/xsrc/pdfparse.c
new file mode 100644
index 00000000000..4d0444b5a30
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pdfparse.c
@@ -0,0 +1,1078 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <ctype.h>
+#include <string.h>
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+
+#include "numbers.h"
+
+#include "mfileio.h"
+
+#include "pdfobj.h"
+#include "pdfdoc.h"
+#include "pdfdev.h"
+
+#include "pdfparse.h"
+
+/* PDF */
+#ifdef is_space
+#undef is_space
+#endif
+#ifdef is_delim
+#undef is_delim
+#endif
+
+#define is_space(c) ((c) == ' ' || (c) == '\t' || (c) == '\f' || \
+ (c) == '\r' || (c) == '\n' || (c) == '\0')
+#define is_delim(c) ((c) == '(' || (c) == '/' || \
+ (c) == '<' || (c) == '>' || \
+ (c) == '[' || (c) == ']' || \
+ (c) == '%')
+#define PDF_TOKEN_END(p,e) ((p) >= (e) || is_space(*(p)) || is_delim(*(p)))
+
+#define istokensep(c) (is_space((c)) || is_delim((c)))
+
+static struct {
+ int tainted;
+} parser_state = {
+ 0
+};
+
+static int xtoi (char ch);
+
+static const char *save = NULL;
+
+void
+dump (const char *start, const char *end)
+{
+ const char *p = start;
+
+#define DUMP_LIMIT 50
+ MESG("\nCurrent input buffer is -->");
+ while (p < end && p < start + DUMP_LIMIT)
+ MESG("%c", *(p++));
+ if (p == start+DUMP_LIMIT)
+ MESG("...");
+ MESG("<--\n");
+}
+
+#define SAVE(s,e) do {\
+ save = (s);\
+ } while (0)
+#define DUMP_RESTORE(s,e) do {\
+ dump(save, end);\
+ (s) = save;\
+ } while (0)
+
+void
+skip_line (const char **start, const char *end)
+{
+ while (*start < end && **start != '\n' && **start != '\r')
+ (*start)++;
+ /* The carriage return (CR; \r; 0x0D) and line feed (LF; \n; 0x0A)
+ * characters, also called newline characters, are treated as
+ * end-of-line (EOL) markers. The combination of a carriage return
+ * followed immediately by a line feed is treated as one EOL marker.
+ */
+ if (*start < end && **start == '\r')
+ (*start)++;
+ if (*start < end && **start == '\n')
+ (*start)++;
+}
+
+void
+skip_white (const char **start, const char *end)
+{
+ /*
+ * The null (NUL; 0x00) character is a white-space character in PDF spec
+ * but isspace(0x00) returns FALSE; on the other hand, the vertical tab
+ * (VT; 0x0B) character is not a white-space character in PDF spec but
+ * isspace(0x0B) returns TRUE.
+ */
+ while (*start < end && (is_space(**start) || **start == '%')) {
+ if (**start == '%')
+ skip_line(start, end);
+ else
+ (*start)++;
+ }
+}
+
+
+static char *
+parsed_string (const char *start, const char *end)
+{
+ char *result = NULL;
+ int len;
+
+ len = end - start;
+ if (len > 0) {
+ result = NEW(len + 1, char);
+ memcpy(result, start, len);
+ result[len] = '\0';
+ }
+
+ return result;
+}
+
+char *
+parse_number (const char **start, const char *end)
+{
+ char *number;
+ const char *p;
+
+ skip_white(start, end);
+ p = *start;
+ if (p < end && (*p == '+' || *p == '-'))
+ p++;
+ while (p < end && isdigit(*p))
+ p++;
+ if (p < end && *p == '.') {
+ p++;
+ while (p < end && isdigit(*p))
+ p++;
+ }
+ number = parsed_string(*start, p);
+
+ *start = p;
+ return number;
+}
+
+char *
+parse_unsigned (const char **start, const char *end)
+{
+ char *number;
+ const char *p;
+
+ skip_white(start, end);
+ for (p = *start; p < end; p++) {
+ if (!isdigit(*p))
+ break;
+ }
+ number = parsed_string(*start, p);
+
+ *start = p;
+ return number;
+}
+
+static char *
+parse_gen_ident (const char **start, const char *end, const char *valid_chars)
+{
+ char *ident;
+ const char *p;
+
+ /* No skip_white(start, end)? */
+ for (p = *start; p < end; p++) {
+ if (!strchr(valid_chars, *p))
+ break;
+ }
+ ident = parsed_string(*start, p);
+
+ *start = p;
+ return ident;
+}
+
+char *
+parse_ident (const char **start, const char *end)
+{
+ static const char *valid_chars =
+ "!\"#$&'*+,-.0123456789:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\^_`abcdefghijklmnopqrstuvwxyz|~";
+
+ return parse_gen_ident(start, end, valid_chars);
+}
+
+char *
+parse_val_ident (const char **start, const char *end)
+{
+ static const char *valid_chars =
+ "!\"#$&'*+,-./0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\^_`abcdefghijklmnopqrstuvwxyz|~";
+
+ return parse_gen_ident(start, end, valid_chars);
+}
+
+char *
+parse_opt_ident (const char **start, const char *end)
+{
+ if (*start < end && **start == '@') {
+ (*start)++;
+ return parse_ident(start, end);
+ }
+
+ return NULL;
+}
+
+#define DDIGITS_MAX 10
+pdf_obj *
+parse_pdf_number (const char **pp, const char *endptr)
+{
+ const char *p;
+ unsigned long ipart = 0, dpart = 0;
+ int nddigits = 0, sign = 1;
+ int has_dot = 0;
+ static double ipot[DDIGITS_MAX+1] = {
+ 1.0,
+ 0.1,
+ 0.01,
+ 0.001,
+ 0.0001,
+ 0.00001,
+ 0.000001,
+ 0.0000001,
+ 0.00000001,
+ 0.000000001,
+ 0.0000000001
+ };
+
+ p = *pp;
+ skip_white(&p, endptr);
+ if (p >= endptr ||
+ (!isdigit(p[0]) && p[0] != '.' &&
+ p[0] != '+' && p[0] != '-')) {
+ WARN("Could not find a numeric object.");
+ return NULL;
+ }
+
+ if (p[0] == '-') {
+ if (p + 1 >= endptr) {
+ WARN("Could not find a numeric object.");
+ return NULL;
+ }
+ sign = -1;
+ p++;
+ } else if (p[0] == '+') {
+ if (p + 1 >= endptr) {
+ WARN("Could not find a numeric object.");
+ return NULL;
+ }
+ sign = 1;
+ p++;
+ }
+
+ while (p < endptr && !istokensep(p[0])) {
+ if (p[0] == '.') {
+ if (has_dot) { /* Two dots */
+ WARN("Could not find a numeric object.");
+ return NULL;
+ } else {
+ has_dot = 1;
+ }
+ } else if (isdigit(p[0])) {
+ if (has_dot) {
+ if (nddigits == DDIGITS_MAX && pdf_obj_get_verbose() > 1) {
+ WARN("Number with more than %d fractional digits.", DDIGITS_MAX);
+ } else if (nddigits < DDIGITS_MAX) {
+ dpart = dpart * 10 + p[0] - '0';
+ nddigits++;
+ } /* Ignore decimal digits more than DDIGITS_MAX */
+ } else {
+ ipart = ipart * 10 + p[0] - '0';
+ }
+ } else {
+ WARN("Could not find a numeric object.");
+ return NULL;
+ }
+ p++;
+ }
+
+ *pp = p;
+ return pdf_new_number((double) sign * (((double ) ipart) + dpart * ipot[nddigits]));
+}
+
+/*
+ * PDF Name:
+ *
+ * PDF-1.2+: Two hexadecimal digits preceded by a number sign.
+ */
+static int
+pn_getc (const char **pp, const char *endptr)
+{
+ int ch = 0;
+ const char *p;
+
+ p = *pp;
+ if (p[0] == '#') {
+ if (p + 2 >= endptr) {
+ *pp = endptr;
+ return -1;
+ }
+ if (!isxdigit(p[1]) || !isxdigit(p[2])) {
+ *pp += 3;
+ return -1;
+ }
+ ch = (xtoi(p[1]) << 4);
+ ch += xtoi(p[2]);
+ *pp += 3;
+ } else {
+ ch = p[0];
+ *pp += 1;
+ }
+
+ return ch;
+}
+
+#ifndef PDF_NAME_LEN_MAX
+#define PDF_NAME_LEN_MAX 128
+#endif
+
+#ifndef PDF_STRING_LEN_MAX
+#define PDF_STRING_LEN_MAX 65535
+#endif
+
+#define STRING_BUFFER_SIZE PDF_STRING_LEN_MAX+1
+static char sbuf[PDF_STRING_LEN_MAX+1];
+
+
+pdf_obj *
+parse_pdf_name (const char **pp, const char *endptr)
+{
+ char name[PDF_NAME_LEN_MAX+1];
+ int ch, len = 0;
+
+ skip_white(pp, endptr);
+ if (*pp >= endptr || **pp != '/') {
+ WARN("Could not find a name object.");
+ return NULL;
+ }
+
+ (*pp)++;
+ while (*pp < endptr && !istokensep(**pp)) {
+ ch = pn_getc(pp, endptr);
+ if (ch < 0 || ch > 0xff) {
+ WARN("Invalid char in PDF name object. (ignored)");
+ } else if (ch == 0) {
+ WARN("Null char not allowed in PDF name object. (ignored)");
+ } else if (len < STRING_BUFFER_SIZE) {
+ if (len == PDF_NAME_LEN_MAX) {
+ WARN("PDF name length too long. (>= %d bytes)", PDF_NAME_LEN_MAX);
+ }
+ name[len++] = ch;
+ } else {
+ WARN("PDF name length too long. (>= %d bytes, truncated)",
+ STRING_BUFFER_SIZE);
+ }
+ }
+ if (len < 1) {
+ WARN("No valid name object found.");
+ return NULL;
+ }
+ name[len] = '\0';
+
+ return pdf_new_name(name);
+}
+
+pdf_obj *
+parse_pdf_boolean (const char **pp, const char *endptr)
+{
+ skip_white(pp, endptr);
+ if (*pp + 4 <= endptr &&
+ !strncmp(*pp, "true", 4)) {
+ if (*pp + 4 == endptr ||
+ istokensep(*(*pp + 4))) {
+ *pp += 4;
+ return pdf_new_boolean(1);
+ }
+ } else if (*pp + 5 <= endptr &&
+ !strncmp(*pp, "false", 5)) {
+ if (*pp + 5 == endptr ||
+ istokensep(*(*pp + 5))) {
+ *pp += 5;
+ return pdf_new_boolean(0);
+ }
+ }
+
+ WARN("Not a boolean object.");
+
+ return NULL;
+}
+
+pdf_obj *
+parse_pdf_null (const char **pp, const char *endptr)
+{
+ skip_white(pp, endptr);
+ if (*pp + 4 > endptr) {
+ WARN("Not a null object.");
+ return NULL;
+ } else if (*pp + 4 < endptr &&
+ !istokensep(*(*pp+4))) {
+ WARN("Not a null object.");
+ return NULL;
+ } else if (!strncmp(*pp, "null", 4)) {
+ *pp += 4;
+ return pdf_new_null();
+ }
+
+ WARN("Not a null object.");
+
+ return NULL;
+}
+
+/*
+ * PDF Literal String
+ */
+#ifndef isodigit
+#define isodigit(c) ((c) >= '0' && (c) <= '7')
+#endif
+static int
+ps_getescc (const char **pp, const char *endptr)
+{
+ int ch, i;
+ const char *p;
+
+ p = *pp + 1; /* backslash assumed. */
+ switch (p[0]) {
+ case 'n': ch = '\n'; p++; break;
+ case 'r': ch = '\r'; p++; break;
+ case 't': ch = '\t'; p++; break;
+ case 'b': ch = '\b'; p++; break;
+ case 'f': ch = '\f'; p++; break;
+
+ /*
+ * An end-of-line marker preceded by a backslash must be ignored.
+ */
+ case '\n':
+ ch = -1;
+ p++;
+ break;
+ case '\r':
+ ch = -1;
+ p++;
+ if (p < endptr && p[0] == '\n')
+ p++;
+ break;
+ default:
+ if (p[0] == '\\' ||
+ p[0] == '(' || p[0] == ')') {
+ ch = p[0];
+ p++;
+ } else if (isodigit(p[0])) {
+ ch = 0;
+ /* Don't forget isodigit() is a macro. */
+ for (i = 0; i < 3 &&
+ p < endptr && isodigit(p[0]); i++) {
+ ch = (ch << 3) + (p[0] - '0');
+ p++;
+ }
+ ch = (ch & 0xff); /* Ignore overflow. */
+ } else {
+ ch = ((unsigned char) p[0]); /* Ignore only backslash. */
+ p++;
+ }
+ }
+
+ *pp = p;
+ return ch;
+}
+
+static pdf_obj *
+parse_pdf_literal_string (const char **pp, const char *endptr)
+{
+ int ch, op_count = 0, len = 0;
+ const char *p;
+
+ p = *pp;
+
+ skip_white(&p, endptr);
+
+ if (p >= endptr || p[0] != '(')
+ return NULL;
+
+ p++;
+
+ /*
+ * Accroding to the PDF spec., an end-of-line marker, not preceded
+ * by a backslash, must be converted to single \n.
+ */
+ while (p < endptr) {
+
+ ch = p[0];
+
+ if (ch == ')' && op_count < 1)
+ break;
+
+#ifndef PDF_PARSE_STRICT
+ if (parser_state.tainted) {
+ if (p + 1 < endptr && (ch & 0x80)) {
+ if (len + 2 >= PDF_STRING_LEN_MAX) {
+ WARN("PDF string length too long. (limit: %ld)",
+ PDF_STRING_LEN_MAX);
+ return NULL;
+ }
+ sbuf[len++] = p[0];
+ sbuf[len++] = p[1];
+ p += 2;
+ continue;
+ }
+ }
+#endif /* !PDF_PARSE_STRICT */
+
+ if (len + 1 >= PDF_STRING_LEN_MAX) {
+ WARN("PDF string length too long. (limit: %ld)",
+ PDF_STRING_LEN_MAX);
+ return NULL;
+ }
+
+ switch (ch) {
+ case '\\':
+ ch = ps_getescc(&p, endptr);
+ if (ch >= 0)
+ sbuf[len++] = (ch & 0xff);
+ break;
+ case '\r':
+ p++;
+ if (p < endptr && p[0] == '\n')
+ p++;
+ sbuf[len++] = '\n';
+ break;
+ default:
+ if (ch == '(')
+ op_count++;
+ else if (ch == ')')
+ op_count--;
+ sbuf[len++] = ch;
+ p++;
+ break;
+ }
+ }
+
+ if (op_count > 0 ||
+ p >= endptr || p[0] != ')') {
+ WARN("Unbalanced parens/truncated PDF literal string.");
+ return NULL;
+ }
+
+ *pp = p + 1;
+ return pdf_new_string(sbuf, len);
+}
+
+/*
+ * PDF Hex String
+ */
+static int
+xtoi (char ch)
+{
+ if (ch >= '0' && ch <= '9')
+ return ch - '0';
+ if (ch >= 'A' && ch <= 'F')
+ return (ch - 'A') + 10;
+ if (ch >= 'a' && ch <= 'f')
+ return (ch - 'a') + 10;
+
+ return -1;
+}
+
+static pdf_obj *
+parse_pdf_hex_string (const char **pp, const char *endptr)
+{
+ const char *p;
+ long len;
+
+ p = *pp;
+
+ skip_white(&p, endptr);
+ if (p >= endptr || p[0] != '<')
+ return NULL;
+
+ p++;
+
+ len = 0;
+ /*
+ * PDF Reference does not describe how to treat invalid char.
+ * Zero is appended if final hex digit is missing.
+ */
+ while (p < endptr && p[0] != '>' && len < PDF_STRING_LEN_MAX) {
+ int ch;
+
+ skip_white(&p, endptr);
+ if (p >= endptr || p[0] == '>')
+ break;
+
+ ch = (xtoi(p[0]) << 4);
+ p++;
+
+ skip_white(&p, endptr);
+ if (p < endptr && p[0] != '>') {
+ ch += xtoi(p[0]);
+ p++;
+ }
+ sbuf[len++] = (ch & 0xff);
+ }
+
+ if (p >= endptr) {
+ WARN("Premature end of input hex string.");
+ return NULL;
+ } else if (p[0] != '>') {
+ WARN("PDF string length too long. (limit: %ld)", PDF_STRING_LEN_MAX);
+ return NULL;
+ }
+
+ *pp = p + 1;
+ return pdf_new_string(sbuf, len);
+}
+
+pdf_obj *
+parse_pdf_string (const char **pp, const char *endptr)
+{
+ skip_white(pp, endptr);
+ if (*pp + 2 <= endptr) {
+ if (**pp == '(')
+ return parse_pdf_literal_string(pp, endptr);
+ else if (**pp == '<' &&
+ (*(*pp + 1) == '>' || isxdigit(*(*pp + 1)))) {
+ return parse_pdf_hex_string(pp, endptr);
+ }
+ }
+
+ WARN("Could not find a string object.");
+
+ return NULL;
+}
+
+#ifndef PDF_PARSE_STRICT
+pdf_obj *
+parse_pdf_tainted_dict (const char **pp, const char *endptr)
+{
+ pdf_obj *result;
+
+ parser_state.tainted = 1;
+ result = parse_pdf_dict(pp, endptr, NULL);
+ parser_state.tainted = 0;
+
+ return result;
+}
+#else /* PDF_PARSE_STRICT */
+pdf_obj *
+parse_pdf_tainted_dict (const char **pp, const char *endptr, int level)
+{
+ return parse_pdf_dict(pp, endptr, NULL);
+}
+#endif /* !PDF_PARSE_STRICT */
+
+pdf_obj *
+parse_pdf_dict (const char **pp, const char *endptr, pdf_file *pf)
+{
+ pdf_obj *result = NULL;
+ const char *p;
+
+ p = *pp;
+
+ skip_white(&p, endptr);
+
+ /* At least four letter <<>>. */
+ if (p + 4 > endptr ||
+ p[0] != '<' || p[1] != '<') {
+ return NULL;
+ }
+ p += 2;
+
+ result = pdf_new_dict();
+
+ skip_white(&p, endptr);
+ while (p < endptr && p[0] != '>') {
+ pdf_obj *key, *value;
+
+ skip_white(&p, endptr);
+ key = parse_pdf_name(&p, endptr);
+ if (!key) {
+ WARN("Could not find a key in dictionary object.");
+ pdf_release_obj(result);
+ return NULL;
+ }
+
+ skip_white(&p, endptr);
+
+ value = parse_pdf_object(&p, endptr, pf);
+ if (!value) {
+ pdf_release_obj(key);
+ pdf_release_obj(value);
+ pdf_release_obj(result);
+ WARN("Could not find a value in dictionary object.");
+ return NULL;
+ }
+ pdf_add_dict(result, key, value);
+
+ skip_white(&p, endptr);
+ }
+
+ if (p + 2 > endptr ||
+ p[0] != '>' || p[1] != '>') {
+ WARN("Syntax error: Dictionary object ended prematurely.");
+ pdf_release_obj(result);
+ return NULL;
+ }
+
+ *pp = p + 2; /* skip >> */
+ return result;
+}
+
+pdf_obj *
+parse_pdf_array (const char **pp, const char *endptr, pdf_file *pf)
+{
+ pdf_obj *result;
+ const char *p;
+
+ p = *pp;
+
+ skip_white(&p, endptr);
+ if (p + 2 > endptr || p[0] != '[') {
+ WARN("Could not find an array object.");
+ return NULL;
+ }
+
+ result = pdf_new_array();
+
+ p++;
+ skip_white(&p, endptr);
+
+ while (p < endptr && p[0] != ']') {
+ pdf_obj *elem;
+
+ elem = parse_pdf_object(&p, endptr, pf);
+ if (!elem) {
+ pdf_release_obj(result);
+ WARN("Could not find a valid object in array object.");
+ return NULL;
+ }
+ pdf_add_array(result, elem);
+
+ skip_white(&p, endptr);
+ }
+
+ if (p >= endptr || p[0] != ']') {
+ WARN("Array object ended prematurely.");
+ pdf_release_obj(result);
+ return NULL;
+ }
+
+ *pp = p + 1; /* skip ] */
+ return result;
+}
+
+static pdf_obj *
+parse_pdf_stream (const char **pp, const char *endptr, pdf_obj *dict, pdf_file *pf)
+{
+ pdf_obj *result = NULL;
+ const char *p;
+ pdf_obj *stream_dict;
+ long stream_length;
+
+ p = *pp;
+ skip_white(&p, endptr);
+ if (p + 6 > endptr ||
+ strncmp(p, "stream", 6)) {
+ return NULL;
+ }
+ p += 6;
+
+ /* Carrige return alone is not allowed after keyword "stream".
+ * See, PDF Reference, 4th ed., version 1.5, p. 36.
+ */
+ if (p < endptr && p[0] == '\n') {
+ p++;
+ } else if (p + 1 < endptr &&
+ (p[0] == '\r' && p[1] == '\n')) {
+ p += 2;
+ }
+#ifndef PDF_PARSE_STRICT
+ else {
+ /* TeX translate end-of-line marker to a single space. */
+ if (parser_state.tainted) {
+ if (p < endptr && p[0] == ' ') {
+ p++;
+ }
+ }
+ }
+ /* The end-of-line marker not mandatory? */
+#endif /* !PDF_PARSE_STRICT */
+
+ /* Stream length */
+ {
+ pdf_obj *tmp, *tmp2;
+
+ tmp = pdf_lookup_dict(dict, "Length");
+
+ if (tmp != NULL) {
+ tmp2 = pdf_deref_obj(tmp);
+ if (pdf_obj_typeof(tmp2) != PDF_NUMBER)
+ stream_length = -1;
+ else {
+ stream_length = (long) pdf_number_value(tmp2);
+ }
+ pdf_release_obj(tmp2);
+ }
+#ifndef PDF_PARSE_STRICT
+ else if (p + 9 <= endptr)
+ {
+ /*
+ * This was added to allow TeX users to write PDF stream object
+ * directly in their TeX source. This violates PDF spec.
+ */
+ const char *q;
+
+ stream_length = -1;
+ for (q = endptr - 1; q >= p + 8; q--) {
+ if (q[0] != 'm')
+ continue;
+ else {
+ if (!memcmp(q - 8, "endstrea", 8)) {
+ /* The end-of-line marker is not skipped here. There are
+ * no way to decide if it is a part of the stream or not.
+ */
+ stream_length = ((long) (q - p)) - 8;
+ break;
+ }
+ }
+ }
+ }
+#endif /* !PDF_PARSE_STRICT */
+ else {
+ return NULL;
+ }
+ }
+
+
+ if (stream_length < 0 ||
+ p + stream_length > endptr)
+ return NULL;
+
+ /*
+ * If Filter is not applied, set STREAM_COMPRESS flag.
+ * Should we use filter for ASCIIHexEncode/ASCII85Encode-ed streams?
+ */
+ {
+ pdf_obj *filters;
+
+ filters = pdf_lookup_dict(dict, "Filter");
+ if (!filters && stream_length > 10) {
+ result = pdf_new_stream(STREAM_COMPRESS);
+ } else {
+ result = pdf_new_stream(0);
+ }
+ }
+
+ stream_dict = pdf_stream_dict(result);
+ pdf_merge_dict(stream_dict, dict);
+
+ pdf_add_stream(result, p, stream_length);
+ p += stream_length;
+
+ /* Check "endsteam" */
+ {
+ /*
+ * It is an error if the stream contained too much data except there
+ * may be an extra end-of-line marker before the keyword "endstream".
+ */
+#ifdef PDF_PARSE_STRICT
+ if (p < endptr && p[0] == '\r')
+ p++;
+ if (p < endptr && p[0] == '\n')
+ p++;
+#else /* !PDF_PARSE_STRICT */
+ /*
+ * This may skip data starting with '%' and terminated by a
+ * '\r' or '\n' or '\r\n'. The PDF syntax rule should not be
+ * applied to the content of the stream data.
+ * TeX may have converted end-of-line to single white space.
+ */
+ skip_white(&p, endptr);
+#endif /* !PDF_PARSE_STRICT */
+
+ if (p + 9 > endptr ||
+ memcmp(p, "endstream", 9)) {
+ pdf_release_obj(result);
+ return NULL;
+ }
+ p += 9;
+ }
+
+ *pp = p;
+ return result;
+}
+
+#ifndef PDF_PARSE_STRICT
+
+/* PLEASE REMOVE THIS */
+#include "specials.h"
+
+/* This is not PDF indirect reference. */
+static pdf_obj *
+parse_pdf_reference (const char **start, const char *end)
+{
+ pdf_obj *result = NULL;
+ char *name;
+
+ SAVE(*start, end);
+
+ skip_white(start, end);
+ name = parse_opt_ident(start, end);
+ if (name) {
+ result = spc_lookup_reference(name);
+ if (!result) {
+ WARN("Could not find the named reference (@%s).", name);
+ DUMP_RESTORE(*start, end);
+ }
+ RELEASE(name);
+ } else {
+ WARN("Could not find a reference name.");
+ DUMP_RESTORE(*start, end);
+ result = NULL;
+ }
+
+ return result;
+}
+#endif /* !PDF_PARSE_STRICT */
+
+static pdf_obj *
+try_pdf_reference (const char *start, const char *end, const char **endptr, pdf_file *pf)
+{
+ unsigned long id = 0;
+ unsigned short gen = 0;
+
+ ASSERT(pf);
+
+ if (endptr)
+ *endptr = start;
+
+ skip_white(&start, end);
+ if (start > end - 5 || !isdigit(*start)) {
+ return NULL;
+ }
+ while (!is_space(*start)) {
+ if (start >= end || !isdigit(*start)) {
+ return NULL;
+ }
+ id = id * 10 + (*start - '0');
+ start++;
+ }
+
+ skip_white(&start, end);
+ if (start >= end || !isdigit(*start))
+ return NULL;
+ while (!is_space(*start)) {
+ if (start >= end || !isdigit(*start))
+ return NULL;
+ gen = gen * 10 + (*start - '0');
+ start++;
+ }
+
+ skip_white(&start, end);
+ if (start >= end || *start != 'R')
+ return NULL;
+ start++;
+ if (!PDF_TOKEN_END(start, end))
+ return NULL;
+
+ if (endptr)
+ *endptr = start;
+
+ return pdf_new_indirect(pf, id, gen);
+}
+
+pdf_obj *
+parse_pdf_object (const char **pp, const char *endptr, pdf_file *pf)
+/* If pf is NULL, then indirect references are not allowed */
+{
+ pdf_obj *result = NULL;
+ const char *nextptr;
+
+ skip_white(pp, endptr);
+ if (*pp >= endptr) {
+ WARN("Could not find any valid object.");
+ return NULL;
+ }
+
+ switch (**pp) {
+
+ case '<':
+
+ if (*(*pp + 1) != '<') {
+ result = parse_pdf_hex_string(pp, endptr);
+ } else {
+ pdf_obj *dict;
+
+ result = parse_pdf_dict(pp, endptr, pf);
+ skip_white(pp, endptr);
+ if ( result &&
+ *pp <= endptr - 15 &&
+ !memcmp(*pp, "stream", 6)) {
+ dict = result;
+ result = parse_pdf_stream(pp, endptr, dict, pf);
+ pdf_release_obj(dict);
+ }
+ }
+
+ break;
+ case '(':
+ result = parse_pdf_string(pp, endptr);
+ break;
+ case '[':
+ result = parse_pdf_array(pp, endptr, pf);
+ break;
+ case '/':
+ result = parse_pdf_name(pp, endptr);
+ break;
+ case 'n':
+ result = parse_pdf_null(pp, endptr);
+ break;
+ case 't': case 'f':
+ result = parse_pdf_boolean(pp, endptr);
+ break;
+ case '+': case '-': case '.':
+ result = parse_pdf_number(pp, endptr);
+ break;
+ case '0': case '1': case '2': case '3': case '4':
+ case '5': case '6': case '7': case '8': case '9':
+
+ /*
+ * If pf != NULL, then we are parsing a PDF file,
+ * and indirect references are allowed.
+ */
+ if (pf && (result = try_pdf_reference(*pp, endptr, &nextptr, pf))) {
+ *pp = nextptr;
+ } else {
+ result = parse_pdf_number(pp, endptr);
+ }
+ break;
+
+ case '@':
+
+#ifndef PDF_PARSE_STRICT
+ result = parse_pdf_reference(pp, endptr);
+#endif /* !PDF_PARSE_STRICT */
+ break;
+
+ default:
+ WARN("Unknown PDF object type.");
+ result = NULL;
+ }
+
+ return result;
+}
+
diff --git a/Build/source/texk/dvipdf-x/xsrc/pdfximage.c b/Build/source/texk/dvipdf-x/xsrc/pdfximage.c
new file mode 100644
index 00000000000..f16829f18ba
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pdfximage.c
@@ -0,0 +1,924 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2007-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "system.h"
+#include "error.h"
+#include "mem.h"
+
+#include "dpxfile.h"
+
+#include "pdfobj.h"
+
+#include "pdfdoc.h"
+#include "pdfdev.h"
+#include "pdfdraw.h"
+
+#include "epdf.h"
+#include "mpost.h"
+#include "pngimage.h"
+#include "jpegimage.h"
+#include "bmpimage.h"
+
+#include "pdfximage.h"
+
+/* From psimage.h */
+static int check_for_ps (FILE *fp);
+static int ps_include_page (pdf_ximage *ximage, const char *file_name);
+
+
+#define IMAGE_TYPE_UNKNOWN -1
+#define IMAGE_TYPE_PDF 0
+#define IMAGE_TYPE_JPEG 1
+#define IMAGE_TYPE_PNG 2
+#define IMAGE_TYPE_MPS 4
+#define IMAGE_TYPE_EPS 5
+#define IMAGE_TYPE_BMP 6
+
+
+struct attr_
+{
+ long width, height;
+ double xdensity, ydensity;
+ pdf_rect bbox;
+};
+
+struct pdf_ximage_
+{
+ char *ident;
+ char res_name[16];
+ long page_no, page_count;
+
+ int subtype;
+
+ struct attr_ attr;
+
+ char *filename;
+ pdf_obj *reference;
+ pdf_obj *resource;
+ pdf_obj *attr_dict;
+
+ char tempfile;
+};
+
+
+/* verbose, verbose, verbose... */
+struct opt_
+{
+ int verbose;
+ char *cmdtmpl;
+};
+
+static struct opt_ _opts = {
+ 0, NULL
+};
+
+void pdf_ximage_set_verbose (void) { _opts.verbose++; }
+
+
+struct ic_
+{
+ int count, capacity;
+ pdf_ximage *ximages;
+};
+
+static struct ic_ _ic = {
+ 0, 0, NULL
+};
+
+static void
+pdf_init_ximage_struct (pdf_ximage *I, const char *ident, const char *filename, pdf_obj *dict)
+{
+ if (ident) {
+ I->ident = NEW(strlen(ident)+1, char);
+ strcpy(I->ident, ident);
+ } else
+ I ->ident = NULL;
+ I->page_no = I->page_count = 0;
+ if (filename) {
+ I->filename = NEW(strlen(filename)+1, char);
+ strcpy(I->filename, filename);
+ } else
+ I->filename = NULL;
+ I->subtype = -1;
+ memset(I->res_name, 0, 16);
+ I->reference = NULL;
+ I->resource = NULL;
+ I->attr_dict = dict;
+
+ I->attr.width = I->attr.height = 0;
+ I->attr.xdensity = I->attr.ydensity = 1.0;
+ I->attr.bbox.llx = I->attr.bbox.lly = 0;
+ I->attr.bbox.urx = I->attr.bbox.ury = 0;
+
+ I->tempfile = 0;
+}
+
+static void
+pdf_set_ximage_tempfile (pdf_ximage *I, const char *filename)
+{
+ if (I->filename)
+ RELEASE(I->filename);
+ I->filename = NEW(strlen(filename)+1, char);
+ strcpy(I->filename, filename);
+ I->tempfile = 1;
+}
+
+static void
+pdf_clean_ximage_struct (pdf_ximage *I)
+{
+ if (I->ident)
+ RELEASE(I->ident);
+ if (I->filename)
+ RELEASE(I->filename);
+ if (I->reference)
+ pdf_release_obj(I->reference);
+ if (I->resource)
+ pdf_release_obj(I->resource);
+ if (I->attr_dict)
+ pdf_release_obj(I->attr_dict);
+ pdf_init_ximage_struct(I, NULL, NULL, NULL);
+}
+
+
+void
+pdf_init_images (void)
+{
+ struct ic_ *ic = &_ic;
+ ic->count = 0;
+ ic->capacity = 0;
+ ic->ximages = NULL;
+}
+
+void
+pdf_close_images (void)
+{
+ struct ic_ *ic = &_ic;
+ if (ic->ximages) {
+ int i;
+ for (i = 0; i < ic->count; i++) {
+ pdf_ximage *I = ic->ximages+i;
+ if (I->tempfile) {
+ /*
+ * It is important to remove temporary files at the end because
+ * we cache file names. Since we use mkstemp to create them, we
+ * might get the same file name again if delete the first file.
+ * (This happens on NetBSD, reported by Jukka Salmi.)
+ * We also use this to convert a PS file only once if multiple
+ * pages are imported from that file.
+ */
+ if (_opts.verbose > 1 && keep_cache != 1)
+ MESG("pdf_image>> deleting temporary file \"%s\"\n", I->filename);
+ dpx_delete_temp_file(I->filename, false); /* temporary filename freed here */
+ I->filename = NULL;
+ }
+ pdf_clean_ximage_struct(I);
+ }
+ RELEASE(ic->ximages);
+ ic->ximages = NULL;
+ ic->count = ic->capacity = 0;
+ }
+
+ if (_opts.cmdtmpl)
+ RELEASE(_opts.cmdtmpl);
+ _opts.cmdtmpl = NULL;
+}
+
+static int
+source_image_type (FILE *fp)
+{
+ int format = IMAGE_TYPE_UNKNOWN;
+
+ rewind(fp);
+ /*
+ * Make sure we check for PS *after* checking for MP since
+ * MP is a special case of PS.
+ */
+ if (check_for_jpeg(fp))
+ {
+ format = IMAGE_TYPE_JPEG;
+ }
+#ifdef HAVE_LIBPNG
+ else if (check_for_png(fp))
+ {
+ format = IMAGE_TYPE_PNG;
+ }
+#endif
+ else if (check_for_bmp(fp))
+ {
+ format = IMAGE_TYPE_BMP;
+ } else if (check_for_pdf(fp)) {
+ format = IMAGE_TYPE_PDF;
+ } else if (check_for_mp(fp)) {
+ format = IMAGE_TYPE_MPS;
+ } else if (check_for_ps(fp)) {
+ format = IMAGE_TYPE_EPS;
+ } else {
+ format = IMAGE_TYPE_UNKNOWN;
+ }
+ rewind(fp);
+
+ return format;
+}
+
+static int
+load_image (const char *ident, const char *fullname, int format, FILE *fp,
+ long page_no, pdf_obj *dict)
+{
+ struct ic_ *ic = &_ic;
+ int id = -1; /* ret */
+ pdf_ximage *I;
+
+ id = ic->count;
+ if (ic->count >= ic->capacity) {
+ ic->capacity += 16;
+ ic->ximages = RENEW(ic->ximages, ic->capacity, pdf_ximage);
+ }
+
+ I = &ic->ximages[id];
+ pdf_init_ximage_struct(I, ident, ident, dict);
+ pdf_ximage_set_page(I, page_no, 0);
+
+ switch (format) {
+ case IMAGE_TYPE_JPEG:
+ if (_opts.verbose)
+ MESG("[JPEG]");
+ if (jpeg_include_image(I, fp) < 0)
+ goto error;
+ I->subtype = PDF_XOBJECT_TYPE_IMAGE;
+ break;
+#ifdef HAVE_LIBPNG
+ case IMAGE_TYPE_PNG:
+ if (_opts.verbose)
+ MESG("[PNG]");
+ if (png_include_image(I, fp) < 0)
+ goto error;
+ I->subtype = PDF_XOBJECT_TYPE_IMAGE;
+ break;
+#endif
+ case IMAGE_TYPE_BMP:
+ if (_opts.verbose)
+ MESG("[BMP]");
+ if (bmp_include_image(I, fp) < 0)
+ goto error;
+ I->subtype = PDF_XOBJECT_TYPE_IMAGE;
+ break;
+ case IMAGE_TYPE_PDF:
+ if (_opts.verbose)
+ MESG("[PDF]");
+ if (pdf_include_page(I, fp) < 0)
+ goto error;
+ if (_opts.verbose)
+ MESG(",Page:%ld", I->page_no);
+ I->subtype = PDF_XOBJECT_TYPE_FORM;
+ break;
+ // case IMAGE_TYPE_EPS:
+ default:
+ if (_opts.verbose)
+ MESG(format == IMAGE_TYPE_EPS ? "[PS]" : "[UNKNOWN]");
+ if (ps_include_page(I, fullname) < 0)
+ goto error;
+ if (_opts.verbose)
+ MESG(",Page:%ld", I->page_no);
+ I->subtype = PDF_XOBJECT_TYPE_FORM;
+ }
+
+ switch (I->subtype) {
+ case PDF_XOBJECT_TYPE_IMAGE:
+ sprintf(I->res_name, "Im%d", id);
+ break;
+ case PDF_XOBJECT_TYPE_FORM:
+ sprintf(I->res_name, "Fm%d", id);
+ break;
+ default:
+ ERROR("Unknown XObject subtype: %d", I->subtype);
+ goto error;
+ }
+
+ ic->count++;
+
+ return id;
+
+ error:
+ pdf_clean_ximage_struct(I);
+ return -1;
+}
+
+
+#define dpx_find_file(n,d,s) (kpse_find_pict((n)))
+#define dpx_fopen(n,m) (MFOPEN((n),(m)))
+#define dpx_fclose(f) (MFCLOSE((f)))
+
+int
+pdf_ximage_findresource (const char *ident, long page_no, pdf_obj *dict)
+{
+ struct ic_ *ic = &_ic;
+ int id = -1;
+ pdf_ximage *I;
+ char *fullname;
+ int format;
+ FILE *fp;
+
+ for (id = 0; id < ic->count; id++) {
+ I = &ic->ximages[id];
+ if (I->ident && !strcmp(ident, I->ident) &&
+ I->page_no == page_no + (page_no < 0 ? I->page_count+1 : 0) &&
+ I->attr_dict == dict) {
+ return id;
+ }
+ }
+
+ /* try loading image */
+ fullname = dpx_find_file(ident, "_pic_", "");
+ if (!fullname) {
+ WARN("Error locating image file \"%s\"", ident);
+ return -1;
+ }
+
+ fp = dpx_fopen(fullname, FOPEN_RBIN_MODE);
+ if (!fp) {
+ WARN("Error opening image file \"%s\"", fullname);
+ RELEASE(fullname);
+ return -1;
+ }
+ if (_opts.verbose) {
+ MESG("(Image:%s", ident);
+ if (_opts.verbose > 1)
+ MESG("[%s]", fullname);
+ }
+
+ format = source_image_type(fp);
+ switch (format) {
+ case IMAGE_TYPE_MPS:
+ if (_opts.verbose)
+ MESG("[MPS]");
+ id = mps_include_page(ident, fp);
+ if (id < 0) {
+ WARN("Try again with the distiller.");
+ format = IMAGE_TYPE_EPS;
+ rewind(fp);
+ } else
+ break;
+ default:
+ id = load_image(ident, fullname, format, fp, page_no, dict);
+ break;
+ }
+ dpx_fclose(fp);
+
+ RELEASE(fullname);
+
+ if (_opts.verbose)
+ MESG(")");
+
+ if (id < 0)
+ WARN("pdf: image inclusion failed for \"%s\".", ident);
+
+ return id;
+}
+
+/* Reference: PDF Reference 1.5 v6, pp.321--322
+ *
+ * TABLE 4.42 Additional entries specific to a type 1 form dictionary
+ *
+ * BBox rectangle (Required) An array of four numbers in the form coordinate
+ * system, giving the coordinates of the left, bottom, right,
+ * and top edges, respectively, of the form XObject's bounding
+ * box. These boundaries are used to clip the form XObject and
+ * to determine its size for caching.
+ *
+ * Matrix array (Optional) An array of six numbers specifying the form
+ * matrix, which maps form space into user space.
+ * Default value: the identity matrix [1 0 0 1 0 0].
+ */
+void
+pdf_ximage_init_form_info (xform_info *info)
+{
+ info->flags = 0;
+ info->bbox.llx = 0;
+ info->bbox.lly = 0;
+ info->bbox.urx = 0;
+ info->bbox.ury = 0;
+ info->matrix.a = 1.0;
+ info->matrix.b = 0.0;
+ info->matrix.c = 0.0;
+ info->matrix.d = 1.0;
+ info->matrix.e = 0.0;
+ info->matrix.f = 0.0;
+}
+
+/* Reference: PDF Reference 1.5 v6, pp.303--306
+ *
+ * TABLE 4.42 Additional entries specific to an image dictionary
+ *
+ * Width integer (Required) The width of the image, in samples.
+ *
+ * Height integer (Required) The height of the image, in samples.
+ *
+ * ColorSpace name or array
+ * (Required for images, except those that use the JPXDecode
+ * filter; not allowed for image masks) The color space in
+ * which image samples are specified. This may be any type
+ * of color space except Patter.
+ *
+ * If the image uses the JPXDecode filter, this entry is
+ * optional.
+ *
+ * BitsPerComponent integer
+ * (Required except for image masks and images that use the
+ * JPXDecode filter) The number of bits used to represent
+ * each color component. Only a single value may be specified;
+ * the number of bits is the same for all color components.
+ * Valid values are 1,2,4,8, and (in PDF1.5) 16. If ImageMask
+ * is true, this entry is optional, and if speficified, its
+ * value must be 1.
+ *
+ * If the image stream uses the JPXDecode filter, this entry
+ * is optional and ignored if present. The bit depth is
+ * determined in the process of decoding the JPEG2000 image.
+ */
+void
+pdf_ximage_init_image_info (ximage_info *info)
+{
+ info->flags = 0;
+ info->width = 0;
+ info->height = 0;
+ info->bits_per_component = 0;
+ info->num_components = 0;
+ info->min_dpi = 0;
+ info->xdensity = info->ydensity = 1.0;
+}
+
+char *
+pdf_ximage_get_ident (pdf_ximage *I)
+{
+ return I->ident;
+}
+
+void
+pdf_ximage_set_image (pdf_ximage *I, void *image_info, pdf_obj *resource)
+{
+ pdf_obj *dict;
+ ximage_info *info = image_info;
+
+ if (!PDF_OBJ_STREAMTYPE(resource))
+ ERROR("Image XObject must be of stream type.");
+
+ I->subtype = PDF_XOBJECT_TYPE_IMAGE;
+
+ I->attr.width = info->width; /* The width of the image, in samples */
+ I->attr.height = info->height; /* The height of the image, in samples */
+ I->attr.xdensity = info->xdensity;
+ I->attr.ydensity = info->ydensity;
+
+ I->reference = pdf_ref_obj(resource);
+
+ dict = pdf_stream_dict(resource);
+ pdf_add_dict(dict, pdf_new_name("Type"), pdf_new_name("XObject"));
+ pdf_add_dict(dict, pdf_new_name("Subtype"), pdf_new_name("Image"));
+ pdf_add_dict(dict, pdf_new_name("Width"), pdf_new_number(info->width));
+ pdf_add_dict(dict, pdf_new_name("Height"), pdf_new_number(info->height));
+ pdf_add_dict(dict, pdf_new_name("BitsPerComponent"),
+ pdf_new_number(info->bits_per_component));
+ if (I->attr_dict)
+ pdf_merge_dict(dict, I->attr_dict);
+
+ pdf_release_obj(resource); /* Caller don't know we are using reference. */
+ I->resource = NULL;
+}
+
+void
+pdf_ximage_set_form (pdf_ximage *I, void *form_info, pdf_obj *resource)
+{
+ xform_info *info = form_info;
+
+ I->subtype = PDF_XOBJECT_TYPE_FORM;
+
+ I->attr.bbox.llx = info->bbox.llx;
+ I->attr.bbox.lly = info->bbox.lly;
+ I->attr.bbox.urx = info->bbox.urx;
+ I->attr.bbox.ury = info->bbox.ury;
+
+ I->reference = pdf_ref_obj(resource);
+
+ pdf_release_obj(resource); /* Caller don't know we are using reference. */
+ I->resource = NULL;
+}
+
+long
+pdf_ximage_get_page (pdf_ximage *I)
+{
+ return I->page_no;
+}
+
+void
+pdf_ximage_set_page (pdf_ximage *I, long page_no, long page_count)
+{
+ I->page_no = page_no;
+ I->page_count = page_count;
+}
+
+
+#define CHECK_ID(c,n) do {\
+ if ((n) < 0 || (n) >= (c)->count) {\
+ ERROR("Invalid XObject ID: %d", (n));\
+ }\
+} while (0)
+#define GET_IMAGE(c,n) (&((c)->ximages[(n)]))
+
+pdf_obj *
+pdf_ximage_get_reference (int id)
+{
+ struct ic_ *ic = &_ic;
+ pdf_ximage *I;
+
+ CHECK_ID(ic, id);
+
+ I = GET_IMAGE(ic, id);
+ if (!I->reference)
+ I->reference = pdf_ref_obj(I->resource);
+
+ return pdf_link_obj(I->reference);
+}
+
+/* called from pdfdoc.c only for late binding */
+int
+pdf_ximage_defineresource (const char *ident,
+ int subtype, void *info, pdf_obj *resource)
+{
+ struct ic_ *ic = &_ic;
+ int id;
+ pdf_ximage *I;
+
+ id = ic->count;
+ if (ic->count >= ic->capacity) {
+ ic->capacity += 16;
+ ic->ximages = RENEW(ic->ximages, ic->capacity, pdf_ximage);
+ }
+
+ I = &ic->ximages[id];
+
+ pdf_init_ximage_struct(I, ident, NULL, NULL);
+
+ switch (subtype) {
+ case PDF_XOBJECT_TYPE_IMAGE:
+ pdf_ximage_set_image(I, info, resource);
+ sprintf(I->res_name, "Im%d", id);
+ break;
+ case PDF_XOBJECT_TYPE_FORM:
+ pdf_ximage_set_form (I, info, resource);
+ sprintf(I->res_name, "Fm%d", id);
+ break;
+ default:
+ ERROR("Unknown XObject subtype: %d", subtype);
+ }
+ ic->count++;
+
+ return id;
+}
+
+
+char *
+pdf_ximage_get_resname (int id)
+{
+ struct ic_ *ic = &_ic;
+ pdf_ximage *I;
+
+ CHECK_ID(ic, id);
+
+ I = GET_IMAGE(ic, id);
+
+ return I->res_name;
+}
+
+
+/* depth...
+ * Dvipdfm treat "depth" as "yoffset" for pdf:image and pdf:uxobj
+ * not as vertical dimension of scaled image. (And there are bugs.)
+ * This part contains incompatibile behaviour than dvipdfm!
+ */
+#define EBB_DPI 72
+
+static void
+scale_to_fit_I (pdf_tmatrix *T,
+ transform_info *p,
+ pdf_ximage *I)
+{
+ double s_x, s_y, d_x, d_y;
+ double wd0, ht0, dp, xscale, yscale;
+
+ if (p->flags & INFO_HAS_USER_BBOX) {
+ wd0 = p->bbox.urx - p->bbox.llx;
+ ht0 = p->bbox.ury - p->bbox.lly;
+ xscale = I->attr.width * I->attr.xdensity / wd0;
+ yscale = I->attr.height * I->attr.ydensity / ht0;
+ d_x = -p->bbox.llx / wd0;
+ d_y = -p->bbox.lly / ht0;
+ } else {
+ wd0 = I->attr.width * I->attr.xdensity;
+ ht0 = I->attr.height * I->attr.ydensity;
+ xscale = yscale = 1.0;
+ d_x = 0.0;
+ d_y = 0.0;
+ }
+
+ if (wd0 == 0.0) {
+ WARN("Image width=0.0!");
+ wd0 = 1.0;
+ }
+ if (ht0 == 0.0) {
+ WARN("Image height=0.0!");
+ ht0 = 1.0;
+ }
+
+ if ( (p->flags & INFO_HAS_WIDTH ) &&
+ (p->flags & INFO_HAS_HEIGHT) ) {
+ s_x = p->width * xscale;
+ s_y = (p->height + p->depth) * yscale;
+ dp = p->depth * yscale;
+ } else if ( p->flags & INFO_HAS_WIDTH ) {
+ s_x = p->width * xscale;
+ s_y = s_x * ((double)I->attr.height / I->attr.width);
+ dp = 0.0;
+ } else if ( p->flags & INFO_HAS_HEIGHT) {
+ s_y = (p->height + p->depth) * yscale;
+ s_x = s_y * ((double)I->attr.width / I->attr.height);
+ dp = p->depth * yscale;
+ } else {
+ s_x = wd0;
+ s_y = ht0;
+ dp = 0.0;
+ }
+ T->a = s_x; T->c = 0.0;
+ T->b = 0.0; T->d = s_y;
+ T->e = d_x * s_x / xscale; T->f = d_y * s_y / yscale - dp;
+
+ return;
+}
+
+
+static void
+scale_to_fit_F (pdf_tmatrix *T,
+ transform_info *p,
+ pdf_ximage *I)
+{
+ double s_x, s_y, d_x, d_y;
+ double wd0, ht0, dp;
+
+ if (p->flags & INFO_HAS_USER_BBOX) {
+ wd0 = p->bbox.urx - p->bbox.llx;
+ ht0 = p->bbox.ury - p->bbox.lly;
+ d_x = -p->bbox.llx;
+ d_y = -p->bbox.lly;
+ } else {
+ wd0 = I->attr.bbox.urx - I->attr.bbox.llx;
+ ht0 = I->attr.bbox.ury - I->attr.bbox.lly;
+ d_x = 0.0;
+ d_y = 0.0;
+ }
+
+ if (wd0 == 0.0) {
+ WARN("Image width=0.0!");
+ wd0 = 1.0;
+ }
+ if (ht0 == 0.0) {
+ WARN("Image height=0.0!");
+ ht0 = 1.0;
+ }
+
+ if ( (p->flags & INFO_HAS_WIDTH ) &&
+ (p->flags & INFO_HAS_HEIGHT) ) {
+ s_x = p->width / wd0;
+ s_y = (p->height + p->depth) / ht0;
+ dp = p->depth;
+ } else if ( p->flags & INFO_HAS_WIDTH ) {
+ s_x = p->width / wd0;
+ s_y = s_x;
+ dp = 0.0;
+ } else if ( p->flags & INFO_HAS_HEIGHT) {
+ s_y = (p->height + p->depth) / ht0;
+ s_x = s_y;
+ dp = p->depth;
+ } else {
+ s_x = s_y = 1.0;
+ dp = 0.0;
+ }
+
+ T->a = s_x; T->c = 0.0;
+ T->b = 0.0; T->d = s_y;
+ T->e = s_x * d_x; T->f = s_y * d_y - dp;
+
+ return;
+}
+
+
+/* called from pdfdev.c and spc_html.c */
+int
+pdf_ximage_scale_image (int id,
+ pdf_tmatrix *M, /* return value for trans matrix */
+ pdf_rect *r, /* return value for clipping */
+ transform_info *p /* argument from specials */
+ )
+{
+ struct ic_ *ic = &_ic;
+ pdf_ximage *I;
+
+ CHECK_ID(ic, id);
+
+ I = GET_IMAGE(ic, id);
+
+ pdf_setmatrix(M, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
+
+ switch (I->subtype) {
+ /* Reference: PDF Reference 1.5 v6, p.302
+ *
+ * An image can be placed on the output page in any desired position,
+ * orientation, and size by using the cm operator to modify the current
+ * transformation matrix (CTM) so as to map the unit square of user space
+ * to the rectangle or parallelogram in which the image is to be painted.
+ *
+ * There is neither BBox nor Matrix key in the image XObject.
+ * Everything must be controlled by the cm operator.
+ *
+ * The argument [p] contains the user-defined bounding box, the scailing
+ * factor of which is bp as EPS and PDF. On the other hand, I->attr
+ * contains the (sampling) width and the (sampling) height of the image.
+ *
+ * There is no problem if a bitmap image has density information.
+ * Otherwise, DVIPDFM's ebb generates bounding box as 100px = 72bp = 1in.
+ * In this case, screen captured images look bad. Moreover, DVIPDFM's ebb
+ * ignores all density information and use just 100px = 72bp = 1in.
+ *
+ * On the other hand, pdfTeX uses 100px = 100bp to get a better quality
+ * for screen captured images.
+ *
+ * DVIPDFMx's xbb generates bounding box as 100px = 100bp in the same
+ * way as pdfTeX. Furthermore, it takes care of density information too.
+ */
+ case PDF_XOBJECT_TYPE_IMAGE:
+ scale_to_fit_I(M, p, I);
+ if (p->flags & INFO_HAS_USER_BBOX) {
+ r->llx = p->bbox.llx / (I->attr.width * I->attr.xdensity);
+ r->lly = p->bbox.lly / (I->attr.height * I->attr.ydensity);
+ r->urx = p->bbox.urx / (I->attr.width * I->attr.xdensity);
+ r->ury = p->bbox.ury / (I->attr.height * I->attr.ydensity);
+ } else {
+ r->llx = 0.0;
+ r->lly = 0.0;
+ r->urx = 1.0;
+ r->ury = 1.0;
+ }
+ break;
+ /* User-defined transformation and clipping are controlled by
+ * the cm operator and W operator, explicitly */
+ case PDF_XOBJECT_TYPE_FORM:
+ scale_to_fit_F(M, p, I);
+ if (p->flags & INFO_HAS_USER_BBOX) {
+ r->llx = p->bbox.llx;
+ r->lly = p->bbox.lly;
+ r->urx = p->bbox.urx;
+ r->ury = p->bbox.ury;
+ } else { /* I->attr.bbox from the image bounding box */
+ r->llx = I->attr.bbox.llx;
+ r->lly = I->attr.bbox.lly;
+ r->urx = I->attr.bbox.urx;
+ r->ury = I->attr.bbox.ury;
+ }
+ break;
+ }
+
+ return 0;
+}
+
+
+/* Migrated from psimage.c */
+
+void set_distiller_template (char *s)
+{
+ if (_opts.cmdtmpl)
+ RELEASE(_opts.cmdtmpl);
+ if (!s || *s == '\0')
+ _opts.cmdtmpl = NULL;
+ else {
+ _opts.cmdtmpl = NEW(strlen(s) + 1, char);
+ strcpy(_opts.cmdtmpl, s);
+ }
+ return;
+}
+
+char *get_distiller_template (void)
+{
+ return _opts.cmdtmpl;
+}
+
+static int
+ps_include_page (pdf_ximage *ximage, const char *filename)
+{
+ char *distiller_template = _opts.cmdtmpl;
+ char *temp;
+ FILE *fp;
+ int error = 0;
+ struct stat stat_o, stat_t;
+
+ if (!distiller_template) {
+ WARN("No image converter available for converting file \"%s\" to PDF format.", filename);
+ WARN(">> Please check if you have 'D' option in config file.");
+ return -1;
+ }
+
+ temp = dpx_create_fix_temp_file(filename);
+ if (!temp) {
+ WARN("Failed to create temporary file for image conversion: %s", filename);
+ return -1;
+ }
+
+#ifdef MIKTEX
+ {
+ char *p;
+ for (p = (char *)filename; *p; p++) {
+ if (*p == '\\') *p = '/';
+ }
+ for (p = (char *)temp; *p; p++) {
+ if (*p == '\\') *p = '/';
+ }
+ }
+#endif
+ if (keep_cache != -1 && stat(temp, &stat_t)==0 && stat(filename, &stat_o)==0
+ && stat_t.st_mtime > stat_o.st_mtime) {
+ /* cache exist */
+ /*printf("\nLast file modification: %s", ctime(&stat_o.st_mtime));
+ printf("Last file modification: %s", ctime(&stat_t.st_mtime));*/
+ ;
+ } else {
+ if (_opts.verbose > 1) {
+ MESG("\n");
+ MESG("pdf_image>> Converting file \"%s\" --> \"%s\" via:\n", filename, temp);
+ MESG("pdf_image>> %s\n", distiller_template);
+ MESG("pdf_image>> ...");
+ }
+ error = dpx_file_apply_filter(distiller_template, filename, temp,
+ (unsigned char) pdf_get_version());
+ if (error) {
+ WARN("Image format conversion for \"%s\" failed...", filename);
+ dpx_delete_temp_file(temp, true);
+ return error;
+ }
+ }
+
+ fp = MFOPEN(temp, FOPEN_RBIN_MODE);
+ if (!fp) {
+ WARN("Could not open conversion result \"%s\" for image \"%s\". Why?", temp, filename);
+ dpx_delete_temp_file(temp, true);
+ return -1;
+ }
+ pdf_set_ximage_tempfile(ximage, temp);
+// error = pdf_include_page(ximage, fp, 0, pdfbox_crop);
+ error = pdf_include_page(ximage, fp);
+ MFCLOSE(fp);
+
+ /* See pdf_close_images for why we cannot delete temporary files here. */
+
+ RELEASE(temp);
+
+ if (error) {
+ WARN("Failed to include image file \"%s\"", filename);
+ WARN(">> Please check if");
+ WARN(">> %s", distiller_template);
+ WARN(">> %%o = output filename, %%i = input filename, %%b = input filename without suffix");
+ WARN(">> can really convert \"%s\" to PDF format image.", filename);
+ }
+
+ return error;
+}
+
+static int check_for_ps (FILE *image_file)
+{
+ rewind (image_file);
+ mfgets (work_buffer, WORK_BUFFER_SIZE, image_file);
+ if (!strncmp (work_buffer, "%!", 2))
+ return 1;
+ return 0;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/pdfximage.h b/Build/source/texk/dvipdf-x/xsrc/pdfximage.h
new file mode 100644
index 00000000000..b1746aa3383
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pdfximage.h
@@ -0,0 +1,92 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2007-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _PDFXIMAGE_H_
+#define _PDFXIMAGE_H_
+
+#include "pdfdev.h"
+
+#define PDF_XOBJECT_TYPE_FORM 0
+#define PDF_XOBJECT_TYPE_IMAGE 1
+
+typedef struct {
+ int flags;
+
+ long width;
+ long height;
+
+ int bits_per_component;
+ int num_components;
+
+ long min_dpi; /* NOT USED YET */
+
+ double xdensity, ydensity; /* scale factor for bp */
+} ximage_info;
+
+typedef struct {
+ int flags;
+
+ pdf_rect bbox;
+ pdf_tmatrix matrix;
+} xform_info;
+
+typedef struct pdf_ximage_ pdf_ximage;
+
+extern void pdf_ximage_set_verbose (void);
+
+extern void pdf_init_images (void);
+extern void pdf_close_images (void);
+
+extern char *pdf_ximage_get_resname (int xobj_id);
+extern pdf_obj *pdf_ximage_get_reference (int xobj_id);
+
+
+extern int pdf_ximage_findresource (const char *ident, long page_no,
+ pdf_obj *dict);
+extern int pdf_ximage_defineresource (const char *ident, int subtype,
+ void *cdata, pdf_obj *resource);
+
+/* Called by pngimage, jpegimage, epdf, mpost, etc. */
+extern void pdf_ximage_init_image_info (ximage_info *info);
+extern void pdf_ximage_init_form_info (xform_info *info);
+extern char *pdf_ximage_get_ident (pdf_ximage *ximage);
+extern void pdf_ximage_set_image (pdf_ximage *ximage, void *info, pdf_obj *resource);
+extern void pdf_ximage_set_form (pdf_ximage *ximage, void *info, pdf_obj *resource);
+extern void pdf_ximage_set_page (pdf_ximage *ximage, long page_no, long page_count);
+extern long pdf_ximage_get_page (pdf_ximage *I);
+
+/* from psimage.h */
+extern void set_distiller_template (char *s);
+extern char *get_distiller_template (void);
+
+extern int
+pdf_ximage_scale_image (int id,
+ pdf_tmatrix *M, /* ret */
+ pdf_rect *r, /* ret */
+ transform_info *p /* arg */
+ );
+
+/* from dvipdfmx.c */
+extern void pdf_ximage_disable_ebb (void);
+#endif /* _PDFXIMAGE_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/pngimage.c b/Build/source/texk/dvipdf-x/xsrc/pngimage.c
new file mode 100644
index 00000000000..f60983a7c40
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pngimage.c
@@ -0,0 +1,1013 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+/*
+ * PNG SUPPORT
+ *
+ * All bitdepth less than 16 is supported.
+ * Supported color types are: PALETTE, RGB, GRAY, RGB_ALPHA, GRAY_ALPHA.
+ * Supported ancillary chunks: tRNS, cHRM + gAMA, (sRGB), (iCCP)
+ *
+ * gAMA support is available only when cHRM exists. cHRM support is not
+ * tested well. CalRGB/CalGray colorspace is used for PNG images that
+ * have cHRM chunk (but not sRGB).
+ *
+ * LIMITATIONS
+ *
+ * Recent version of PDF (>= 1.5) support 16 bpc, but 16 bit bitdepth PNG
+ * images are automatically converted to 8 bit bitpedth image.
+ *
+ * TODO
+ *
+ * sBIT ? iTXT, tEXT and tIME as MetaData ?, pHYS (see below)
+ * 16 bpc support for PDF-1.5. JBIG compression for monochrome image.
+ * Predictor for deflate ?
+ */
+
+#include "system.h"
+#include "error.h"
+#include "mem.h"
+
+#include "pdfcolor.h"
+#include "pdfobj.h"
+
+#define PNG_DEBUG_STR "PNG"
+#define PNG_DEBUG 3
+
+#ifdef HAVE_LIBPNG
+
+/*
+ * Write, MNG, Progressive not required.
+ */
+#define PNG_NO_WRITE_SUPPORTED
+#define PNG_NO_MNG_FEATURES
+#define PNG_NO_PROGRESSIVE_READ
+#if 0
+/* 16_TO_8 required. */
+#define PNG_NO_READ_TRANSFORMS
+#endif
+
+#include <png.h>
+#include "pngimage.h"
+
+#include "pdfximage.h"
+
+#define PDF_TRANS_TYPE_NONE 0
+#define PDF_TRANS_TYPE_BINARY 1
+#define PDF_TRANS_TYPE_ALPHA 2
+
+/* ColorSpace */
+static pdf_obj *create_cspace_Indexed (png_structp png_ptr, png_infop info_ptr);
+
+/* CIE-Based: CalRGB/CalGray
+ *
+ * We ignore gAMA if cHRM is not found.
+ */
+static pdf_obj *create_cspace_CalRGB (png_structp png_ptr, png_infop info_ptr);
+static pdf_obj *create_cspace_CalGray (png_structp png_ptr, png_infop info_ptr);
+static pdf_obj *make_param_Cal (png_byte color_type,
+ double G,
+ double xw, double yw,
+ double xr, double yr,
+ double xg, double yg,
+ double xb, double yb);
+
+/* sRGB:
+ *
+ * We (and PDF) do not have direct sRGB support. The sRGB color space can be
+ * precisely represented by ICC profile, but we use approximate CalRGB color
+ * space.
+ */
+static pdf_obj *create_cspace_sRGB (png_structp png_ptr, png_infop info_ptr);
+static pdf_obj *get_rendering_intent (png_structp png_ptr, png_infop info_ptr);
+
+/* ICCBased:
+ *
+ * Not supported yet.
+ * Must check if ICC profile is valid and can be imported to PDF.
+ * There are few restrictions (should be applied to PNG too?) in ICC profile
+ * support in PDF. Some information should be obtained from profile.
+ */
+static pdf_obj *create_cspace_ICCBased (png_structp png_ptr, png_infop info_ptr);
+
+/* Transparency */
+static int check_transparency (png_structp png_ptr, png_infop info_ptr);
+/* Color-Key Mask */
+static pdf_obj *create_ckey_mask (png_structp png_ptr, png_infop info_ptr);
+/* Soft Mask:
+ *
+ * create_soft_mask() is for PNG_COLOR_TYPE_PALLETE.
+ * Images with alpha chunnel use strip_soft_mask().
+ * An object representing mask itself is returned.
+ */
+static pdf_obj *create_soft_mask (png_structp png_ptr, png_infop info_ptr,
+ png_bytep image_data_ptr,
+ png_uint_32 width, png_uint_32 height);
+static pdf_obj *strip_soft_mask (png_structp png_ptr, png_infop info_ptr,
+ png_bytep image_data_ptr,
+ png_uint_32p rowbytes_ptr,
+ png_uint_32 width, png_uint_32 height);
+
+/* Read image body */
+static void read_image_data (png_structp png_ptr, png_infop info_ptr,
+ png_bytep dest_ptr,
+ png_uint_32 height, png_uint_32 rowbytes);
+
+int
+check_for_png (FILE *png_file)
+{
+ unsigned char sigbytes[4];
+
+ rewind (png_file);
+ if (fread (sigbytes, 1, sizeof(sigbytes), png_file) !=
+ sizeof(sigbytes) ||
+ (png_sig_cmp (sigbytes, 0, sizeof(sigbytes))))
+ return 0;
+ else
+ return 1;
+}
+
+int
+png_include_image (pdf_ximage *ximage, FILE *png_file)
+{
+ pdf_obj *stream;
+ pdf_obj *stream_dict;
+ pdf_obj *colorspace, *mask, *intent;
+ png_bytep stream_data_ptr;
+ int trans_type;
+ ximage_info info;
+ /* Libpng stuff */
+ png_structp png_ptr;
+ png_infop png_info_ptr;
+ png_byte bpc, color_type;
+ png_uint_32 width, height, rowbytes, xppm, yppm;
+
+ pdf_ximage_init_image_info(&info);
+
+ stream = NULL;
+ stream_dict = NULL;
+ colorspace = mask = intent = NULL;
+
+ rewind (png_file);
+ png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+ if (png_ptr == NULL ||
+ (png_info_ptr = png_create_info_struct (png_ptr)) == NULL) {
+ WARN("%s: Creating Libpng read/info struct failed.", PNG_DEBUG_STR);
+ if (png_ptr)
+ png_destroy_read_struct(&png_ptr, NULL, NULL);
+ return -1;
+ }
+
+ /* Inititializing file IO. */
+ png_init_io (png_ptr, png_file);
+
+ /* Read PNG info-header and get some info. */
+ png_read_info(png_ptr, png_info_ptr);
+ color_type = png_get_color_type (png_ptr, png_info_ptr);
+ width = png_get_image_width (png_ptr, png_info_ptr);
+ height = png_get_image_height(png_ptr, png_info_ptr);
+ bpc = png_get_bit_depth (png_ptr, png_info_ptr);
+ xppm = png_get_x_pixels_per_meter(png_ptr, png_info_ptr);
+ yppm = png_get_y_pixels_per_meter(png_ptr, png_info_ptr);
+
+ /* We do not need 16-bpc color. Ask libpng to convert down to 8-bpc. */
+ if (bpc > 8) {
+ png_set_strip_16(png_ptr);
+ bpc = 8;
+ }
+
+ trans_type = check_transparency(png_ptr, png_info_ptr);
+ /* check_transparency() does not do updata_info() */
+ png_read_update_info(png_ptr, png_info_ptr);
+ rowbytes = png_get_rowbytes(png_ptr, png_info_ptr);
+
+ stream = pdf_new_stream (STREAM_COMPRESS);
+ stream_dict = pdf_stream_dict(stream);
+
+ /* Values listed below will not be modified in the remaining process. */
+ info.width = width;
+ info.height = height;
+ info.bits_per_component = bpc;
+ if (xppm > 0)
+ info.xdensity = 72.0 / 0.0254 / xppm;
+ if (yppm > 0)
+ info.ydensity = 72.0 / 0.0254 / yppm;
+
+ stream_data_ptr = (png_bytep) NEW(rowbytes*height, png_byte);
+ read_image_data(png_ptr, png_info_ptr, stream_data_ptr, height, rowbytes);
+
+ /* Non-NULL intent means there is valid sRGB chunk. */
+ intent = get_rendering_intent(png_ptr, png_info_ptr);
+ if (intent)
+ pdf_add_dict(stream_dict, pdf_new_name("Intent"), intent);
+
+ switch (color_type) {
+ case PNG_COLOR_TYPE_PALETTE:
+
+ colorspace = create_cspace_Indexed(png_ptr, png_info_ptr);
+
+ switch (trans_type) {
+ case PDF_TRANS_TYPE_BINARY:
+ /* Color-key masking */
+ mask = create_ckey_mask(png_ptr, png_info_ptr);
+ break;
+ case PDF_TRANS_TYPE_ALPHA:
+ /* Soft mask */
+ mask = create_soft_mask(png_ptr, png_info_ptr, stream_data_ptr, width, height);
+ break;
+ default:
+ /* Nothing to be done here.
+ * No tRNS chunk or image already composited with background color.
+ */
+ break;
+ }
+ break;
+ case PNG_COLOR_TYPE_RGB:
+ case PNG_COLOR_TYPE_RGB_ALPHA:
+
+ if (png_get_valid(png_ptr, png_info_ptr, PNG_INFO_iCCP))
+ colorspace = create_cspace_ICCBased(png_ptr, png_info_ptr);
+ else if (intent) {
+ colorspace = create_cspace_sRGB(png_ptr, png_info_ptr);
+ } else {
+ colorspace = create_cspace_CalRGB(png_ptr, png_info_ptr);
+ }
+ if (!colorspace)
+ colorspace = pdf_new_name("DeviceRGB");
+
+ switch (trans_type) {
+ case PDF_TRANS_TYPE_BINARY:
+ if (color_type != PNG_COLOR_TYPE_RGB)
+ ERROR("Unexpected error in png_include_image().");
+ mask = create_ckey_mask(png_ptr, png_info_ptr);
+ break;
+ /* rowbytes changes 4 to 3 at here */
+ case PDF_TRANS_TYPE_ALPHA:
+ if (color_type != PNG_COLOR_TYPE_RGB_ALPHA)
+ ERROR("Unexpected error in png_include_image().");
+ mask = strip_soft_mask(png_ptr, png_info_ptr,
+ stream_data_ptr, &rowbytes, width, height);
+ break;
+ default:
+ mask = NULL;
+ }
+ info.num_components = 3;
+ break;
+
+ case PNG_COLOR_TYPE_GRAY:
+ case PNG_COLOR_TYPE_GRAY_ALPHA:
+
+ if (png_get_valid(png_ptr, png_info_ptr, PNG_INFO_iCCP))
+ colorspace = create_cspace_ICCBased(png_ptr, png_info_ptr);
+ else if (intent) {
+ colorspace = create_cspace_sRGB(png_ptr, png_info_ptr);
+ } else {
+ colorspace = create_cspace_CalGray(png_ptr, png_info_ptr);
+ }
+ if (!colorspace)
+ colorspace = pdf_new_name("DeviceGray");
+
+ switch (trans_type) {
+ case PDF_TRANS_TYPE_BINARY:
+ if (color_type != PNG_COLOR_TYPE_GRAY)
+ ERROR("Unexpected error in png_include_image().");
+ mask = create_ckey_mask(png_ptr, png_info_ptr);
+ break;
+ case PDF_TRANS_TYPE_ALPHA:
+ if (color_type != PNG_COLOR_TYPE_GRAY_ALPHA)
+ ERROR("Unexpected error in png_include_image().");
+ mask = strip_soft_mask(png_ptr, png_info_ptr,
+ stream_data_ptr, &rowbytes, width, height);
+ break;
+ default:
+ mask = NULL;
+ }
+ info.num_components = 1;
+ break;
+
+ default:
+ WARN("%s: Unknown PNG colortype %d.", PNG_DEBUG_STR, color_type);
+ }
+ pdf_add_dict(stream_dict, pdf_new_name("ColorSpace"), colorspace);
+
+ pdf_add_stream(stream, stream_data_ptr, rowbytes*height);
+ RELEASE(stream_data_ptr);
+
+ if (mask) {
+ if (trans_type == PDF_TRANS_TYPE_BINARY)
+ pdf_add_dict(stream_dict, pdf_new_name("Mask"), mask);
+ else if (trans_type == PDF_TRANS_TYPE_ALPHA) {
+ pdf_add_dict(stream_dict, pdf_new_name("SMask"), pdf_ref_obj(mask));
+ pdf_release_obj(mask);
+ } else {
+ WARN("%s: You found a bug in pngimage.c.", PNG_DEBUG_STR);
+ pdf_release_obj(mask);
+ }
+ }
+
+ png_read_end(png_ptr, NULL);
+
+ /* Cleanup */
+ if (png_info_ptr)
+ png_destroy_info_struct(png_ptr, &png_info_ptr);
+ if (png_ptr)
+ png_destroy_read_struct(&png_ptr, NULL, NULL);
+
+ pdf_ximage_set_image(ximage, &info, stream);
+
+ return 0;
+}
+
+/*
+ * The returned value trans_type is the type of transparency to be used for
+ * this image. Possible values are:
+ *
+ * PDF_TRANS_TYPE_NONE No Masking will be used/required.
+ * PDF_TRANS_TYPE_BINARY Pixels are either fully opaque/fully transparent.
+ * PDF_TRANS_TYPE_ALPHA Uses alpha channel, requies SMask.(PDF-1.4)
+ *
+ * check_transparency() must check the current setting of output PDF version
+ * and must choose appropriate trans_type value according to PDF version of
+ * current output PDF document.
+ *
+ * If the PDF version is less than 1.3, no transparency is supported for this
+ * version of PDF, hence PDF_TRANS_TYPE_NONE must be returned. And when the PDF
+ * version is equal to 1.3, possible retrun values are PDF_TRANS_TYPE_BINARY or
+ * PDF_TRANS_TYPE_NONE. The latter case arises when PNG file uses alpha channel
+ * explicitly (color type PNG_COLOR_TYPE_XXX_ALPHA), or the tRNS chunk for the
+ * PNG_COLOR_TYPE_PALETTE image contains intermediate values of opacity.
+ *
+ * Finally, in the case of PDF version 1.4, all kind of translucent pixels can
+ * be represented with Soft-Mask.
+ */
+
+static int
+check_transparency (png_structp png_ptr, png_infop info_ptr)
+{
+ int trans_type;
+ unsigned pdf_version;
+ png_byte color_type;
+ png_color_16p trans_values;
+ png_bytep trans;
+ int num_trans;
+
+ pdf_version = pdf_get_version();
+ color_type = png_get_color_type(png_ptr, info_ptr);
+
+ /*
+ * First we set trans_type to appropriate value for PNG image.
+ */
+ if (color_type == PNG_COLOR_TYPE_RGB_ALPHA ||
+ color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
+ trans_type = PDF_TRANS_TYPE_ALPHA;
+ } else if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) &&
+ png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, &trans_values)) {
+ /* Have valid tRNS chunk. */
+ switch (color_type) {
+ case PNG_COLOR_TYPE_PALETTE:
+ /* Use color-key mask if possible. */
+ trans_type = PDF_TRANS_TYPE_BINARY;
+ while (num_trans-- > 0) {
+ if (trans[num_trans] != 0x00 && trans[num_trans] != 0xff) {
+ /* This seems not binary transparency */
+ trans_type = PDF_TRANS_TYPE_ALPHA;
+ break;
+ }
+ }
+ break;
+ case PNG_COLOR_TYPE_GRAY:
+ case PNG_COLOR_TYPE_RGB:
+ /* RGB or GRAY, single color specified by trans_values is transparent. */
+ trans_type = PDF_TRANS_TYPE_BINARY;
+ break;
+ default:
+ /* Else tRNS silently ignored. */
+ trans_type = PDF_TRANS_TYPE_NONE;
+ }
+ } else { /* no transparency */
+ trans_type = PDF_TRANS_TYPE_NONE;
+ }
+
+ /*
+ * Now we check PDF version.
+ * We can convert alpha cahnnels to explicit mask via user supplied alpha-
+ * threshold value. But I will not do that.
+ */
+ if (( pdf_version < 3 && trans_type != PDF_TRANS_TYPE_NONE ) ||
+ ( pdf_version < 4 && trans_type == PDF_TRANS_TYPE_ALPHA )) {
+ /*
+ * No transparency supported but PNG uses transparency, or Soft-Mask
+ * required but no support for it is available in this version of PDF.
+ * We must do pre-composition of image with the background image here. But,
+ * we cannot do that in general since dvipdfmx is not a rasterizer. What we
+ * can do here is to composite image with a rectangle filled with the
+ * background color. However, images are stored as an Image XObject which
+ * can be referenced anywhere in the PDF document content. Hence, we cannot
+ * know the correct background color at this time. So we will choose white
+ * as background color, which is most probable color in our cases.
+ * We ignore bKGD chunk.
+ */
+ png_color_16 bg;
+ bg.red = 255; bg.green = 255; bg.blue = 255; bg.gray = 255; bg.index = 0;
+ png_set_background(png_ptr, &bg, PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
+ WARN("%s: Transparency will be ignored. (no support in PDF ver. < 1.3)", PNG_DEBUG_STR);
+ if (pdf_version < 3)
+ WARN("%s: Please use -V 3 option to enable binary transparency support.", PNG_DEBUG_STR);
+ if (pdf_version < 4)
+ WARN("%s: Please use -V 4 option to enable full alpha channel support.", PNG_DEBUG_STR);
+ trans_type = PDF_TRANS_TYPE_NONE;
+ }
+
+ return trans_type;
+}
+
+/*
+ * sRGB:
+ *
+ * If sRGB chunk is present, cHRM and gAMA chunk must be ignored.
+ *
+ */
+static pdf_obj *
+get_rendering_intent (png_structp png_ptr, png_infop info_ptr)
+{
+ pdf_obj *intent;
+ int srgb_intent;
+
+ if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB) &&
+ png_get_sRGB (png_ptr, info_ptr, &srgb_intent)) {
+ switch (srgb_intent) {
+ case PNG_sRGB_INTENT_SATURATION:
+ intent = pdf_new_name("Saturation");
+ break;
+ case PNG_sRGB_INTENT_PERCEPTUAL:
+ intent = pdf_new_name("Perceptual");
+ break;
+ case PNG_sRGB_INTENT_ABSOLUTE:
+ intent = pdf_new_name("AbsoluteColorimetric");
+ break;
+ case PNG_sRGB_INTENT_RELATIVE:
+ intent = pdf_new_name("RelativeColorimetric");
+ break;
+ default:
+ WARN("%s: Invalid value in PNG sRGB chunk: %d", PNG_DEBUG_STR, srgb_intent);
+ intent = NULL;
+ }
+ } else
+ intent = NULL;
+
+ return intent;
+}
+
+/* Approximated sRGB */
+static pdf_obj *
+create_cspace_sRGB (png_structp png_ptr, png_infop info_ptr)
+{
+ pdf_obj *colorspace;
+ pdf_obj *cal_param;
+ png_byte color_type;
+
+ color_type = png_get_color_type(png_ptr, info_ptr);
+
+ /* Parameters taken from PNG spec. section 4.2.2.3. */
+ cal_param = make_param_Cal(color_type,
+ 2.2,
+ 0.3127, 0.329,
+ 0.64, 0.33, 0.3, 0.6, 0.15, 0.06);
+ if (!cal_param)
+ return NULL;
+
+ colorspace = pdf_new_array();
+
+ switch (color_type) {
+ case PNG_COLOR_TYPE_RGB:
+ case PNG_COLOR_TYPE_RGB_ALPHA:
+ case PNG_COLOR_TYPE_PALETTE:
+ pdf_add_array(colorspace, pdf_new_name("CalRGB"));
+ break;
+ case PNG_COLOR_TYPE_GRAY:
+ case PNG_COLOR_TYPE_GRAY_ALPHA:
+ pdf_add_array(colorspace, pdf_new_name("CalGray"));
+ break;
+ }
+ pdf_add_array(colorspace, cal_param);
+
+ return colorspace;
+}
+
+static pdf_obj *
+create_cspace_ICCBased (png_structp png_ptr, png_infop info_ptr)
+{
+ pdf_obj *colorspace;
+ int csp_id, colortype;
+ png_byte color_type;
+ png_charp name;
+ int compression_type; /* Manual page for libpng does not
+ * clarify whether profile data is inflated by libpng.
+ */
+#if PNG_LIBPNG_VER_MINOR < 5
+ png_charp profile;
+#else
+ png_bytep profile;
+#endif
+ png_uint_32 proflen;
+
+ if (!png_get_valid(png_ptr, info_ptr, PNG_INFO_iCCP) ||
+ !png_get_iCCP(png_ptr, info_ptr, &name, &compression_type, &profile, &proflen))
+ return NULL;
+
+ color_type = png_get_color_type(png_ptr, info_ptr);
+
+ if (color_type & PNG_COLOR_MASK_COLOR) {
+ colortype = PDF_COLORSPACE_TYPE_RGB;
+#if 0
+ alternate = create_cspace_CalRGB(png_ptr, info_ptr);
+#endif
+ } else {
+ colortype = PDF_COLORSPACE_TYPE_GRAY;
+#if 0
+ alternate = create_cspace_CalGray(png_ptr, info_ptr);
+#endif
+ }
+
+#if 0
+ if (alternate)
+ pdf_add_dict(dict, pdf_new_name("Alternate"), alternate);
+#endif
+
+ if (iccp_check_colorspace(colortype, profile, proflen) < 0)
+ colorspace = NULL;
+ else {
+ csp_id = iccp_load_profile(name, profile, proflen);
+ if (csp_id < 0) {
+ colorspace = NULL;
+ } else {
+ colorspace = pdf_get_colorspace_reference(csp_id);
+ }
+ }
+
+ /* Rendering intent ... */
+
+ return colorspace;
+}
+
+/*
+ * gAMA, cHRM:
+ *
+ * If cHRM is present, we use CIE-Based color space. gAMA is also used here
+ * if available.
+ */
+
+#define INVALID_CHRM_VALUE(xw,yw,xr,yr,xg,yg,xb,yb) (\
+ (xw) <= 0.0 || (yw) < 1.0e-10 || \
+ (xr) < 0.0 || (yr) < 0.0 || (xg) < 0.0 || (yg) < 0.0 || \
+ (xb) < 0.0 || (yb) < 0.0)
+
+static pdf_obj *
+create_cspace_CalRGB (png_structp png_ptr, png_infop info_ptr)
+{
+ pdf_obj *colorspace;
+ pdf_obj *cal_param;
+ double xw, yw, xr, yr, xg, yg, xb, yb;
+ double G;
+
+ if (!png_get_valid(png_ptr, info_ptr, PNG_INFO_cHRM) ||
+ !png_get_cHRM(png_ptr, info_ptr, &xw, &yw, &xr, &yr, &xg, &yg, &xb, &yb))
+ return NULL;
+
+ if (xw <= 0.0 || yw < 1.0e-10 ||
+ xr < 0.0 || yr < 0.0 || xg < 0.0 || yg < 0.0 || xb < 0.0 || yb < 0.0) {
+ WARN("%s: Invalid cHRM chunk parameters found.", PNG_DEBUG_STR);
+ return NULL;
+ }
+
+ if (png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) &&
+ png_get_gAMA (png_ptr, info_ptr, &G)) {
+ if (G < 1.0e-2) {
+ WARN("%s: Unusual Gamma value: %g", PNG_DEBUG_STR, G);
+ return NULL;
+ }
+ G = 1.0 / G; /* Gamma is inverted. */
+ } else {
+ G = 1.0;
+ }
+
+ cal_param = make_param_Cal(PNG_COLOR_TYPE_RGB, G, xw, yw, xr, yr, xg, yg, xb, yb);
+
+ if (!cal_param)
+ return NULL;
+
+ colorspace = pdf_new_array();
+ pdf_add_array(colorspace, pdf_new_name("CalRGB"));
+ pdf_add_array(colorspace, cal_param);
+
+ return colorspace;
+}
+
+static pdf_obj *
+create_cspace_CalGray (png_structp png_ptr, png_infop info_ptr)
+{
+ pdf_obj *colorspace;
+ pdf_obj *cal_param;
+ double xw, yw, xr, yr, xg, yg, xb, yb;
+ double G;
+
+ if (!png_get_valid(png_ptr, info_ptr, PNG_INFO_cHRM) ||
+ !png_get_cHRM(png_ptr, info_ptr, &xw, &yw, &xr, &yr, &xg, &yg, &xb, &yb))
+ return NULL;
+
+ if (xw <= 0.0 || yw < 1.0e-10 ||
+ xr < 0.0 || yr < 0.0 || xg < 0.0 || yg < 0.0 || xb < 0.0 || yb < 0.0) {
+ WARN("%s: Invalid cHRM chunk parameters found.", PNG_DEBUG_STR);
+ return NULL;
+ }
+
+ if (png_get_valid(png_ptr, info_ptr, PNG_INFO_gAMA) &&
+ png_get_gAMA (png_ptr, info_ptr, &G)) {
+ if (G < 1.0e-2) {
+ WARN("%s: Unusual Gamma value: %g", PNG_DEBUG_STR, G);
+ return NULL;
+ }
+ G = 1.0 / G; /* Gamma is inverted. */
+ } else {
+ G = 1.0;
+ }
+
+ cal_param = make_param_Cal(PNG_COLOR_TYPE_GRAY, G, xw, yw, xr, yr, xg, yg, xb, yb);
+
+ if (!cal_param)
+ return NULL;
+
+ colorspace = pdf_new_array();
+ pdf_add_array(colorspace, pdf_new_name("CalGray"));
+ pdf_add_array(colorspace, cal_param);
+
+ return colorspace;
+}
+
+static pdf_obj *
+make_param_Cal (png_byte color_type,
+ double G, /* Gamma */
+ double xw, double yw,
+ double xr, double yr, double xg, double yg, double xb, double yb)
+{
+ pdf_obj *cal_param;
+ pdf_obj *white_point, *matrix, *dev_gamma;
+ double Xw, Yw, Zw; /* Yw = 1.0 */
+ double Xr, Xg, Xb, Yr, Yb, Yg, Zr, Zg, Zb;
+
+#ifndef ABS
+#define ABS(x) ((x) < 0 ? -(x) : (x))
+#endif
+ /*
+ * TODO: Check validity
+ *
+ * Conversion found in
+ *
+ * com.sixlegs.image.png - Java package to read and display PNG images
+ * Copyright (C) 1998, 1999, 2001 Chris Nokleberg
+ *
+ * http://www.sixlegs.com/software/png/
+ *
+ */
+ {
+ double zw, zr, zg, zb;
+ double fr, fg, fb;
+ double det;
+
+ /* WhitePoint */
+ zw = 1 - (xw + yw);
+ zr = 1 - (xr + yr); zg = 1 - (xg + yg); zb = 1 - (xb + yb);
+ Xw = xw / yw; Yw = 1.0; Zw = zw / yw;
+
+ /* Matrix */
+ det = xr * (yg * zb - zg * yb) - xg * (yr * zb - zr * yb) + xb * (yr * zg - zr * yg);
+ if (ABS(det) < 1.0e-10) {
+ WARN("Non invertible matrix: Maybe invalid value(s) specified in cHRM chunk.");
+ return NULL;
+ }
+ fr = (Xw * (yg * zb - zg * yb) - xg * (zb - Zw * yb) + xb * (zg - Zw * yg)) / det;
+ fg = (xr * (zb - Zw * yb) - Xw * (yr * zb - zr * yb) + xb * (yr * Zw - zr)) / det;
+ fb = (xr * (yg * Zw - zg) - xg * (yr * Zw - zr) + Xw * (yr * zg - zr * yg)) / det;
+ Xr = fr * xr; Yr = fr * yr; Zr = fr * zr;
+ Xg = fg * xg; Yg = fg * yg; Zg = fg * zg;
+ Xb = fb * xb; Yb = fb * yb; Zb = fb * zb;
+ }
+
+ if (G < 1.0e-2) {
+ WARN("Unusual Gamma specified: %g", G);
+ return NULL;
+ }
+
+ cal_param = pdf_new_dict();
+
+ /* White point is always required. */
+ white_point = pdf_new_array();
+ pdf_add_array(white_point, pdf_new_number(ROUND(Xw, 0.00001)));
+ pdf_add_array(white_point, pdf_new_number(ROUND(Yw, 0.00001)));
+ pdf_add_array(white_point, pdf_new_number(ROUND(Zw, 0.00001)));
+ pdf_add_dict(cal_param, pdf_new_name("WhitePoint"), white_point);
+
+ /* Matrix - default: Identity */
+ if (color_type & PNG_COLOR_MASK_COLOR) {
+ if (G != 1.0) {
+ dev_gamma = pdf_new_array();
+ pdf_add_array(dev_gamma, pdf_new_number(ROUND(G, 0.00001)));
+ pdf_add_array(dev_gamma, pdf_new_number(ROUND(G, 0.00001)));
+ pdf_add_array(dev_gamma, pdf_new_number(ROUND(G, 0.00001)));
+ pdf_add_dict(cal_param, pdf_new_name("Gamma"), dev_gamma);
+ }
+
+ matrix = pdf_new_array();
+ pdf_add_array(matrix, pdf_new_number(ROUND(Xr, 0.00001)));
+ pdf_add_array(matrix, pdf_new_number(ROUND(Yr, 0.00001)));
+ pdf_add_array(matrix, pdf_new_number(ROUND(Zr, 0.00001)));
+ pdf_add_array(matrix, pdf_new_number(ROUND(Xg, 0.00001)));
+ pdf_add_array(matrix, pdf_new_number(ROUND(Yg, 0.00001)));
+ pdf_add_array(matrix, pdf_new_number(ROUND(Zg, 0.00001)));
+ pdf_add_array(matrix, pdf_new_number(ROUND(Xb, 0.00001)));
+ pdf_add_array(matrix, pdf_new_number(ROUND(Yb, 0.00001)));
+ pdf_add_array(matrix, pdf_new_number(ROUND(Zb, 0.00001)));
+ pdf_add_dict (cal_param, pdf_new_name("Matrix"), matrix);
+ } else { /* Gray */
+ if (G != 1.0)
+ pdf_add_dict(cal_param,
+ pdf_new_name("Gamma"),
+ pdf_new_number(ROUND(G, 0.00001)));
+ }
+
+ return cal_param;
+}
+
+/*
+ * Set up Indexed ColorSpace for color-type PALETTE:
+ *
+ * PNG allows only RGB color for base color space. If gAMA and/or cHRM
+ * chunk is available, we can use CalRGB color space instead of DeviceRGB
+ * for base color space.
+ *
+ */
+static pdf_obj *
+create_cspace_Indexed (png_structp png_ptr, png_infop info_ptr)
+{
+ pdf_obj *colorspace;
+ pdf_obj *base, *lookup;
+ png_byte *data_ptr;
+ png_colorp plte;
+ int num_plte, i;
+
+ if (!png_get_valid(png_ptr, info_ptr, PNG_INFO_PLTE) ||
+ !png_get_PLTE(png_ptr, info_ptr, &plte, &num_plte)) {
+ WARN("%s: PNG does not have valid PLTE chunk.", PNG_DEBUG_STR);
+ return NULL;
+ }
+
+ /* Order is important. */
+ colorspace = pdf_new_array ();
+ pdf_add_array(colorspace, pdf_new_name("Indexed"));
+
+ if (png_get_valid(png_ptr, info_ptr, PNG_INFO_iCCP))
+ base = create_cspace_ICCBased(png_ptr, info_ptr);
+ else {
+ if (png_get_valid(png_ptr, info_ptr, PNG_INFO_sRGB))
+ base = create_cspace_sRGB(png_ptr, info_ptr);
+ else
+ base = create_cspace_CalRGB(png_ptr, info_ptr);
+ }
+
+ if (!base)
+ base = pdf_new_name("DeviceRGB");
+
+ pdf_add_array(colorspace, base);
+ pdf_add_array(colorspace, pdf_new_number(num_plte-1));
+ data_ptr = NEW(num_plte*3, png_byte);
+ for (i = 0; i < num_plte; i++) {
+ data_ptr[3*i] = plte[i].red;
+ data_ptr[3*i+1] = plte[i].green;
+ data_ptr[3*i+2] = plte[i].blue;
+ }
+ lookup = pdf_new_string(data_ptr, num_plte*3);
+ RELEASE(data_ptr);
+ pdf_add_array(colorspace, lookup);
+
+ return colorspace;
+}
+
+/*
+ * pHYs: no support
+ *
+ * pngimage.c is not responsible for adjusting image size.
+ * Higher layer must do something for this.
+ */
+
+/*
+ * Colorkey Mask: array
+ *
+ * [component_0_min component_0_max ... component_n_min component_n_max]
+ *
+ */
+
+static pdf_obj *
+create_ckey_mask (png_structp png_ptr, png_infop info_ptr)
+{
+ pdf_obj *colorkeys;
+ png_byte color_type;
+ png_bytep trans;
+ int num_trans, i;
+ png_color_16p colors;
+
+ if (!png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ||
+ !png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, &colors)) {
+ WARN("%s: PNG does not have valid tRNS chunk!", PNG_DEBUG_STR);
+ return NULL;
+ }
+
+ colorkeys = pdf_new_array();
+ color_type = png_get_color_type(png_ptr, info_ptr);
+
+ switch (color_type) {
+ case PNG_COLOR_TYPE_PALETTE:
+ for (i = 0; i < num_trans; i++) {
+ if (trans[i] == 0x00) {
+ pdf_add_array(colorkeys, pdf_new_number(i));
+ pdf_add_array(colorkeys, pdf_new_number(i));
+ } else if (trans[i] != 0xff) {
+ WARN("%s: You found a bug in pngimage.c.", PNG_DEBUG_STR);
+ }
+ }
+ break;
+ case PNG_COLOR_TYPE_RGB:
+ pdf_add_array(colorkeys, pdf_new_number(colors->red));
+ pdf_add_array(colorkeys, pdf_new_number(colors->red));
+ pdf_add_array(colorkeys, pdf_new_number(colors->green));
+ pdf_add_array(colorkeys, pdf_new_number(colors->green));
+ pdf_add_array(colorkeys, pdf_new_number(colors->blue));
+ pdf_add_array(colorkeys, pdf_new_number(colors->blue));
+ break;
+ case PNG_COLOR_TYPE_GRAY:
+ pdf_add_array(colorkeys, pdf_new_number(colors->gray));
+ pdf_add_array(colorkeys, pdf_new_number(colors->gray));
+ break;
+ default:
+ WARN("%s: You found a bug in pngimage.c.", PNG_DEBUG_STR);
+ pdf_release_obj(colorkeys);
+ colorkeys = NULL;
+ }
+
+ return colorkeys;
+}
+
+/*
+ * Soft-Mask: stream
+ *
+ * <<
+ * /Type /XObject
+ * /Subtype /Image
+ * /Width -int-
+ * /Height -int-
+ * /BitsPerComponent bpc
+ * >>
+ * stream .... endstream
+ *
+ * ColorSpace, Mask, SMask must be absent. ImageMask must be false or absent.
+ */
+
+static pdf_obj *
+create_soft_mask (png_structp png_ptr, png_infop info_ptr,
+ png_bytep image_data_ptr, png_uint_32 width, png_uint_32 height)
+{
+ pdf_obj *smask, *dict;
+ png_bytep smask_data_ptr;
+ png_bytep trans;
+ int num_trans;
+ png_uint_32 i;
+
+ if (!png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS) ||
+ !png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, NULL)) {
+ WARN("%s: PNG does not have valid tRNS chunk but tRNS is requested.", PNG_DEBUG_STR);
+ return NULL;
+ }
+
+ smask = pdf_new_stream(STREAM_COMPRESS);
+ dict = pdf_stream_dict(smask);
+ smask_data_ptr = (png_bytep) NEW(width*height, png_byte);
+ pdf_add_dict(dict, pdf_new_name("Type"), pdf_new_name("XObjcect"));
+ pdf_add_dict(dict, pdf_new_name("Subtype"), pdf_new_name("Image"));
+ pdf_add_dict(dict, pdf_new_name("Width"), pdf_new_number(width));
+ pdf_add_dict(dict, pdf_new_name("Height"), pdf_new_number(height));
+ pdf_add_dict(dict, pdf_new_name("ColorSpace"), pdf_new_name("DeviceGray"));
+ pdf_add_dict(dict, pdf_new_name("BitsPerComponent"), pdf_new_number(8));
+ for (i = 0; i < width*height; i++) {
+ png_byte idx = image_data_ptr[i];
+ smask_data_ptr[i] = (idx < num_trans) ? trans[idx] : 0xff;
+ }
+ pdf_add_stream(smask, (char *)smask_data_ptr, width*height);
+ RELEASE(smask_data_ptr);
+
+ return smask;
+}
+
+/* bitdepth is always 8 (16 is not supported) */
+static pdf_obj *
+strip_soft_mask (png_structp png_ptr, png_infop info_ptr,
+ /* next two values will be modified. */
+ png_bytep image_data_ptr, png_uint_32p rowbytes_ptr,
+ png_uint_32 width, png_uint_32 height)
+{
+ pdf_obj *smask, *dict;
+ png_byte color_type;
+ png_bytep smask_data_ptr;
+ png_uint_32 i;
+
+ color_type = png_get_color_type(png_ptr, info_ptr);
+
+ if (color_type & PNG_COLOR_MASK_COLOR) {
+ if (*rowbytes_ptr != 4*width*sizeof(png_byte)) { /* Something wrong */
+ WARN("%s: Inconsistent rowbytes value.", PNG_DEBUG_STR);
+ return NULL;
+ }
+ } else {
+ if (*rowbytes_ptr != 2*width*sizeof(png_byte)) { /* Something wrong */
+ WARN("%s: Inconsistent rowbytes value.", PNG_DEBUG_STR);
+ return NULL;
+ }
+ }
+
+ smask = pdf_new_stream(STREAM_COMPRESS);
+ dict = pdf_stream_dict(smask);
+ pdf_add_dict(dict, pdf_new_name("Type"), pdf_new_name("XObjcect"));
+ pdf_add_dict(dict, pdf_new_name("Subtype"), pdf_new_name("Image"));
+ pdf_add_dict(dict, pdf_new_name("Width"), pdf_new_number(width));
+ pdf_add_dict(dict, pdf_new_name("Height"), pdf_new_number(height));
+ pdf_add_dict(dict, pdf_new_name("ColorSpace"), pdf_new_name("DeviceGray"));
+ pdf_add_dict(dict, pdf_new_name("BitsPerComponent"), pdf_new_number(8));
+
+ smask_data_ptr = (png_bytep) NEW(width*height, png_byte);
+
+ switch (color_type) {
+ case PNG_COLOR_TYPE_RGB_ALPHA:
+ for (i = 0; i < width*height; i++) {
+ memmove(image_data_ptr+(3*i), image_data_ptr+(4*i), 3);
+ smask_data_ptr[i] = image_data_ptr[4*i+3];
+ }
+ *rowbytes_ptr = 3*width*sizeof(png_byte);
+ break;
+ case PNG_COLOR_TYPE_GRAY_ALPHA:
+ for (i = 0; i < width*height; i++) {
+ image_data_ptr[i] = image_data_ptr[2*i];
+ smask_data_ptr[i] = image_data_ptr[2*i+1];
+ }
+ *rowbytes_ptr = width*sizeof(png_byte);
+ break;
+ default:
+ WARN("You found a bug in pngimage.c!");
+ pdf_release_obj(smask);
+ RELEASE(smask_data_ptr);
+ return NULL;
+ }
+
+ pdf_add_stream(smask, smask_data_ptr, width*height);
+ RELEASE(smask_data_ptr);
+
+ return smask;
+}
+
+static void
+read_image_data (png_structp png_ptr, png_infop info_ptr, /* info_ptr unused */
+ png_bytep dest_ptr, png_uint_32 height, png_uint_32 rowbytes)
+{
+ png_bytepp rows_p;
+ png_uint_32 i;
+
+ rows_p = (png_bytepp) NEW (height, png_bytep);
+ for (i=0; i< height; i++)
+ rows_p[i] = dest_ptr + (rowbytes * i);
+ png_read_image(png_ptr, rows_p);
+ RELEASE(rows_p);
+}
+
+#endif /* HAVE_LIBPNG */
diff --git a/Build/source/texk/dvipdf-x/xsrc/pngimage.h b/Build/source/texk/dvipdf-x/xsrc/pngimage.h
new file mode 100644
index 00000000000..747b7b1d223
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/pngimage.h
@@ -0,0 +1,43 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+
+#ifndef _PNGIMAGE_H_
+#define _PNGIMAGE_H_
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#ifdef HAVE_LIBPNG
+
+#include "mfileio.h"
+#include "pdfximage.h"
+
+extern int png_include_image (pdf_ximage *ximage, FILE *file);
+extern int check_for_png (FILE *file);
+
+#endif
+
+#endif /* _PNGIMAGE_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/sfnt.c b/Build/source/texk/dvipdf-x/xsrc/sfnt.c
new file mode 100644
index 00000000000..754fe366db3
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/sfnt.c
@@ -0,0 +1,652 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+/* Based on dvipdfmx-0.13.2c */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif /* HAVE_CONFIG_H_ */
+
+#include <string.h>
+
+#include "system.h"
+
+#include "error.h"
+#include "mem.h"
+#include "mfileio.h"
+
+#include "sfnt.h"
+
+#ifdef XETEX
+UNSIGNED_BYTE
+ft_unsigned_byte(sfnt* f)
+{
+ unsigned char byte;
+ unsigned long length = 1;
+
+ if (FT_Load_Sfnt_Table(f->ft_face, 0, f->loc, &byte, &length) != 0)
+ ERROR("sfnt: Freetype failure...");
+ f->loc += 1;
+
+ return byte;
+}
+
+SIGNED_BYTE
+ft_signed_byte(sfnt* f)
+{
+ int b = ft_unsigned_byte(f);
+ if (b >= 0x80)
+ b -= 0x100;
+ return (SIGNED_BYTE)b;
+}
+
+UNSIGNED_PAIR
+ft_unsigned_pair(sfnt* f)
+{
+ unsigned char buf[2];
+ unsigned long length = 2;
+
+ if (FT_Load_Sfnt_Table(f->ft_face, 0, f->loc, buf, &length) != 0)
+ ERROR("sfnt: Freetype failure...");
+ f->loc += 2;
+
+ return (UNSIGNED_PAIR)((unsigned)buf[0] << 8) + buf[1];
+}
+
+SIGNED_PAIR
+ft_signed_pair(sfnt* f)
+{
+ int p = ft_unsigned_pair(f);
+ if (p >= 0x8000U)
+ p -= 0x10000U;
+
+ return (SIGNED_PAIR)p;
+}
+
+UNSIGNED_QUAD
+ft_unsigned_quad(sfnt* f)
+{
+ unsigned char buf[4];
+ unsigned long length = 4;
+
+ if (FT_Load_Sfnt_Table(f->ft_face, 0, f->loc, buf, &length) != 0)
+ ERROR("sfnt: Freetype failure...");
+ f->loc += 4;
+
+ return ((unsigned long)buf[0] << 24) + ((unsigned long)buf[1] << 16)
+ + ((unsigned long)buf[2] << 8) + (unsigned long)buf[3];
+}
+
+unsigned long
+ft_read(unsigned char* buf, unsigned long len, sfnt* f)
+{
+ unsigned long length = len;
+ if (FT_Load_Sfnt_Table(f->ft_face, 0, f->loc, buf, &length) != 0)
+ ERROR("sfnt: Freetype failure...");
+ f->loc += len;
+
+ return length;
+}
+#endif
+
+
+/*
+ * type:
+ * `true' (0x74727565): TrueType (Mac)
+ * `typ1' (0x74797031) (Mac): PostScript font housed in a sfnt wrapper
+ * 0x00010000: TrueType (Win)/OpenType
+ * `OTTO': PostScript CFF font with OpenType wrapper
+ * `ttcf': TrueType Collection
+*/
+#define SFNT_TRUETYPE 0x00010000UL
+#define SFNT_MAC_TRUE 0x74727565UL
+#define SFNT_OPENTYPE 0x00010000UL
+#define SFNT_POSTSCRIPT 0x4f54544fUL
+#define SFNT_TTC 0x74746366UL
+
+#ifdef XETEX
+sfnt *
+sfnt_open (FT_Face face, int accept_types)
+{
+ sfnt *sfont;
+ ULONG type;
+
+ if (!face || !FT_IS_SFNT(face))
+ return NULL;
+
+ sfont = NEW(1, sfnt);
+ sfont->ft_face = face;
+ sfont->type = 0;
+ sfont->loc = 0;
+ sfont->offset = 0;
+
+ type = sfnt_get_ulong(sfont);
+
+ if (type == SFNT_TRUETYPE || type == SFNT_MAC_TRUE) {
+ sfont->type = SFNT_TYPE_TRUETYPE;
+ } else if (type == SFNT_OPENTYPE) {
+ sfont->type = SFNT_TYPE_OPENTYPE;
+ } else if (type == SFNT_POSTSCRIPT) {
+ sfont->type = SFNT_TYPE_POSTSCRIPT;
+ } else if (type == SFNT_TTC) {
+ sfont->type = SFNT_TYPE_TTC;
+ }
+
+ if ((sfont->type & accept_types) == 0) {
+ RELEASE(sfont);
+ return NULL;
+ }
+
+ sfont->directory = NULL;
+
+ return sfont;
+}
+#else /* not XETEX */
+sfnt *
+sfnt_open (FILE *fp)
+{
+ sfnt *sfont;
+ ULONG type;
+
+ ASSERT(fp);
+
+ rewind(fp);
+
+ sfont = NEW(1, sfnt);
+
+ sfont->stream = fp;
+
+ type = sfnt_get_ulong(sfont);
+
+ if (type == SFNT_TRUETYPE || type == SFNT_MAC_TRUE) {
+ sfont->type = SFNT_TYPE_TRUETYPE;
+ } else if (type == SFNT_OPENTYPE) {
+ sfont->type = SFNT_TYPE_OPENTYPE;
+ } else if (type == SFNT_POSTSCRIPT) {
+ sfont->type = SFNT_TYPE_POSTSCRIPT;
+ } else if (type == SFNT_TTC) {
+ sfont->type = SFNT_TYPE_TTC;
+ }
+
+ rewind(sfont->stream);
+
+ sfont->directory = NULL;
+ sfont->offset = 0UL;
+
+ return sfont;
+}
+
+sfnt *
+dfont_open (FILE *fp, int index)
+{
+ sfnt *sfont;
+ ULONG rdata_pos, map_pos, tags_pos, types_pos, res_pos, tag;
+ USHORT tags_num, types_num, i;
+
+ ASSERT(fp);
+
+ rewind(fp);
+
+ sfont = NEW(1, sfnt);
+
+ sfont->stream = fp;
+
+ rdata_pos = sfnt_get_ulong(sfont);
+ map_pos = sfnt_get_ulong(sfont);
+ sfnt_seek_set(sfont, map_pos + 0x18);
+ tags_pos = map_pos + sfnt_get_ushort(sfont);
+ sfnt_seek_set(sfont, tags_pos);
+ tags_num = sfnt_get_ushort(sfont);
+
+ for (i = 0; i <= tags_num; i++) {
+ tag = sfnt_get_ulong(sfont); /* tag name */
+ types_num = sfnt_get_ushort(sfont); /* typefaces number */
+ types_pos = tags_pos + sfnt_get_ushort(sfont); /* typefaces position */
+ if (tag == 0x73666e74UL) /* "sfnt" */
+ break;
+ }
+
+ if (i > tags_num) {
+ RELEASE(sfont);
+ return NULL;
+ }
+
+ sfnt_seek_set(sfont, types_pos);
+ if (index > types_num) {
+ ERROR("Invalid index %d for dfont.", index);
+ }
+
+ for (i = 0; i <= types_num; i++) {
+ (void) sfnt_get_ushort(sfont); /* resource id */
+ (void) sfnt_get_ushort(sfont); /* resource name position from name_list */
+ res_pos = sfnt_get_ulong(sfont); /* resource flag (byte) + resource offset */
+ sfnt_get_ulong(sfont); /* mbz */
+ if (i == index) break;
+ }
+
+ rewind(sfont->stream);
+
+ sfont->type = SFNT_TYPE_DFONT;
+ sfont->directory = NULL;
+ sfont->offset = (res_pos & 0x00ffffffUL) + rdata_pos + 4;
+
+ return sfont;
+}
+#endif
+
+static void
+release_directory (struct sfnt_table_directory *td)
+{
+ long i;
+
+ if (td) {
+ if (td->tables) {
+ for (i = 0; i < td->num_tables; i++) {
+ if (td->tables[i].data)
+ RELEASE(td->tables[i].data);
+ }
+ RELEASE(td->tables);
+ }
+ if (td->flags)
+ RELEASE(td->flags);
+ RELEASE(td);
+ }
+
+ return;
+}
+
+void
+sfnt_close (sfnt *sfont)
+{
+
+ if (sfont) {
+ if (sfont->directory)
+ release_directory(sfont->directory);
+ RELEASE(sfont);
+ }
+
+ return;
+}
+
+int
+put_big_endian (void *s, LONG q, int n)
+{
+ int i;
+ char *p;
+
+ p = (char *) s;
+ for (i = n - 1; i >= 0; i--) {
+ p[i] = (char) (q & 0xff);
+ q >>= 8;
+ }
+
+ return n;
+}
+
+/* Convert four-byte number to big endianess
+ * in a machine independent way.
+ */
+static void
+convert_tag (char *tag, unsigned long u_tag)
+{
+ int i;
+
+ for (i = 3; i >= 0; i--) {
+ tag[i] = (char) (u_tag % 256);
+ u_tag /= 256;
+ }
+
+ return;
+}
+
+/*
+ * Computes the max power of 2 <= n
+ */
+static unsigned
+max2floor (unsigned n)
+{
+ int val = 1;
+
+ while (n > 1) {
+ n /= 2;
+ val *= 2;
+ }
+
+ return val;
+}
+
+/*
+ * Computes the log2 of the max power of 2 <= n
+ */
+static unsigned
+log2floor (unsigned n)
+{
+ unsigned val = 0;
+
+ while (n > 1) {
+ n /= 2;
+ val++;
+ }
+
+ return val;
+}
+
+static ULONG
+sfnt_calc_checksum(void *data, ULONG length)
+{
+ ULONG chksum = 0;
+ BYTE *p, *endptr;
+ int count = 0;
+
+ p = (BYTE *) data;
+ endptr = p + length;
+ while (p < endptr) {
+ chksum += (p[0] << (8 * ( 3 - count)));
+ count = ((count + 1) & 3);
+ p++;
+ }
+
+ return chksum;
+}
+
+static int
+find_table_index (struct sfnt_table_directory *td, const char *tag)
+{
+ int idx;
+
+ if (!td)
+ return -1;
+
+ for (idx = 0; idx < td->num_tables; idx++) {
+ if (!memcmp(td->tables[idx].tag, tag, 4))
+ return idx;
+ }
+
+ return -1;
+}
+
+void
+sfnt_set_table (sfnt *sfont, const char *tag, void *data, ULONG length)
+{
+ struct sfnt_table_directory *td;
+ int idx;
+
+ ASSERT(sfont);
+
+ td = sfont->directory;
+ idx = find_table_index(td, tag);
+
+ if (idx < 0) {
+ idx = td->num_tables;
+ td->num_tables++;
+ td->tables = RENEW(td->tables, td->num_tables, struct sfnt_table);
+ memcpy(td->tables[idx].tag, tag, 4);
+ }
+
+ td->tables[idx].check_sum = sfnt_calc_checksum(data, length);
+ td->tables[idx].offset = 0L;
+ td->tables[idx].length = length;
+ td->tables[idx].data = data;
+
+ return;
+}
+
+ULONG
+sfnt_find_table_len (sfnt *sfont, const char *tag)
+{
+ ULONG length;
+ struct sfnt_table_directory *td;
+ int idx;
+
+ ASSERT(sfont && tag);
+
+ td = sfont->directory;
+ idx = find_table_index(td, tag);
+ if (idx < 0)
+ length = 0;
+ else {
+ length = td->tables[idx].length;
+ }
+
+ return length;
+}
+
+ULONG
+sfnt_find_table_pos (sfnt *sfont, const char *tag)
+{
+ ULONG offset;
+ struct sfnt_table_directory *td;
+ int idx;
+
+ ASSERT(sfont && tag);
+
+ td = sfont->directory;
+ idx = find_table_index(td, tag);
+ if (idx < 0)
+ offset = 0;
+ else {
+ offset = td->tables[idx].offset;
+ }
+
+ return offset;
+}
+
+ULONG
+sfnt_locate_table (sfnt *sfont, const char *tag)
+{
+ ULONG offset;
+
+ ASSERT(sfont && tag);
+
+ offset = sfnt_find_table_pos(sfont, tag);
+ if (offset == 0)
+ ERROR("sfnt: table not found...");
+
+ sfnt_seek_set(sfont, offset);
+
+ return offset;
+}
+
+int
+sfnt_read_table_directory (sfnt *sfont, ULONG offset)
+{
+ struct sfnt_table_directory *td;
+ unsigned long i, u_tag;
+
+ ASSERT(sfont);
+
+ if (sfont->directory)
+ release_directory(sfont->directory);
+ sfont->directory = td = NEW (1, struct sfnt_table_directory);
+
+#ifdef XETEX
+ ASSERT(sfont->ft_face);
+#else
+ ASSERT(sfont->stream);
+#endif
+
+ sfnt_seek_set(sfont, offset);
+
+ td->version = sfnt_get_ulong(sfont);
+ td->num_tables = sfnt_get_ushort(sfont);
+ td->search_range = sfnt_get_ushort(sfont);
+ td->entry_selector = sfnt_get_ushort(sfont);
+ td->range_shift = sfnt_get_ushort(sfont);
+
+ td->flags = NEW(td->num_tables, char);
+ td->tables = NEW(td->num_tables, struct sfnt_table);
+
+ for (i = 0; i < td->num_tables; i++) {
+ u_tag = sfnt_get_ulong(sfont);
+
+ convert_tag(td->tables[i].tag, u_tag);
+ td->tables[i].check_sum = sfnt_get_ulong(sfont);
+ td->tables[i].offset = sfnt_get_ulong(sfont) + sfont->offset;
+ td->tables[i].length = sfnt_get_ulong(sfont);
+ td->tables[i].data = NULL;
+//fprintf(stderr, "[%4s:%x]", td->tables[i].tag, td->tables[i].offset);
+
+ td->flags[i] = 0;
+ }
+
+ td->num_kept_tables = 0;
+
+ return 0;
+}
+
+int
+sfnt_require_table (sfnt *sfont, const char *tag, int must_exist)
+{
+ struct sfnt_table_directory *td;
+ int idx;
+
+ ASSERT(sfont && sfont->directory);
+
+ td = sfont->directory;
+ idx = find_table_index(td, tag);
+ if (idx < 0) {
+ if (must_exist)
+ return -1;
+ } else {
+ td->flags[idx] |= SFNT_TABLE_REQUIRED;
+ td->num_kept_tables++;
+ }
+
+ return 0;
+}
+
+#include "pdfobj.h"
+
+/*
+ * o All tables begin on four byte boundries, and pad any remaining space
+ * between tables with zeros
+ *
+ * o Entries in the Table Directory must be sorted in ascending order by tag
+ *
+ * o The head table contains checksum of the whole font file.
+ * To compute: first set it to 0, sum the entire font as ULONG,
+ * then store 0xB1B0AFBA - sum.
+ */
+
+static unsigned char wbuf[1024], padbytes[4] = {0, 0, 0, 0};
+
+pdf_obj *
+sfnt_create_FontFile_stream (sfnt *sfont)
+{
+ pdf_obj *stream;
+ pdf_obj *stream_dict;
+ struct sfnt_table_directory *td;
+ long offset, nb_read, length;
+ int i, sr;
+ char *p;
+
+ ASSERT(sfont && sfont->directory);
+
+ stream = pdf_new_stream(STREAM_COMPRESS);
+
+ td = sfont->directory;
+
+ /* Header */
+ p = (char *) wbuf;
+ p += sfnt_put_ulong (p, td->version);
+ p += sfnt_put_ushort(p, td->num_kept_tables);
+ sr = max2floor(td->num_kept_tables) * 16;
+ p += sfnt_put_ushort(p, sr);
+ p += sfnt_put_ushort(p, log2floor(td->num_kept_tables));
+ p += sfnt_put_ushort(p, td->num_kept_tables * 16 - sr);
+
+ pdf_add_stream(stream, wbuf, 12);
+
+ /*
+ * Compute start of actual tables (after headers).
+ */
+ offset = 12 + 16 * td->num_kept_tables;
+ for (i = 0; i < td->num_tables; i++) {
+ /* This table must exist in FontFile */
+ if (td->flags[i] & SFNT_TABLE_REQUIRED) {
+ if ((offset % 4) != 0) {
+ offset += 4 - (offset % 4);
+ }
+
+ p = (char *) wbuf;
+ memcpy(p, td->tables[i].tag, 4);
+ p += 4;
+ p += sfnt_put_ulong(p, td->tables[i].check_sum);
+ p += sfnt_put_ulong(p, offset);
+ p += sfnt_put_ulong(p, td->tables[i].length);
+ pdf_add_stream(stream, wbuf, 16);
+
+ offset += td->tables[i].length;
+ }
+ }
+
+ offset = 12 + 16 * td->num_kept_tables;
+ for (i = 0; i < td->num_tables; i++) {
+ if (td->flags[i] & SFNT_TABLE_REQUIRED) {
+ if ((offset % 4) != 0) {
+ length = 4 - (offset % 4);
+ pdf_add_stream(stream, padbytes, length);
+ offset += length;
+ }
+ if (!td->tables[i].data) {
+#ifdef XETEX
+ if (!sfont->ft_face)
+#else
+ if (!sfont->stream)
+#endif
+ {
+ pdf_release_obj(stream);
+ ERROR("Font file not opened or already closed...");
+ return NULL;
+ }
+
+ length = td->tables[i].length;
+ sfnt_seek_set(sfont, td->tables[i].offset);
+ while (length > 0) {
+ nb_read = sfnt_read(wbuf, MIN(length, 1024), sfont);
+ if (nb_read < 0) {
+ pdf_release_obj(stream);
+ ERROR("Reading file failed...");
+ return NULL;
+ } else if (nb_read > 0) {
+ pdf_add_stream(stream, wbuf, nb_read);
+ }
+ length -= nb_read;
+ }
+ } else {
+ pdf_add_stream(stream,
+ td->tables[i].data, td->tables[i].length);
+ RELEASE(td->tables[i].data);
+ td->tables[i].data = NULL;
+ }
+ /* Set offset for next table */
+ offset += td->tables[i].length;
+ }
+ }
+
+ stream_dict = pdf_stream_dict(stream);
+ pdf_add_dict(stream_dict,
+ pdf_new_name("Length1"),
+ pdf_new_number(offset));
+
+ return stream;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/spc_color.c b/Build/source/texk/dvipdf-x/xsrc/spc_color.c
new file mode 100644
index 00000000000..ae1d85cf8f1
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/spc_color.c
@@ -0,0 +1,192 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+#include "dpxutil.h"
+
+#include "pdfdev.h"
+#include "pdfcolor.h"
+
+#include "specials.h"
+
+#include "spc_util.h"
+#include "spc_color.h"
+
+
+/* Color stack is actually placed into pdfcolor.c.
+ * The reason why we need to place stack there is
+ * that we must reinstall color after grestore and
+ * other operations that can change current color
+ * implicitely.
+ */
+
+static int
+spc_handler_color_push (struct spc_env *spe, struct spc_arg *args)
+{
+ int error;
+ pdf_color colorspec;
+
+ error = spc_util_read_colorspec(spe, &colorspec, args, 1);
+ if (!error) {
+ pdf_color_push(&colorspec, &colorspec);
+ }
+
+ return error;
+}
+
+static int
+spc_handler_color_pop (struct spc_env *spe, struct spc_arg *args)
+{
+ pdf_color_pop();
+
+ return 0;
+}
+
+/* Invoked by the special command "color rgb .625 0 0".
+ * DVIPS clears the color stack, and then saves and sets the given color.
+ */
+static int
+spc_handler_color_default (struct spc_env *spe, struct spc_arg *args)
+{
+ int error;
+ pdf_color colorspec;
+
+ error = spc_util_read_colorspec(spe, &colorspec, args, 1);
+ if (!error) {
+ pdf_color_set_default(&colorspec);
+ pdf_color_clear_stack(); /* the default color is saved on color_stack */
+ pdf_color_push(&colorspec, &colorspec);
+ }
+
+ return error;
+}
+
+
+/* This is from color special? */
+#include "pdfdoc.h"
+
+static int
+spc_handler_background (struct spc_env *spe, struct spc_arg *args)
+{
+ int error;
+ pdf_color colorspec;
+
+ error = spc_util_read_colorspec(spe, &colorspec, args, 1);
+ if (!error)
+ pdf_doc_set_bgcolor(&colorspec);
+
+ return error;
+}
+
+
+#ifndef ISBLANK
+#define ISBLANK(c) ((c) == ' ' || (c) == '\t' || (c) == '\v')
+#endif
+static void
+skip_blank (const char **pp, const char *endptr)
+{
+ const char *p = *pp;
+ for ( ; p < endptr && ISBLANK(*p); p++);
+ *pp = p;
+}
+
+int
+spc_color_check_special (const char *buf, long len)
+{
+ int r = 0;
+ char *q;
+ const char *p, *endptr;
+
+ p = buf;
+ endptr = p + len;
+
+ skip_blank(&p, endptr);
+ q = parse_c_ident(&p, endptr);
+ if (!q)
+ return 0;
+ else if (!strcmp(q, "color"))
+ r = 1;
+ else if (!strcmp(q, "background")) {
+ r = 1;
+ }
+ RELEASE(q);
+
+ return r;
+}
+
+int
+spc_color_setup_handler (struct spc_handler *sph,
+ struct spc_env *spe, struct spc_arg *ap)
+{
+ const char *p;
+ char *q;
+
+ ASSERT(sph && spe && ap);
+
+ skip_blank(&ap->curptr, ap->endptr);
+ q = parse_c_ident(&ap->curptr, ap->endptr);
+ if (!q)
+ return -1;
+ skip_blank(&ap->curptr, ap->endptr);
+
+ if (!strcmp(q, "background")) {
+ ap->command = "background";
+ sph->exec = &spc_handler_background;
+ RELEASE(q);
+ } else if (!strcmp(q, "color")) { /* color */
+ RELEASE(q);
+ p = ap->curptr;
+
+ q = parse_c_ident(&p, ap->endptr);
+ if (!q)
+ return -1;
+ else if (!strcmp(q, "push")) {
+ ap->command = "push";
+ sph->exec = &spc_handler_color_push;
+ ap->curptr = p;
+ } else if (!strcmp(q, "pop")) {
+ ap->command = "pop";
+ sph->exec = &spc_handler_color_pop;
+ ap->curptr = p;
+ } else { /* cmyk, rgb, ... */
+ ap->command = "";
+ sph->exec = &spc_handler_color_default;
+ }
+ RELEASE(q);
+ } else {
+ spc_warn(spe, "Not color/background special?");
+ RELEASE(q);
+ return -1;
+ }
+
+ skip_blank(&ap->curptr, ap->endptr);
+ return 0;
+}
+
diff --git a/Build/source/texk/dvipdf-x/xsrc/spc_dvips.c b/Build/source/texk/dvipdf-x/xsrc/spc_dvips.c
new file mode 100644
index 00000000000..d9e713511a5
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/spc_dvips.c
@@ -0,0 +1,1075 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#include <string.h>
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+
+#include "dpxfile.h"
+
+#include "dvi.h"
+#include "dvicodes.h"
+
+#include "pdfparse.h"
+
+#include "pdfdoc.h"
+
+#include "mpost.h"
+
+#include "pdfximage.h"
+#include "pdfdraw.h"
+#include "pdfcolor.h"
+#include "pdfdev.h"
+
+#include "specials.h"
+#include "spc_util.h"
+#include "mfileio.h"
+
+#include "spc_dvips.h"
+#include "spc_xtx.h"
+
+#include "epdf.h"
+
+static int block_pending = 0;
+static double pending_x = 0.0;
+static double pending_y = 0.0;
+static int position_set = 0;
+
+static char** ps_headers = 0;
+static int num_ps_headers = 0;
+
+static int
+spc_handler_ps_header (struct spc_env *spe, struct spc_arg *args)
+{
+ char *ps_header, *pro;
+
+ skip_white(&args->curptr, args->endptr);
+ if (args->curptr + 1 >= args->endptr ||
+ args->curptr[0] != '=') {
+ spc_warn(spe, "No filename specified for PSfile special.");
+ return -1;
+ }
+ args->curptr++;
+
+ pro = malloc(args->endptr - args->curptr + 1);
+ strncpy(pro, args->curptr, args->endptr - args->curptr);
+ pro[args->endptr - args->curptr] = 0;
+ ps_header = kpse_find_file(pro, kpse_tex_ps_header_format, 0);
+ if (!ps_header) {
+ spc_warn(spe, "PS header %s not found.", pro);
+ return -1;
+ }
+ free(pro);
+
+ if (!(num_ps_headers & 0x0f))
+ ps_headers = realloc(ps_headers, sizeof(char*) * (num_ps_headers + 16));
+ ps_headers[num_ps_headers++] = ps_header;
+ args->curptr = args->endptr;
+ return 0;
+}
+
+static char *
+parse_filename (const char **pp, const char *endptr)
+{
+ char *r;
+ const char *q = NULL, *p = *pp;
+ char qchar;
+ int n;
+
+ if (!p || p >= endptr)
+ return NULL;
+ else if (*p == '\"' || *p == '\'')
+ qchar = *p++;
+ else {
+ qchar = ' ';
+ }
+ for (n = 0, q = p; p < endptr && *p != qchar; n++, p++);
+ if (qchar != ' ') {
+ if (*p != qchar)
+ return NULL;
+ p++;
+ }
+ if (!q || n == 0)
+ return NULL;
+
+#if 0
+ {
+ int i;
+ for (i = 0; i < n && isprint(q[i]); i++);
+ if (i != n) {
+ WARN("Non printable char in filename string...");
+ }
+ }
+#endif
+
+ r = NEW(n + 1, char);
+ memcpy(r, q, n); r[n] = '\0';
+
+ *pp = p;
+ return r;
+}
+
+/* =filename ... */
+static int
+spc_handler_ps_file (struct spc_env *spe, struct spc_arg *args)
+{
+ int form_id;
+ char *filename;
+ transform_info ti;
+
+ ASSERT(spe && args);
+
+ skip_white(&args->curptr, args->endptr);
+ if (args->curptr + 1 >= args->endptr ||
+ args->curptr[0] != '=') {
+ spc_warn(spe, "No filename specified for PSfile special.");
+ return -1;
+ }
+ args->curptr++;
+
+ filename = parse_filename(&args->curptr, args->endptr);
+ if (!filename) {
+ spc_warn(spe, "No filename specified for PSfile special.");
+ return -1;
+ }
+
+ transform_info_clear(&ti);
+ if (spc_util_read_dimtrns(spe, &ti, args, NULL, 1) < 0) {
+ RELEASE(filename);
+ return -1;
+ }
+
+ form_id = pdf_ximage_findresource(filename, 1, NULL);
+ if (form_id < 0) {
+ spc_warn(spe, "Failed to read image file: %s", filename);
+ RELEASE(filename);
+ return -1;
+ }
+ RELEASE(filename);
+
+ pdf_dev_put_image(form_id, &ti, spe->x_user, spe->y_user);
+
+ return 0;
+}
+
+/* This isn't correct implementation but dvipdfm supports... */
+static int
+spc_handler_ps_plotfile (struct spc_env *spe, struct spc_arg *args)
+{
+ int error = 0;
+ int form_id;
+ char *filename;
+ transform_info p;
+
+ ASSERT(spe && args);
+
+ spc_warn(spe, "\"ps: plotfile\" found (not properly implemented)");
+
+ skip_white(&args->curptr, args->endptr);
+ filename = parse_filename(&args->curptr, args->endptr);
+ if (!filename) {
+ spc_warn(spe, "Expecting filename but not found...");
+ return -1;
+ }
+
+ form_id = pdf_ximage_findresource(filename, 1, NULL);
+ if (form_id < 0) {
+ spc_warn(spe, "Could not open PS file: %s", filename);
+ error = -1;
+ } else {
+ transform_info_clear(&p);
+ p.matrix.d = -1.0; /* xscale = 1.0, yscale = -1.0 */
+#if 0
+ /* I don't know how to treat this... */
+ pdf_dev_put_image(form_id, &p,
+ block_pending ? pending_x : spe->x_user,
+ block_pending ? pending_y : spe->y_user);
+#endif
+ pdf_dev_put_image(form_id, &p, 0, 0);
+ }
+ RELEASE(filename);
+
+ return error;
+}
+
+static int
+spc_handler_ps_literal (struct spc_env *spe, struct spc_arg *args)
+{
+ int error = 0;
+ int st_depth, gs_depth;
+ double x_user, y_user;
+
+ ASSERT(spe && args && args->curptr <= args->endptr);
+
+ if (args->curptr + strlen(":[begin]") <= args->endptr &&
+ !strncmp(args->curptr, ":[begin]", strlen(":[begin]"))) {
+ block_pending++;
+ position_set = 1;
+
+ x_user = pending_x = spe->x_user;
+ y_user = pending_y = spe->y_user;
+ args->curptr += strlen(":[begin]");
+ } else if (args->curptr + strlen(":[end]") <= args->endptr &&
+ !strncmp(args->curptr, ":[end]", strlen(":[end]"))) {
+ if (block_pending <= 0) {
+ spc_warn(spe, "No corresponding ::[begin] found.");
+ return -1;
+ }
+ block_pending--;
+
+ position_set = 0;
+
+ x_user = pending_x;
+ y_user = pending_y;
+ args->curptr += strlen(":[end]");
+ } else if (args->curptr < args->endptr &&
+ args->curptr[0] == ':') {
+ x_user = position_set ? pending_x : spe->x_user;
+ y_user = position_set ? pending_y : spe->y_user;
+ args->curptr++;
+ } else {
+ position_set = 1;
+ x_user = pending_x = spe->x_user;
+ y_user = pending_y = spe->y_user;
+ }
+
+ skip_white(&args->curptr, args->endptr);
+ if (args->curptr < args->endptr) {
+
+ st_depth = mps_stack_depth();
+ gs_depth = pdf_dev_current_depth();
+
+ error = mps_exec_inline(&args->curptr,
+ args->endptr,
+ x_user, y_user);
+ if (error) {
+ spc_warn(spe, "Interpreting PS code failed!!! Output might be broken!!!");
+ pdf_dev_grestore_to(gs_depth);
+ } else if (st_depth != mps_stack_depth()) {
+ spc_warn(spe, "Stack not empty after execution of inline PostScript code.");
+ spc_warn(spe, ">> Your macro package makes some assumption on internal behaviour of DVI drivers.");
+ spc_warn(spe, ">> It may not compatible with dvipdfmx.");
+ }
+ }
+
+ return error;
+}
+
+static char *global_defs = 0;
+static char *page_defs = 0;
+static char *temporary_defs = 0;
+static char *distiller_template = 0;
+static pdf_coord *put_stack;
+static int put_stack_depth = -1;
+static char *gs_in = 0;
+
+#if 0
+/* Not used */
+static int
+spc_handler_ps_tricks_gdef (struct spc_env *spe, struct spc_arg *args)
+{
+ FILE* fp;
+
+ fp = fopen(global_defs, "ab");
+ fwrite(args->curptr, 1, args->endptr - args->curptr, fp);
+ fprintf(fp, "\n");
+ fclose(fp);
+
+ return 0;
+}
+#endif
+
+static int
+spc_handler_ps_tricks_pdef (struct spc_env *spe, struct spc_arg *args)
+{
+ FILE* fp;
+ pdf_tmatrix M, T = { 1, 0, 0, 1, 0, 0 };
+ pdf_coord pt;
+
+ pdf_dev_currentmatrix(&M);
+ pdf_dev_get_fixed_point(&pt);
+ T.e = pt.x;
+ T.f = pt.y;
+ pdf_concatmatrix(&M, &T);
+
+ if (!page_defs)
+ page_defs = dpx_create_temp_file();
+ if (!page_defs) {
+ WARN("Failed to create temporary input file for PSTricks image conversion.");
+ return -1;
+ }
+
+ fp = fopen(page_defs, "ab");
+ fprintf(fp, "gsave initmatrix [%f %f %f %f %f %f] concat %f %f moveto\n", M.a, M.b, M.c, M.d, M.e, M.f, spe->x_user - pt.x, spe->y_user - pt.y);
+ fwrite(args->curptr, 1, args->endptr - args->curptr, fp);
+ fprintf(fp, "\ngrestore\n");
+ fclose(fp);
+
+ return 0;
+}
+
+static int
+spc_handler_ps_tricks_tdef (struct spc_env *spe, struct spc_arg *args)
+{
+ FILE* fp;
+ if (!temporary_defs)
+ temporary_defs = dpx_create_temp_file();
+ if (!temporary_defs) {
+ WARN("Failed to create temporary input file for PSTricks image conversion.");
+ return -1;
+ }
+
+ fp = fopen(temporary_defs, "wb");
+ fwrite(args->curptr, 1, args->endptr - args->curptr, fp);
+ fprintf(fp, "\n");
+ fclose(fp);
+
+ return 0;
+}
+
+static int calculate_PS (char *string, int length, double *res1, double *res2, double *res3, double *res4, double *res5, double *res6);
+
+static int
+spc_handler_ps_tricks_bput (struct spc_env *spe, struct spc_arg *args, int must_def, int pre_def)
+{
+ char *PutBegin, *formula, *ncLabel;
+ int label = 0;
+ pdf_coord tr;
+ pdf_tmatrix M, T = { 1, 0, 0, 1, 0, 0 };
+
+ if (must_def != 0) {
+ ncLabel = strstr(args->curptr, "LPut");
+ if (ncLabel != 0 && ncLabel < args->endptr - 3)
+ label = 1;
+ ncLabel = strstr(args->curptr, "HPutPos");
+ if (ncLabel != 0 && ncLabel < args->endptr - 6)
+ label = 1;
+ }
+
+ if (pre_def == 0) {
+ dpx_delete_temp_file(temporary_defs, true);
+ temporary_defs = 0;
+ }
+
+ pdf_dev_currentmatrix(&M);
+ formula = malloc(args->endptr - args->curptr + 120);
+ if (label != 0) {
+ sprintf(formula, "[%f %f %f %f %f %f] concat %f %f moveto\n", M.a, M.b, M.c, M.d, M.e, M.f, spe->x_user + get_origin(1), spe->y_user + get_origin(0));
+ } else
+ sprintf(formula, "[%f %f %f %f %f %f] concat %f %f moveto\n", M.a, M.b, M.c, M.d, M.e, M.f, spe->x_user, spe->y_user);
+ strncat(formula, args->curptr, args->endptr - args->curptr);
+ PutBegin = strstr(formula, "PutBegin");
+ strcpy(PutBegin, "exch = =");
+ *(PutBegin + 8) = 0;
+ if (calculate_PS(formula, strlen(formula), &tr.x, &tr.y, 0, 0, 0, 0) == 0) {
+ if (!(++put_stack_depth & 0x0f))
+ put_stack = realloc(put_stack, (put_stack_depth + 16) * sizeof(pdf_coord));
+ put_stack[put_stack_depth] = tr;
+ }
+ T.e = tr.x; T.f = tr.y;
+
+ pdf_dev_concat(&T);
+
+ if (must_def != 0) {
+ FILE* fp;
+ if (!temporary_defs)
+ temporary_defs = dpx_create_temp_file();
+ if (!temporary_defs) {
+ WARN("Failed to create temporary input file for PSTricks image conversion.");
+ return -1;
+ }
+
+ fp = fopen(temporary_defs, "ab");
+ fprintf(fp, "gsave\n");
+ if (label == 0)
+ fprintf(fp, "[%f %f %f %f %f %f] concat %f %f moveto\n", M.a, M.b, M.c, M.d, M.e, M.f, spe->x_user, spe->y_user);
+ fwrite(args->curptr, 1, args->endptr - args->curptr, fp);
+ fprintf(fp, "\ngrestore\n");
+ fclose(fp);
+ }
+
+ free(formula);
+ return 0;
+}
+
+static int
+spc_handler_ps_tricks_eput (struct spc_env *spe, struct spc_arg *args)
+{
+ pdf_coord tr = put_stack[put_stack_depth--];
+ pdf_tmatrix M = { 1, 0, 0, 1, -tr.x, -tr.y };
+
+ pdf_dev_concat(&M);
+
+ return 0;
+}
+
+/* Rotation without gsave/grestore. */
+static double* RAngles = 0;
+static int RAngleCount = -1;
+
+static int
+spc_handler_ps_tricks_brotate (struct spc_env *spe, struct spc_arg *args)
+{
+ double value, RAngle = 0;
+ char *cmd, *RotBegin;
+ int i, l = args->endptr - args->curptr;
+
+ static const char *pre = "tx@Dict begin /RAngle { %f } def\n";
+ static const char *post = "= end";
+
+ if (!(++RAngleCount & 0x0f))
+ RAngles = realloc(RAngles, (RAngleCount + 16) * sizeof(double));
+ for (i = 0; i < RAngleCount; i++)
+ RAngle += RAngles[i];
+ cmd = calloc(l + strlen(pre) + strlen(post) + 12, 1);
+ sprintf(cmd, pre, RAngle);
+ strncat(cmd, args->curptr, l);
+ RotBegin = strstr(cmd, "RotBegin");
+ strcpy(RotBegin, post);
+ if (calculate_PS(cmd, strlen(cmd), &value, 0, 0, 0, 0, 0) != 0)
+ return -1;
+ RAngles[RAngleCount] = value;
+
+ return spc_handler_xtx_do_transform (spe->x_user, spe->y_user,
+ cos(value * M_PI / 180), sin(value * M_PI / 180),
+ -sin(value * M_PI / 180), cos(value * M_PI / 180),
+ 0, 0);
+}
+
+static int
+spc_handler_ps_tricks_erotate (struct spc_env *spe, struct spc_arg *args)
+{
+ double value = RAngles[RAngleCount--];
+
+ return spc_handler_xtx_do_transform (spe->x_user, spe->y_user,
+ cos(value * M_PI / 180), -sin(value * M_PI / 180),
+ sin(value * M_PI / 180), cos(value * M_PI / 180),
+ 0, 0);
+}
+
+static int
+spc_handler_ps_tricks_transform (struct spc_env *spe, struct spc_arg *args)
+{
+ double d1, d2, d3, d4, d5, d6;
+ char *cmd, *concat;
+ int l = args->endptr - args->curptr;
+
+ static const char *post = "concat matrix currentmatrix ==";
+
+ cmd = calloc(l + 41, 1);
+ strncpy(cmd, "matrix setmatrix ", 17);
+ strncpy(cmd + 17, args->curptr, l);
+ concat = strstr(cmd, "concat");
+ if (concat != 0) {
+ strcpy(concat, post);
+ concat[strlen(post)] = 0;
+ concat = strstr(cmd, "{");
+ *concat = ' ';
+ if (calculate_PS(cmd, strlen(cmd), &d1, &d2, &d3, &d4, &d5, &d6) != 0)
+ return -1;
+ if (spc_handler_xtx_gsave (0, 0) != 0)
+ return -1;
+ return spc_handler_xtx_do_transform (spe->x_user, spe->y_user, d1, d2, d3, d4, d5, d6);
+ }
+ return spc_handler_xtx_grestore (0, 0);
+}
+
+static int
+check_next_obj(const unsigned char * buffer)
+{
+ switch (buffer[0]) {
+ case XXX1:
+ if (buffer[1] < 5)
+ return 0;
+ buffer += 2;
+ break;
+ case XXX2:
+ buffer += 3;
+ break;
+ case XXX3:
+ buffer += 4;
+ break;
+ case XXX4:
+ buffer += 5;
+ break;
+ default:
+ return 0;
+ }
+
+ if (strncmp((const char*)buffer, "pst:", 4))
+ return 0;
+ return 1;
+}
+
+static int
+spc_handler_ps_tricks_parse_path (struct spc_env *spe, struct spc_arg *args,
+ int flag)
+{
+ FILE* fp;
+ int k;
+ pdf_tmatrix M;
+ char *distiller_template = get_distiller_template();
+ char *gs_out;
+ const char *clip;
+ int error;
+
+ if (!distiller_template)
+ distiller_template = get_distiller_template();
+
+ pdf_dev_currentmatrix(&M);
+ if (!gs_in) {
+ gs_in = dpx_create_temp_file();
+ if (!gs_in) {
+ WARN("Failed to create temporary input file for PSTricks image conversion.");
+ return -1;
+ }
+ fp = fopen(gs_in, "wb");
+ for (k = 0; k < num_ps_headers; k++)
+ fprintf(fp, "(%s) run\n", ps_headers[k]);
+ fprintf(fp, "[%f %f %f %f %f %f] concat %f %f translate 0 0 moveto\n", M.a, M.b, M.c, M.d, M.e, M.f, spe->x_user, spe->y_user);
+ fprintf(fp, "(%s) run\n", global_defs);
+ if (page_defs != 0)
+ fprintf(fp, "(%s) run\n", page_defs);
+
+#if 0
+ fprintf(fp, "/clip {stroke} def\n");
+ fwrite(args->curptr, 1, args->endptr - args->curptr, fp);
+#else
+ clip = strstr(args->curptr, " clip");
+ if (clip == 0 || clip > args->endptr - 5) {
+ fprintf(fp, "tx@TextPathDict begin /stroke {} def\n");
+ fwrite(args->curptr, 1, args->endptr - args->curptr, fp);
+ fprintf(fp, "\nend\n");
+ fclose(fp);
+ return 0;
+ } else {
+ fwrite(args->curptr, 1, clip - args->curptr, fp);
+ fprintf(fp, " stroke ");
+ skip_white(&clip, args->endptr);
+ parse_ident(&clip, args->endptr);
+ fwrite(clip, 1, args->endptr - clip, fp);
+ }
+#endif
+ } else {
+ fp = fopen(gs_in, "ab");
+ fprintf(fp, "flattenpath stroke\n");
+ }
+ fclose(fp);
+
+ gs_out = dpx_create_temp_file();
+ if (!gs_out) {
+ WARN("Failed to create temporary output file for PSTricks image conversion.");
+ RELEASE(gs_in);
+ gs_in = 0;
+ return -1;
+ }
+#ifdef MIKTEX
+ {
+ char *p;
+ for (p = (char *)gs_in; *p; p++) {
+ if (*p == '\\') *p = '/';
+ }
+ for (p = (char *)gs_out; *p; p++) {
+ if (*p == '\\') *p = '/';
+ }
+ }
+#endif
+ error = dpx_file_apply_filter(distiller_template, gs_in, gs_out,
+ (unsigned char) pdf_get_version());
+ if (error) {
+ WARN("Image format conversion for PSTricks failed.");
+ RELEASE(gs_in);
+ gs_in = 0;
+ return error;
+ }
+
+ fp = fopen(gs_out, "rb");
+ if (pdf_copy_clip(fp, 1, 0, 0) != 0) {
+ spc_warn(spe, "Failed to parse the clipping path.");
+ RELEASE(gs_in);
+ gs_in = 0;
+ RELEASE(gs_out);
+ return -1;
+ }
+ fclose(fp);
+
+ dpx_delete_temp_file(gs_out, true);
+ dpx_delete_temp_file(gs_in, true);
+ gs_in = 0;
+
+ return 0;
+}
+
+static int
+spc_handler_ps_tricks_render (struct spc_env *spe, struct spc_arg *args)
+{
+ FILE* fp;
+ int k;
+ pdf_tmatrix M;
+
+ if (!distiller_template)
+ distiller_template = get_distiller_template();
+
+ pdf_dev_currentmatrix(&M);
+ if (!gs_in) {
+ gs_in = dpx_create_temp_file();
+ if (!gs_in) {
+ WARN("Failed to create temporary input file for PSTricks image conversion.");
+ return -1;
+ }
+ fp = fopen(gs_in, "wb");
+ for (k = 0; k < num_ps_headers; k++)
+ fprintf(fp, "(%s) run\n", ps_headers[k]);
+ fprintf(fp, "[%f %f %f %f %f %f] concat %f %f translate 0 0 moveto\n", M.a, M.b, M.c, M.d, M.e, M.f, spe->x_user, spe->y_user);
+ fprintf(fp, "(%s) run\n", global_defs);
+ if (page_defs != 0)
+ fprintf(fp, "(%s) run\n", page_defs);
+ } else
+ fp = fopen(gs_in, "ab");
+
+ fprintf(fp, "\nsave\n");
+ fwrite(args->curptr, 1, args->endptr - args->curptr, fp);
+ fprintf(fp, "\ncount 1 sub {pop} repeat restore\n");
+
+ if (check_next_obj((const unsigned char*)args->endptr)) {
+ fclose(fp);
+ } else {
+ char *distiller_template = get_distiller_template();
+ char *gs_out;
+ int error, form_id;
+ transform_info p;
+ transform_info_clear(&p);
+ pdf_invertmatrix(&M);
+ p.matrix = M;
+
+ fclose(fp);
+
+ gs_out = dpx_create_temp_file();
+ if (!gs_out) {
+ WARN("Failed to create temporary output file for PSTricks image conversion.");
+ RELEASE(gs_in);
+ gs_in = 0;
+ return -1;
+ }
+#ifdef MIKTEX
+ {
+ char *p;
+ for (p = (char *)gs_in; *p; p++) {
+ if (*p == '\\') *p = '/';
+ }
+ for (p = (char *)gs_out; *p; p++) {
+ if (*p == '\\') *p = '/';
+ }
+ }
+#endif
+ error = dpx_file_apply_filter(distiller_template, gs_in, gs_out,
+ (unsigned char) pdf_get_version());
+ if (error) {
+ WARN("Image format conversion for PSTricks failed.");
+ RELEASE(gs_in);
+ gs_in = 0;
+ return error;
+ }
+
+ form_id = pdf_ximage_findresource(gs_out, 1, NULL);
+ if (form_id < 0) {
+ spc_warn(spe, "Failed to read converted PSTricks image file.");
+ RELEASE(gs_in);
+ gs_in = 0;
+ RELEASE(gs_out);
+ return -1;
+ }
+ pdf_dev_put_image(form_id, &p, 0, 0);
+
+ dpx_delete_temp_file(gs_out, true);
+ dpx_delete_temp_file(gs_in, true);
+ gs_in = 0;
+ }
+
+ return 0;
+}
+
+typedef enum {
+ render = 1 << 0,
+ global_def = 1 << 1,
+ page_def = 1 << 2,
+ new_temp = 1 << 3,
+ add_temp = 1 << 4,
+ begin_put = 1 << 5,
+ end_put = 1 << 6,
+ begin_rotate = 1 << 7,
+ end_rotate = 1 << 8,
+ parse = 1 << 9,
+ req_ref = 1 << 10,
+ transform = 1 << 11
+} Operation;
+
+/* ToDo: all the substring search must be centralized so that *
+ * keys can be read from external configuration. */
+struct pstricks_key_ {
+ const char * key;
+ Operation exec;
+} pstricks_key[] = {
+ /* The first 5 are hard-coded here. */
+ {"LPut", add_temp | req_ref},
+ {"HPutPos", add_temp | req_ref},
+ {"PutBegin", begin_put},
+ {"RotBegin", begin_rotate},
+ {"clip", parse},
+ /* The rest can be read from an external source. */
+ {"NewNode", page_def | req_ref},
+ {"InitNC", render | new_temp},
+ {"/Glbx", add_temp},
+ {"NewtonSolving", add_temp},
+ {"tx@LightThreeDDict", page_def},
+ {"PutEnd", end_put},
+ {"RotEnd", end_rotate},
+ {"mtrxc", parse},
+ {"stroke", render},
+ {"fill", render},
+ {"Fill", render},
+ {" Glbx", req_ref},
+ {"TextPathShow", parse},
+ {"/rotAngle", page_def},
+ {"NAngle", req_ref},
+ {"TMatrix", transform}
+};
+
+static int
+spc_handler_ps_trickscmd (struct spc_env *spe, struct spc_arg *args)
+{
+ char *test_string;
+ int k, error = 0, f_exec = 0;
+
+ /* Hack time! */
+ /* The problem is that while any macros in pstricks.tex
+ * can be overridden by the codes in pstricks.con, you cannot
+ * modify the pst@Verb specials generated by other PSTricks
+ * packages. So pstricks generate specials won't signal what
+ * to expect for you.
+ */
+ test_string = malloc(args->endptr - args->curptr + 1);
+ strncpy(test_string, args->curptr, args->endptr - args->curptr);
+ test_string[args->endptr - args->curptr] = 0;
+ for (k = 0; k < sizeof(pstricks_key) / sizeof(pstricks_key[0]); k++) {
+ if (strstr(test_string, pstricks_key[k].key) != 0)
+ f_exec |= pstricks_key[k].exec;
+ }
+ free(test_string);
+
+ if (f_exec & new_temp)
+ error |= spc_handler_ps_tricks_tdef(spe, args);
+ if (f_exec & render)
+ error |= spc_handler_ps_tricks_render(spe, args);
+ if (f_exec & parse)
+ error |= spc_handler_ps_tricks_parse_path(spe, args, f_exec);
+ if (f_exec & begin_put)
+ error |= spc_handler_ps_tricks_bput(spe, args, (f_exec & add_temp), (f_exec & req_ref));
+ if (f_exec & end_put)
+ error |= spc_handler_ps_tricks_eput(spe, args);
+ if (f_exec & begin_rotate)
+ error |= spc_handler_ps_tricks_brotate(spe, args);
+ if (f_exec & end_rotate)
+ error |= spc_handler_ps_tricks_erotate(spe, args);
+ if (f_exec & transform)
+ error |= spc_handler_ps_tricks_transform(spe, args);
+ if (f_exec & page_def)
+ error |= spc_handler_ps_tricks_pdef (spe, args);
+ if (f_exec == 0)
+ error |= spc_handler_ps_tricks_pdef (spe, args);
+
+ args->curptr = args->endptr;
+ return error;
+}
+
+static int
+spc_handler_ps_tricksobj (struct spc_env *spe, struct spc_arg *args)
+{
+ int error = spc_handler_ps_tricks_render(spe, args);
+ args->curptr = args->endptr;
+ return error;
+}
+
+static int
+spc_handler_ps_default (struct spc_env *spe, struct spc_arg *args)
+{
+ int error;
+ int st_depth, gs_depth;
+
+ ASSERT(spe && args);
+
+ pdf_dev_gsave();
+
+ st_depth = mps_stack_depth();
+ gs_depth = pdf_dev_current_depth();
+
+ {
+ pdf_tmatrix M;
+ M.a = M.d = 1.0; M.b = M.c = 0.0; M.e = spe->x_user; M.f = spe->y_user;
+ pdf_dev_concat(&M);
+ error = mps_exec_inline(&args->curptr,
+ args->endptr,
+ spe->x_user, spe->y_user);
+ M.e = -spe->x_user; M.f = -spe->y_user;
+ pdf_dev_concat(&M);
+ }
+ if (error)
+ spc_warn(spe, "Interpreting PS code failed!!! Output might be broken!!!");
+ else {
+ if (st_depth != mps_stack_depth()) {
+ spc_warn(spe, "Stack not empty after execution of inline PostScript code.");
+ spc_warn(spe, ">> Your macro package makes some assumption on internal behaviour of DVI drivers.");
+ spc_warn(spe, ">> It may not compatible with dvipdfmx.");
+ }
+ }
+
+ pdf_dev_grestore_to(gs_depth);
+ pdf_dev_grestore();
+
+ return error;
+}
+
+static struct spc_handler dvips_handlers[] = {
+ {"header", spc_handler_ps_header},
+ {"PSfile", spc_handler_ps_file},
+ {"psfile", spc_handler_ps_file},
+ {"ps: plotfile ", spc_handler_ps_plotfile},
+ {"PS: plotfile ", spc_handler_ps_plotfile},
+ {"PS:", spc_handler_ps_literal},
+ {"ps:", spc_handler_ps_literal},
+ {"PST:", spc_handler_ps_trickscmd},
+ {"pst:", spc_handler_ps_tricksobj},
+ {"\" ", spc_handler_ps_default}
+};
+
+#ifdef XETEX
+int
+spc_dvips_at_begin_document (void)
+{
+ FILE* fp;
+
+ /* This, together with \pscharpath support code, must be moved to xtex.pro header. */
+ global_defs = dpx_create_temp_file();
+ if (!global_defs) {
+ WARN("Failed to create temporary input file for PSTricks image conversion.");
+ return -1;
+ }
+
+ fp = fopen(global_defs, "wb");
+ fprintf(fp, "tx@Dict begin /STV {} def end\n");
+ fclose(fp);
+ return 0;
+}
+
+int
+spc_dvips_at_end_document (void)
+{
+ if (ps_headers) {
+ while (num_ps_headers > 0)
+ RELEASE(ps_headers[--num_ps_headers]);
+ free(ps_headers);
+ ps_headers = NULL;
+ }
+ dpx_delete_temp_file(global_defs, true);
+ dpx_delete_temp_file(page_defs, true);
+ return 0;
+}
+
+int
+spc_dvips_at_begin_page (void)
+{
+ if (page_defs) {
+ dpx_delete_temp_file(page_defs, true);
+ page_defs = 0;
+ }
+
+ put_stack_depth = -1;
+
+ return 0;
+}
+#endif
+
+int
+spc_dvips_at_end_page (void)
+{
+ mps_eop_cleanup();
+#ifdef XETEX
+ if (!temporary_defs) {
+ dpx_delete_temp_file(temporary_defs, true);
+ temporary_defs = 0;
+ }
+#endif
+ return 0;
+}
+
+int
+spc_dvips_check_special (const char *buf, long len)
+{
+ const char *p, *endptr;
+ int i;
+
+ p = buf;
+ endptr = p + len;
+
+ skip_white(&p, endptr);
+ if (p >= endptr)
+ return 0;
+
+ len = (long) (endptr - p);
+ for (i = 0;
+ i < sizeof(dvips_handlers)/sizeof(struct spc_handler); i++) {
+ if (len >= strlen(dvips_handlers[i].key) &&
+ !memcmp(p, dvips_handlers[i].key,
+ strlen(dvips_handlers[i].key))) {
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+int
+spc_dvips_setup_handler (struct spc_handler *handle,
+ struct spc_env *spe, struct spc_arg *args)
+{
+ const char *key;
+ int i, keylen;
+
+ ASSERT(handle && spe && args);
+
+ skip_white(&args->curptr, args->endptr);
+
+ key = args->curptr;
+ while (args->curptr < args->endptr &&
+ isalpha(args->curptr[0])) {
+ args->curptr++;
+ }
+ /* Test for "ps:". The "ps::" special is subsumed under this case. */
+ if (args->curptr < args->endptr &&
+ args->curptr[0] == ':') {
+ args->curptr++;
+ if (args->curptr+strlen(" plotfile ") <= args->endptr &&
+ !strncmp(args->curptr, " plotfile ", strlen(" plotfile "))) {
+ args->curptr += strlen(" plotfile ");
+ }
+ } else if (args->curptr+1 < args->endptr &&
+ args->curptr[0] == '"' && args->curptr[1] == ' ') {
+ args->curptr += 2;
+ }
+
+ keylen = (int) (args->curptr - key);
+ if (keylen < 1) {
+ spc_warn(spe, "Not ps: special???");
+ return -1;
+ }
+
+ for (i = 0;
+ i < sizeof(dvips_handlers) / sizeof(struct spc_handler); i++) {
+ if (keylen <= strlen(dvips_handlers[i].key) &&
+ !strncmp(key, dvips_handlers[i].key, strlen(dvips_handlers[i].key))) {
+
+ skip_white(&args->curptr, args->endptr);
+
+ args->command = dvips_handlers[i].key;
+
+ handle->key = "ps:";
+ handle->exec = dvips_handlers[i].exec;
+
+ return 0;
+ }
+ }
+
+ return -1;
+}
+
+#ifdef __EMX__
+#define GS_CALCULATOR "gsos2 -q -dNOPAUSE -dBATCH -sDEVICE=nullpage -f "
+#elif defined(WIN32)
+#define GS_CALCULATOR "gswin32c -q -dNOPAUSE -dBATCH -sDEVICE=nullpage -f "
+#else
+#define GS_CALCULATOR "gs -q -dNOPAUSE -dBATCH -sDEVICE=nullpage -f "
+#endif
+
+static
+int calculate_PS (char *string, int length, double *res1, double *res2, double *res3, double *res4, double *res5, double *res6) {
+ char *formula, *cmd;
+ FILE *fp, *coord;
+ int k;
+
+ if (res1 == 0 && res2 == 0)
+ return -1;
+ formula = dpx_create_temp_file();
+ if (!formula) {
+ WARN("Failed to create temporary input file for PSTricks image conversion.");
+ return -1;
+ }
+
+ fp = fopen(formula, "wb");
+ for (k = 0; k < num_ps_headers; k++)
+ fprintf(fp, "(%s) run\n", ps_headers[k]);
+ fprintf(fp, "0 0 moveto\n");
+ fprintf(fp, "(%s) run\n", global_defs);
+ if (page_defs != 0)
+ fprintf(fp, "(%s) run\n", page_defs);
+ if (temporary_defs)
+ fprintf(fp, "(%s) run\n", temporary_defs);
+ fwrite(string, 1, length, fp);
+ fclose(fp);
+#ifdef MIKTEX
+ {
+ char *p;
+ for (p = formula; *p; p++)
+ if (*p == '\\')
+ *p = '/';
+ }
+#endif
+ k = strlen(GS_CALCULATOR) + strlen(formula) + 1;
+ cmd = NEW(k, char);
+ strcpy(cmd, GS_CALCULATOR);
+ strcat(cmd, formula);
+
+ coord = popen(cmd, "r");
+ if (coord) {
+ if (res1 == 0)
+ fscanf(coord, " %lf ", res2);
+ else if (res2 == 0)
+ fscanf(coord, " %lf ", res1);
+ else if (res3 == 0)
+ fscanf(coord, " %lf %lf ", res1, res2);
+ else
+ fscanf(coord, " [%lf %lf %lf %lf %lf %lf] ", res1, res2, res3, res4, res5, res6);
+ } else
+ return -1;
+
+ pclose(coord);
+ RELEASE(cmd);
+ dpx_delete_temp_file(formula, true);
+ return 0;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/spc_html.c b/Build/source/texk/dvipdf-x/xsrc/spc_html.c
new file mode 100644
index 00000000000..5d9fc66ab4f
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/spc_html.c
@@ -0,0 +1,944 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+#include "dpxutil.h"
+
+#include "pdfdraw.h"
+#include "pdfdev.h"
+#include "pdfximage.h"
+
+#include "pdfdoc.h"
+
+#include "specials.h"
+#include "spc_util.h"
+
+#include "spc_html.h"
+
+
+#define ENABLE_HTML_IMG_SUPPORT 1
+#define ENABLE_HTML_SVG_TRANSFORM 1
+#define ENABLE_HTML_SVG_OPACITY 1
+
+/* _FIXME_
+ * Please rewrite this or remove html special support
+ */
+
+#define ANCHOR_TYPE_HREF 0
+#define ANCHOR_TYPE_NAME 1
+
+struct spc_html_
+{
+ struct {
+ long extensions;
+ } opts;
+
+ pdf_obj *link_dict;
+ char *baseurl;
+ int pending_type;
+};
+
+static struct spc_html_ _html_state = {
+ { 0 },
+ NULL, NULL, -1
+};
+
+
+#ifdef ENABLE_HTML_SVG_TRANSFORM
+static int cvt_a_to_tmatrix (pdf_tmatrix *M, const char *ptr, const char **nextptr);
+#endif /* ENABLE_HTML_SVG_TRANSFORM */
+
+#define \
+downcasify(s) \
+if ((s)) { \
+ char *_p = (char *) (s); \
+ while (*(_p) != 0) { \
+ if (*(_p) >= 'A' && *(_p) <= 'Z') { \
+ *(_p) = (*(_p) - 'A') + 'a'; \
+ } \
+ _p++; \
+ } \
+}
+
+static int
+parse_key_val (const char **pp, const char *endptr, char **kp, char **vp)
+{
+ const char *q, *p;
+ char *k, *v;
+ int n, error = 0;
+
+ for (p = *pp ; p < endptr && isspace(*p); p++);
+#if 0
+ while (!error && p < endptr &&
+ ((*p >= 'a' && *p <= 'z') ||
+ (*p >= 'A' && *p <= 'Z'))
+ ) {
+#endif
+ k = v = NULL;
+ for (q = p, n = 0;
+ p < endptr &&
+ ((*p >= 'a' && *p <= 'z') ||
+ (*p >= 'A' && *p <= 'Z') ||
+ (*p >= '0' && *p <= '9') ||
+ *p == '-' || *p == ':'
+ ); n++, p++);
+ if (n == 0) {
+#if 0
+ break;
+#else
+ *kp = *vp = NULL;
+ return -1;
+#endif
+ }
+ k = NEW(n + 1, char);
+ memcpy(k, q, n); k[n] = '\0';
+ if (p + 2 >= endptr || p[0] != '=' || (p[1] != '\"' && p[1] != '\'')) {
+ RELEASE(k); k = NULL;
+ *pp = p;
+ error = -1;
+ } else {
+ char qchr = p[1];
+ p += 2; /* skip '="' */
+ for (q = p, n = 0; p < endptr && *p != qchr; p++, n++);
+ if (p == endptr || *p != qchr)
+ error = -1;
+ else {
+ v = NEW(n + 1, char);
+ memcpy(v, q, n); v[n] = '\0';
+#if 0
+ pdf_add_dict(t->attr,
+ pdf_new_name(k),
+ pdf_new_string(v, n));
+ RELEASE(v);
+#endif
+ p++;
+ }
+ }
+#if 0
+ RELEASE(k);
+ if (!error)
+ for ( ; p < endptr && isspace(*p); p++);
+ }
+#endif
+
+ *kp = k; *vp = v; *pp = p;
+ return error;
+}
+
+#define HTML_TAG_NAME_MAX 127
+#define HTML_TAG_TYPE_EMPTY 1
+#define HTML_TAG_TYPE_OPEN 1
+#define HTML_TAG_TYPE_CLOSE 2
+
+static int
+read_html_tag (char *name, pdf_obj *attr, int *type, const char **pp, const char *endptr)
+{
+ const char *p = *pp;
+ int n = 0, error = 0;
+
+ for ( ; p < endptr && isspace(*p); p++);
+ if (p >= endptr || *p != '<')
+ return -1;
+
+ *type = HTML_TAG_TYPE_OPEN;
+ for (++p; p < endptr && isspace(*p); p++);
+ if (p < endptr && *p == '/') {
+ *type = HTML_TAG_TYPE_CLOSE;
+ for (++p; p < endptr && isspace(*p); p++);
+ }
+
+#define ISDELIM(c) ((c) == '>' || (c) == '/' || isspace(c))
+ for (n = 0; p < endptr && n < HTML_TAG_NAME_MAX && !ISDELIM(*p); n++, p++) {
+ name[n] = *p;
+ }
+ name[n] = '\0';
+ if (n == 0 || p == endptr || !ISDELIM(*p)) {
+ *pp = p;
+ return -1;
+ }
+
+ for ( ; p < endptr && isspace(*p); p++);
+ while (p < endptr && !error && *p != '/' && *p != '>') {
+ char *kp = NULL, *vp = NULL;
+ error = parse_key_val(&p, endptr, &kp, &vp);
+ if (!error) {
+ downcasify(kp);
+ pdf_add_dict(attr,
+ pdf_new_name(kp),
+ pdf_new_string(vp, strlen(vp) + 1)); /* include trailing NULL here!!! */
+ RELEASE(kp);
+ RELEASE(vp);
+ }
+ for ( ; p < endptr && isspace(*p); p++);
+ }
+ if (error) {
+ *pp = p;
+ return error;
+ }
+
+ if (p < endptr && *p == '/') {
+ *type = HTML_TAG_TYPE_EMPTY;
+ for (++p; p < endptr && isspace(*p); p++);
+ }
+ if (p == endptr || *p != '>') {
+ *pp = p;
+ return -1;
+ }
+ p++;
+
+ downcasify(name);
+ *pp = p;
+ return 0;
+}
+
+
+static int
+spc_handler_html__init (struct spc_env *spe, struct spc_arg *ap, void *dp)
+{
+ struct spc_html_ *sd = dp;
+
+ sd->link_dict = NULL;
+ sd->baseurl = NULL;
+ sd->pending_type = -1;
+
+ return 0;
+}
+
+static int
+spc_handler_html__clean (struct spc_env *spe, struct spc_arg *ap, void *dp)
+{
+ struct spc_html_ *sd = dp;
+
+ if (sd->baseurl)
+ RELEASE(sd->baseurl);
+
+ if (sd->pending_type >= 0 || sd->link_dict)
+ spc_warn(spe, "Unclosed html anchor found.");
+
+ if (sd->link_dict)
+ pdf_release_obj(sd->link_dict);
+
+ sd->pending_type = -1;
+ sd->baseurl = NULL;
+ sd->link_dict = NULL;
+
+ return 0;
+}
+
+
+static int
+spc_handler_html__bophook (struct spc_env *spe, struct spc_arg *ap, void *dp)
+{
+ struct spc_html_ *sd = dp;
+
+ if (sd->pending_type >= 0) {
+ spc_warn(spe, "...html anchor continues from previous page processed...");
+ }
+
+ return 0;
+}
+
+static int
+spc_handler_html__eophook (struct spc_env *spe, struct spc_arg *ap, void *dp)
+{
+ struct spc_html_ *sd = dp;
+
+ if (sd->pending_type >= 0) {
+ spc_warn(spe, "Unclosed html anchor at end-of-page!");
+ }
+
+ return 0;
+}
+
+
+static char *
+fqurl (const char *baseurl, const char *name)
+{
+ char *q;
+ int len = 0;
+
+ len = strlen(name);
+ if (baseurl)
+ len += strlen(baseurl) + 1; /* we may want to add '/' */
+
+ q = NEW(len + 1, char);
+ *q = '\0';
+ if (baseurl && baseurl[0]) {
+ char *p;
+ strcpy(q, baseurl);
+ p = q + strlen(q) - 1;
+ if (*p == '/')
+ *p = '\0';
+ if (name[0] && name[0] != '/')
+ strcat(q, "/");
+ }
+ strcat(q, name);
+
+ return q;
+}
+
+static int
+html_open_link (struct spc_env *spe, const char *name, struct spc_html_ *sd)
+{
+ pdf_obj *color;
+ char *url;
+
+ ASSERT( name );
+ ASSERT( sd->link_dict == NULL ); /* Should be checked somewhere else */
+
+ sd->link_dict = pdf_new_dict();
+ pdf_add_dict(sd->link_dict,
+ pdf_new_name("Type"), pdf_new_name ("Annot"));
+ pdf_add_dict(sd->link_dict,
+ pdf_new_name("Subtype"), pdf_new_name ("Link"));
+
+ color = pdf_new_array ();
+ pdf_add_array(color, pdf_new_number(0.0));
+ pdf_add_array(color, pdf_new_number(0.0));
+ pdf_add_array(color, pdf_new_number(1.0));
+ pdf_add_dict(sd->link_dict, pdf_new_name("C"), color);
+
+ url = fqurl(sd->baseurl, name);
+ if (url[0] == '#') {
+ /* url++; causes memory leak in RELEASE(url) */
+ pdf_add_dict(sd->link_dict,
+ pdf_new_name("Dest"),
+ pdf_new_string(url+1, strlen(url+1)));
+ } else { /* Assume this is URL */
+ pdf_obj *action = pdf_new_dict();
+ pdf_add_dict(action,
+ pdf_new_name("Type"),
+ pdf_new_name("Action"));
+ pdf_add_dict(action,
+ pdf_new_name("S"),
+ pdf_new_name("URI"));
+ pdf_add_dict(action,
+ pdf_new_name("URI"),
+ pdf_new_string(url, strlen(url)));
+ pdf_add_dict(sd->link_dict,
+ pdf_new_name("A"),
+ pdf_link_obj(action));
+ pdf_release_obj(action);
+ }
+ RELEASE(url);
+
+ spc_begin_annot(spe, sd->link_dict);
+
+ sd->pending_type = ANCHOR_TYPE_HREF;
+
+ return 0;
+}
+
+static int
+html_open_dest (struct spc_env *spe, const char *name, struct spc_html_ *sd)
+{
+ int error;
+ pdf_obj *array, *page_ref;
+ pdf_coord cp;
+
+ cp.x = spe->x_user; cp.y = spe->y_user;
+ pdf_dev_transform(&cp, NULL);
+
+ page_ref = pdf_doc_this_page_ref();
+ ASSERT( page_ref ); /* Otherwise must be bug */
+
+ array = pdf_new_array();
+ pdf_add_array(array, page_ref);
+ pdf_add_array(array, pdf_new_name("XYZ"));
+ pdf_add_array(array, pdf_new_null());
+ pdf_add_array(array, pdf_new_number(cp.y + 24.0));
+ pdf_add_array(array, pdf_new_null());
+
+ error = pdf_doc_add_names("Dests",
+ name, strlen(name),
+ array);
+
+ if (error)
+ spc_warn(spe, "Failed to add named destination: %s", name);
+
+ sd->pending_type = ANCHOR_TYPE_NAME;
+
+ return error;
+}
+
+#define ANCHOR_STARTED(s) ((s)->pending_type >= 0 || (s)->link_dict)
+
+static int
+spc_html__anchor_open (struct spc_env *spe, pdf_obj *attr, struct spc_html_ *sd)
+{
+ pdf_obj *href, *name;
+ int error = 0;
+
+ if (ANCHOR_STARTED(sd)) {
+ spc_warn(spe, "Nested html anchors found!");
+ return -1;
+ }
+
+ href = pdf_lookup_dict(attr, "href");
+ name = pdf_lookup_dict(attr, "name");
+ if (href && name) {
+ spc_warn(spe, "Sorry, you can't have both \"href\" and \"name\" in anchor tag...");
+ error = -1;
+ } else if (href) {
+ error = html_open_link(spe, pdf_string_value(href), sd);
+ } else if (name) { /* name */
+ error = html_open_dest(spe, pdf_string_value(name), sd);
+ } else {
+ spc_warn(spe, "You should have \"href\" or \"name\" in anchor tag!");
+ error = -1;
+ }
+
+ return error;
+}
+
+static int
+spc_html__anchor_close (struct spc_env *spe, pdf_obj *attr, struct spc_html_ *sd)
+{
+ int error = 0;
+
+ switch (sd->pending_type) {
+ case ANCHOR_TYPE_HREF:
+ if (sd->link_dict) {
+ spc_end_annot(spe);
+ pdf_release_obj(sd->link_dict);
+ sd->link_dict = NULL;
+ sd->pending_type = -1;
+ } else {
+ spc_warn(spe, "Closing html anchor (link) without starting!");
+ error = -1;
+ }
+ break;
+ case ANCHOR_TYPE_NAME:
+ sd->pending_type = -1;
+ break;
+ default:
+ spc_warn(spe, "No corresponding opening tag for html anchor.");
+ error = -1;
+ break;
+ }
+
+ return error;
+}
+
+static int
+spc_html__base_empty (struct spc_env *spe, pdf_obj *attr, struct spc_html_ *sd)
+{
+ pdf_obj *href;
+ char *vp;
+
+ href = pdf_lookup_dict(attr, "href");
+ if (!href) {
+ spc_warn(spe, "\"href\" not found for \"base\" tag!");
+ return -1;
+ }
+
+ vp = (char *) pdf_string_value(href);
+ if (sd->baseurl) {
+ spc_warn(spe, "\"baseurl\" changed: \"%s\" --> \"%s\"", sd->baseurl, vp);
+ RELEASE(sd->baseurl);
+ }
+ sd->baseurl = NEW(strlen(vp) + 1, char);
+ strcpy(sd->baseurl, vp);
+
+ return 0;
+}
+
+
+#ifdef ENABLE_HTML_IMG_SUPPORT
+/* This isn't completed.
+ * Please think about placement of images.
+ */
+static double
+atopt (const char *a)
+{
+ char *q;
+ const char *p = a;
+ double v, u = 1.0;
+ const char *_ukeys[] = {
+#define K_UNIT__PT 0
+#define K_UNIT__IN 1
+#define K_UNIT__CM 2
+#define K_UNIT__MM 3
+#define K_UNIT__BP 4
+ "pt", "in", "cm", "mm", "bp",
+#define K_UNIT__PX 5
+ "px",
+ NULL
+ };
+ int k;
+
+ q = parse_float_decimal(&p, p + strlen(p));
+ if (!q) {
+ WARN("Invalid length value: %s (%c)", a, *p);
+ return 0.0;
+ }
+
+ v = atof(q);
+ RELEASE(q);
+
+ q = parse_c_ident(&p, p + strlen(p));
+ if (q) {
+ for (k = 0; _ukeys[k] && strcmp(_ukeys[k], q); k++);
+ switch (k) {
+ case K_UNIT__PT: u *= 72.0 / 72.27; break;
+ case K_UNIT__IN: u *= 72.0; break;
+ case K_UNIT__CM: u *= 72.0 / 2.54 ; break;
+ case K_UNIT__MM: u *= 72.0 / 25.4 ; break;
+ case K_UNIT__BP: u *= 1.0 ; break;
+ case K_UNIT__PX: u *= 1.0 ; break; /* 72dpi */
+ default:
+ WARN("Unknown unit of measure: %s", q);
+ break;
+ }
+ RELEASE(q);
+ }
+
+ return v * u;
+}
+
+
+#ifdef ENABLE_HTML_SVG_OPACITY
+/* Replicated from spc_tpic */
+static pdf_obj *
+create_xgstate (double a /* alpha */, int f_ais /* alpha is shape */)
+{
+ pdf_obj *dict;
+
+ dict = pdf_new_dict();
+ pdf_add_dict(dict,
+ pdf_new_name("Type"),
+ pdf_new_name("ExtGState"));
+ if (f_ais) {
+ pdf_add_dict(dict,
+ pdf_new_name("AIS"),
+ pdf_new_boolean(1));
+ }
+ pdf_add_dict(dict,
+ pdf_new_name("ca"),
+ pdf_new_number(a));
+
+ return dict;
+}
+
+static int
+check_resourcestatus (const char *category, const char *resname)
+{
+ pdf_obj *dict1, *dict2;
+
+ dict1 = pdf_doc_current_page_resources();
+ if (!dict1)
+ return 0;
+
+ dict2 = pdf_lookup_dict(dict1, category);
+ if (dict2 &&
+ pdf_obj_typeof(dict2) == PDF_DICT) {
+ if (pdf_lookup_dict(dict2, resname))
+ return 1;
+ }
+ return 0;
+}
+#endif /* ENABLE_HTML_SVG_OPACITY */
+
+static int
+spc_html__img_empty (struct spc_env *spe, pdf_obj *attr, struct spc_html_ *sd)
+{
+ pdf_obj *src, *obj;
+ transform_info ti;
+ int id, error = 0;
+#ifdef ENABLE_HTML_SVG_OPACITY
+ double alpha = 1.0; /* meaning fully opaque */
+#endif /* ENABLE_HTML_SVG_OPACITY */
+#ifdef ENABLE_HTML_SVG_TRANSFORM
+ pdf_tmatrix M;
+
+ pdf_setmatrix(&M, 1.0, 0.0, 0.0, 1.0, spe->x_user, spe->y_user);
+#endif /* ENABLE_HTML_SVG_TRANSFORM */
+
+ spc_warn(spe, "html \"img\" tag found (not completed, plese don't use!).");
+
+ src = pdf_lookup_dict(attr, "src");
+ if (!src) {
+ spc_warn(spe, "\"src\" attribute not found for \"img\" tag!");
+ return -1;
+ }
+
+ transform_info_clear(&ti);
+ obj = pdf_lookup_dict(attr, "width");
+ if (obj) {
+ ti.width = atopt(pdf_string_value(obj));
+ ti.flags |= INFO_HAS_WIDTH;
+ }
+ obj = pdf_lookup_dict(attr, "height");
+ if (obj) {
+ ti.height = atopt(pdf_string_value(obj));
+ ti.flags |= INFO_HAS_HEIGHT;
+ }
+
+#ifdef ENABLE_HTML_SVG_OPACITY
+ obj = pdf_lookup_dict(attr, "svg:opacity");
+ if (obj) {
+ alpha = atof(pdf_string_value(obj));
+ if (alpha < 0.0 || alpha > 1.0) {
+ spc_warn(spe, "Invalid opacity value: %s", pdf_string_value(obj));
+ alpha = 1.0;
+ }
+ }
+#endif /* ENABLE_HTML_SVG_OPCAITY */
+
+#ifdef ENABLE_HTML_SVG_TRANSFORM
+ obj = pdf_lookup_dict(attr, "svg:transform");
+ if (obj) {
+ const char *p = pdf_string_value(obj);
+ pdf_tmatrix N;
+ for ( ; *p && isspace(*p); p++);
+ while (*p && !error) {
+ pdf_setmatrix(&N, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
+ error = cvt_a_to_tmatrix(&N, p, &p);
+ if (!error) {
+ N.f = -N.f;
+ pdf_concatmatrix(&M, &N);
+ for ( ; *p && isspace(*p); p++);
+ if (*p == ',')
+ for (++p; *p && isspace(*p); p++);
+ }
+ }
+ }
+#endif /* ENABLE_HTML_SVG_TRANSFORM */
+
+ if (error) {
+ spc_warn(spe, "Error in html \"img\" tag attribute.");
+ return error;
+ }
+
+ id = pdf_ximage_findresource(pdf_string_value(src), 0, NULL);
+ if (id < 0) {
+ spc_warn(spe, "Could not find/load image: %s", pdf_string_value(src));
+ error = -1;
+ } else {
+#if defined(ENABLE_HTML_SVG_TRANSFORM) || defined(ENABLE_HTML_SVG_OPACITY)
+ {
+ char *res_name;
+ pdf_rect r;
+
+ graphics_mode();
+
+ pdf_dev_gsave();
+
+#ifdef ENABLE_HTML_SVG_OPACITY
+ {
+ pdf_obj *dict;
+ int a = round(100.0 * alpha);
+ if (a != 0) {
+ res_name = NEW(strlen("_Tps_a100_") + 1, char);
+ sprintf(res_name, "_Tps_a%03d_", a); /* Not Tps prefix but... */
+ if (!check_resourcestatus("ExtGState", res_name)) {
+ dict = create_xgstate(round_at(0.01 * a, 0.01), 0);
+ pdf_doc_add_page_resource("ExtGState",
+ res_name, pdf_ref_obj(dict));
+ pdf_release_obj(dict);
+ }
+ pdf_doc_add_page_content(" /", 2);
+ pdf_doc_add_page_content(res_name, strlen(res_name));
+ pdf_doc_add_page_content(" gs", 3);
+ RELEASE(res_name);
+ }
+ }
+#endif /* ENABLE_HTML_SVG_OPACITY */
+
+ pdf_dev_concat(&M);
+
+ pdf_ximage_scale_image(id, &M, &r, &ti);
+ pdf_dev_concat(&M);
+
+ pdf_dev_rectclip(r.llx, r.lly, r.urx - r.llx, r.ury - r.lly);
+
+ res_name = pdf_ximage_get_resname(id);
+ pdf_doc_add_page_content(" /", 2);
+ pdf_doc_add_page_content(res_name, strlen(res_name));
+ pdf_doc_add_page_content(" Do", 3);
+
+ pdf_dev_grestore();
+
+ pdf_doc_add_page_resource("XObject",
+ res_name,
+ pdf_ximage_get_reference(id));
+ }
+#else
+ pdf_dev_put_image(id, &ti, spe->x_user, spe->y_user);
+#endif /* ENABLE_HTML_SVG_XXX */
+ }
+
+ return error;
+}
+#else
+static int
+spc_html__img_empty (struct spc_env *spe, pdf_obj *attr, struct spc_html_ *sd)
+{
+ spc_warn(spe, "IMG tag not yet supported yet...");
+ return -1;
+}
+#endif /* ENABLE_HTML_IMG_SUPPORT */
+
+
+static int
+spc_handler_html_default (struct spc_env *spe, struct spc_arg *ap)
+{
+ struct spc_html_ *sd = &_html_state;
+ char name[HTML_TAG_NAME_MAX + 1];
+ pdf_obj *attr;
+ int error = 0, type = HTML_TAG_TYPE_OPEN;
+
+ if (ap->curptr >= ap->endptr)
+ return 0;
+
+ attr = pdf_new_dict();
+ error = read_html_tag(name, attr, &type, &ap->curptr, ap->endptr);
+ if (error) {
+ pdf_release_obj(attr);
+ return error;
+ }
+ if (!strcmp(name, "a")) {
+ switch (type) {
+ case HTML_TAG_TYPE_OPEN:
+ error = spc_html__anchor_open (spe, attr, sd);
+ break;
+ case HTML_TAG_TYPE_CLOSE:
+ error = spc_html__anchor_close(spe, attr, sd);
+ break;
+ default:
+ spc_warn(spe, "Empty html anchor tag???");
+ error = -1;
+ break;
+ }
+ } else if (!strcmp(name, "base")) {
+ if (type == HTML_TAG_TYPE_CLOSE) {
+ spc_warn(spe, "Close tag for \"base\"???");
+ error = -1;
+ } else { /* treat "open" same as "empty" */
+ error = spc_html__base_empty(spe, attr, sd);
+ }
+ } else if (!strcmp(name, "img")) {
+ if (type == HTML_TAG_TYPE_CLOSE) {
+ spc_warn(spe, "Close tag for \"img\"???");
+ error = -1;
+ } else { /* treat "open" same as "empty" */
+ error = spc_html__img_empty(spe, attr, sd);
+ }
+ }
+ pdf_release_obj(attr);
+
+ for ( ; ap->curptr < ap->endptr && isspace(ap->curptr[0]); ap->curptr++);
+
+ return error;
+}
+
+
+#ifdef ENABLE_HTML_SVG_TRANSFORM
+/* translate wsp* '(' wsp* number (comma-wsp number)? wsp* ')' */
+static int
+cvt_a_to_tmatrix (pdf_tmatrix *M, const char *ptr, const char **nextptr)
+{
+ char *q;
+ const char *p = ptr;
+ int n;
+ double v[6];
+ static const char *_tkeys[] = {
+#define K_TRNS__MATRIX 0
+ "matrix", /* a b c d e f */
+#define K_TRNS__TRANSLATE 1
+ "translate", /* tx [ty] : dflt. tf = 0 */
+#define K_TRNS__SCALE 2
+ "scale", /* sx [sy] : dflt. sy = sx */
+#define K_TRNS__ROTATE 3
+ "rotate", /* ang [cx cy] : dflt. cx, cy = 0 */
+#define K_TRNS__SKEWX 4
+#define K_TRNS__SKEWY 5
+ "skewX", /* ang */
+ "skewY", /* ang */
+ NULL
+ };
+ int k;
+
+ for ( ; *p && isspace(*p); p++);
+
+ q = parse_c_ident(&p, p + strlen(p));
+ if (!q)
+ return -1;
+ /* parsed transformation key */
+ for (k = 0; _tkeys[k] && strcmp(q, _tkeys[k]); k++);
+ RELEASE(q);
+
+ /* handle args */
+ for ( ; *p && isspace(*p); p++);
+ if (*p != '(' || *(p + 1) == 0)
+ return -1;
+ for (++p; *p && isspace(*p); p++);
+ for (n = 0; n < 6 && *p && *p != ')'; n++) {
+ q = parse_float_decimal(&p, p + strlen(p));
+ if (!q)
+ break;
+ else {
+ v[n] = atof(q);
+ if (*p == ',')
+ p++;
+ for ( ; *p && isspace(*p); p++);
+ if (*p == ',')
+ for (++p; *p && isspace(*p); p++);
+ RELEASE(q);
+ }
+ }
+ if (*p != ')')
+ return -1;
+ p++;
+
+ switch (k) {
+ case K_TRNS__MATRIX:
+ if (n != 6)
+ return -1;
+ M->a = v[0]; M->c = v[1];
+ M->b = v[2]; M->d = v[3];
+ M->e = v[4]; M->f = v[5];
+ break;
+ case K_TRNS__TRANSLATE:
+ if (n != 1 && n != 2)
+ return -1;
+ M->a = M->d = 1.0;
+ M->c = M->b = 0.0;
+ M->e = v[0]; M->f = (n == 2) ? v[1] : 0.0;
+ break;
+ case K_TRNS__SCALE:
+ if (n != 1 && n != 2)
+ return -1;
+ M->a = v[0]; M->d = (n == 2) ? v[1] : v[0];
+ M->c = M->b = 0.0;
+ M->e = M->f = 0.0;
+ break;
+ case K_TRNS__ROTATE:
+ if (n != 1 && n != 3)
+ return -1;
+ M->a = cos(v[0] * M_PI / 180.0);
+ M->c = sin(v[0] * M_PI / 180.0);
+ M->b = -M->c; M->d = M->a;
+ M->e = (n == 3) ? v[1] : 0.0;
+ M->f = (n == 3) ? v[2] : 0.0;
+ break;
+ case K_TRNS__SKEWX:
+ if (n != 1)
+ return -1;
+ M->a = M->d = 1.0;
+ M->c = 0.0;
+ M->b = tan(v[0] * M_PI / 180.0);
+ break;
+ case K_TRNS__SKEWY:
+ if (n != 1)
+ return -1;
+ M->a = M->d = 1.0;
+ M->c = tan(v[0] * M_PI / 180.0);
+ M->b = 0.0;
+ break;
+ }
+
+ if (nextptr)
+ *nextptr = p;
+ return 0;
+}
+#endif /* ENABLE_HTML_SVG_TRANSFORM */
+
+int
+spc_html_at_begin_document (void)
+{
+ struct spc_html_ *sd = &_html_state;
+ return spc_handler_html__init(NULL, NULL, sd);
+}
+
+int
+spc_html_at_begin_page (void)
+{
+ struct spc_html_ *sd = &_html_state;
+ return spc_handler_html__bophook(NULL, NULL, sd);
+}
+
+int
+spc_html_at_end_page (void)
+{
+ struct spc_html_ *sd = &_html_state;
+ return spc_handler_html__eophook(NULL, NULL, sd);
+}
+
+int
+spc_html_at_end_document (void)
+{
+ struct spc_html_ *sd = &_html_state;
+ return spc_handler_html__clean(NULL, NULL, sd);
+}
+
+
+int
+spc_html_check_special (const char *buffer, long size)
+{
+ const char *p, *endptr;
+
+ p = buffer;
+ endptr = p + size;
+
+ for ( ; p < endptr && isspace(*p); p++);
+ size = (long) (endptr - p);
+ if (size >= strlen("html:") &&
+ !memcmp(p, "html:", strlen("html:"))) {
+ return 1;
+ }
+
+ return 0;
+}
+
+
+int
+spc_html_setup_handler (struct spc_handler *sph,
+ struct spc_env *spe, struct spc_arg *ap)
+{
+ ASSERT(sph && spe && ap);
+
+ for ( ; ap->curptr < ap->endptr && isspace(ap->curptr[0]); ap->curptr++);
+ if (ap->curptr + strlen("html:") > ap->endptr ||
+ memcmp(ap->curptr, "html:", strlen("html:"))) {
+ return -1;
+ }
+
+ ap->command = "";
+
+ sph->key = "html:";
+ sph->exec = &spc_handler_html_default;
+
+ ap->curptr += strlen("html:");
+ for ( ; ap->curptr < ap->endptr && isspace(ap->curptr[0]); ap->curptr++);
+
+ return 0;
+}
+
diff --git a/Build/source/texk/dvipdf-x/xsrc/spc_pdfm.c b/Build/source/texk/dvipdf-x/xsrc/spc_pdfm.c
new file mode 100644
index 00000000000..7aa8863ae9b
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/spc_pdfm.c
@@ -0,0 +1,2115 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2007-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <ctype.h>
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+#include "mfileio.h"
+
+#include "numbers.h"
+
+#include "fontmap.h"
+#include "dpxfile.h"
+#include "dpxutil.h"
+
+#include "pdfobj.h"
+#include "pdfparse.h"
+
+#include "pdfdoc.h"
+
+#include "pdfximage.h"
+#include "pdfdraw.h"
+#include "pdfcolor.h"
+#include "pdfdev.h"
+
+#include "specials.h"
+
+#include "spc_util.h"
+#include "spc_pdfm.h"
+
+
+#define ENABLE_TOUNICODE 1
+
+
+/* PLEASE REMOVE THIS */
+struct resource_map {
+ int type;
+ int res_id;
+};
+
+#ifdef ENABLE_TOUNICODE
+struct tounicode {
+ int cmap_id;
+ int unescape_backslash;
+ pdf_obj *taintkeys; /* An array of PDF names. */
+};
+#endif /* ENABLE_TOUNICODE */
+
+struct spc_pdf_
+{
+ pdf_obj *annot_dict; /* pending annotation dict */
+ int lowest_level; /* current min level of outlines */
+ struct ht_table *resourcemap; /* see remark below (somewhere) */
+#ifdef ENABLE_TOUNICODE
+ struct tounicode cd; /* For to-UTF16-BE conversion :( */
+#endif /* ENABLE_TOUNICODE */
+};
+
+#if 1
+static struct spc_pdf_ _pdf_stat = {
+ NULL,
+ 255,
+ NULL,
+#ifdef ENABLE_TOUNICODE
+ { -1, 0, NULL }
+#endif /* ENABLE_TOUNICODE */
+};
+#endif
+
+/* PLEASE REMOVE THIS */
+static void
+hval_free (void *vp)
+{
+ RELEASE(vp);
+}
+
+
+static int
+addresource (struct spc_pdf_ *sd, const char *ident, int res_id)
+{
+ struct resource_map *r;
+
+ if (!ident || res_id < 0)
+ return -1;
+
+ r = NEW(1, struct resource_map);
+ r->type = 0; /* unused */
+ r->res_id = res_id;
+
+ ht_append_table(sd->resourcemap, ident, strlen(ident), r);
+ spc_push_object(ident, pdf_ximage_get_reference(res_id));
+
+ return 0;
+}
+
+static int
+findresource (struct spc_pdf_ *sd, const char *ident)
+{
+ struct resource_map *r;
+
+ if (!ident)
+ return -1;
+
+ r = ht_lookup_table(sd->resourcemap, ident, strlen(ident));
+
+ return (r ? r->res_id : -1);
+}
+
+
+static int
+spc_handler_pdfm__init (struct spc_env *spe, struct spc_arg *ap, void *dp)
+{
+ struct spc_pdf_ *sd = dp;
+#ifdef ENABLE_TOUNICODE
+ static const char *default_taintkeys[] = {
+ "Title", "Author", "Subject", "Keywords",
+ "Creator", "Producer", "Contents", "Subj",
+ "TU", "T", "TM", NULL /* EOD */
+ };
+ int i;
+#endif /* ENABLE_TOUNICODE */
+
+ sd->annot_dict = NULL;
+ sd->lowest_level = 255;
+ sd->resourcemap = NEW(1, struct ht_table);
+ ht_init_table(sd->resourcemap, hval_free);
+
+#ifdef ENABLE_TOUNICODE
+ sd->cd.taintkeys = pdf_new_array();
+ for (i = 0; default_taintkeys[i] != NULL; i++) {
+ pdf_add_array(sd->cd.taintkeys,
+ pdf_new_name(default_taintkeys[i]));
+ }
+#endif /* ENABLE_TOUNICODE */
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm__clean (struct spc_env *spe, struct spc_arg *ap, void *dp)
+{
+ struct spc_pdf_ *sd = dp;
+
+ if (sd->annot_dict) {
+ WARN("Unbalanced bann and eann found.");
+ pdf_release_obj(sd->annot_dict);
+ }
+ sd->lowest_level = 255;
+ sd->annot_dict = NULL;
+ if (sd->resourcemap) {
+ ht_clear_table(sd->resourcemap);
+ RELEASE(sd->resourcemap);
+ }
+ sd->resourcemap = NULL;
+
+#ifdef ENABLE_TOUNICODE
+ if (sd->cd.taintkeys)
+ pdf_release_obj(sd->cd.taintkeys);
+ sd->cd.taintkeys = NULL;
+#endif /* ENABLE_TOUNICODE */
+
+ return 0;
+}
+
+
+int
+spc_pdfm_at_begin_document (void)
+{
+ struct spc_pdf_ *sd = &_pdf_stat;
+ return spc_handler_pdfm__init(NULL, NULL, sd);
+}
+
+int
+spc_pdfm_at_end_document (void)
+{
+ struct spc_pdf_ *sd = &_pdf_stat;
+ return spc_handler_pdfm__clean(NULL, NULL, sd);
+}
+
+
+/* Dvipdfm specials */
+static int
+spc_handler_pdfm_bop (struct spc_env *spe, struct spc_arg *args)
+{
+ if (args->curptr < args->endptr) {
+ pdf_doc_set_bop_content(args->curptr,
+ (long) (args->endptr - args->curptr));
+ }
+
+ args->curptr = args->endptr;
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm_eop (struct spc_env *spe, struct spc_arg *args)
+{
+ if (args->curptr < args->endptr) {
+ pdf_doc_set_eop_content(args->curptr,
+ (long) (args->endptr - args->curptr));
+ }
+
+ args->curptr = args->endptr;
+
+ return 0;
+}
+
+#define streamfiltered(o) \
+ (pdf_lookup_dict(pdf_stream_dict((o)), "Filter") ? 1 : 0)
+
+/* Why should we have this kind of things? */
+static int
+safeputresdent (pdf_obj *kp, pdf_obj *vp, void *dp)
+{
+ char *key;
+
+ ASSERT(kp && vp && dp);
+
+ key = pdf_name_value(kp);
+ if (pdf_lookup_dict(dp, key))
+ WARN("Object \"%s\" already defined in dict! (ignored)", key);
+ else {
+ pdf_add_dict(dp,
+ pdf_link_obj(kp), pdf_link_obj(vp));
+ }
+ return 0;
+}
+
+#ifndef pdf_obj_isaref
+#define pdf_obj_isaref(o) (pdf_obj_typeof((o)) == PDF_INDIRECT)
+#endif
+
+static int
+safeputresdict (pdf_obj *kp, pdf_obj *vp, void *dp)
+{
+ char *key;
+ pdf_obj *dict;
+
+ ASSERT(kp && vp && dp);
+
+ key = pdf_name_value(kp);
+ dict = pdf_lookup_dict(dp, key);
+
+ if (pdf_obj_isaref(vp)) {
+ pdf_add_dict(dp, pdf_new_name(key), pdf_link_obj(vp));
+ } else if (pdf_obj_typeof(vp) == PDF_DICT) {
+ if (dict)
+ pdf_foreach_dict(vp, safeputresdent, dict);
+ else {
+ pdf_add_dict(dp, pdf_new_name(key), pdf_link_obj(vp));
+ }
+ } else {
+ WARN("Invalid type (not DICT) for page/form resource dict entry: key=\"%s\"", key);
+ return -1;
+ }
+
+ return 0;
+}
+
+
+/* Think what happens if you do
+ *
+ * pdf:put @resources << /Font << >> >>
+ *
+ */
+static int
+spc_handler_pdfm_put (struct spc_env *spe, struct spc_arg *ap)
+{
+ pdf_obj *obj1, *obj2; /* put obj2 into obj1 */
+ char *ident;
+ int error = 0;
+
+ skip_white(&ap->curptr, ap->endptr);
+
+ ident = parse_opt_ident(&ap->curptr, ap->endptr);
+ if (!ident) {
+ spc_warn(spe, "Missing object identifier.");
+ return -1;
+ }
+ obj1 = spc_lookup_object(ident);
+ if (!obj1) {
+ spc_warn(spe, "Specified object not exist: %s", ident);
+ RELEASE(ident);
+ return -1;
+ }
+ skip_white(&ap->curptr, ap->endptr);
+
+ obj2 = parse_pdf_object(&ap->curptr, ap->endptr, NULL);
+ if (!obj2) {
+ spc_warn(spe, "Missing (an) object(s) to put into \"%s\"!", ident);
+ RELEASE(ident);
+ return -1;
+ }
+
+ switch (pdf_obj_typeof(obj1)) {
+ case PDF_DICT:
+ if (pdf_obj_typeof(obj2) != PDF_DICT) {
+ spc_warn(spe, "Inconsistent object type for \"put\" (expecting DICT): %s", ident);
+ error = -1;
+ } else {
+ if (!strcmp(ident, "resources"))
+ error = pdf_foreach_dict(obj2, safeputresdict, obj1);
+ else {
+ pdf_merge_dict(obj1, obj2);
+ }
+ }
+ break;
+
+ case PDF_STREAM:
+ if (pdf_obj_typeof(obj2) == PDF_DICT)
+ pdf_merge_dict(pdf_stream_dict(obj1), obj2);
+ else if (pdf_obj_typeof(obj2) == PDF_STREAM)
+#if 0
+ {
+ pdf_merge_dict(pdf_stream_dict(obj1), pdf_stream_dict(obj2));
+ pdf_add_stream(obj1, pdf_stream_dataptr(obj2), pdf_stream_length(obj2));
+ }
+#else
+ {
+ spc_warn(spe, "\"put\" operation not supported for STREAM <- STREAM: %s", ident);
+ error = -1;
+ }
+#endif
+ else {
+ spc_warn(spe, "Invalid type: expecting a DICT or STREAM: %s", ident);
+ error = -1;
+ }
+ break;
+
+ case PDF_ARRAY:
+ /* dvipdfm */
+ pdf_add_array(obj1, pdf_link_obj(obj2));
+ while (ap->curptr < ap->endptr) {
+ pdf_obj *obj3 = parse_pdf_object(&ap->curptr, ap->endptr, NULL);
+ if (!obj3)
+ break;
+ pdf_add_array(obj1, obj3);
+ skip_white(&ap->curptr, ap->endptr);
+ }
+ break;
+
+ default:
+ spc_warn(spe, "Can't \"put\" object into non-DICT/STREAM/ARRAY type object: %s", ident);
+ error = -1;
+ break;
+ }
+ pdf_release_obj(obj2);
+ RELEASE(ident);
+
+ return error;
+}
+
+
+#ifdef ENABLE_TOUNICODE
+
+/* For pdf:tounicode support
+ * This feature is provided for convenience. TeX can't do
+ * input encoding conversion.
+ */
+#include "cmap.h"
+
+static int
+reencodestring (CMap *cmap, pdf_obj *instring)
+{
+#define WBUF_SIZE 4096
+ unsigned char wbuf[WBUF_SIZE];
+ unsigned char *obufcur;
+ const unsigned char *inbufcur;
+ long inbufleft, obufleft;
+
+ if (!cmap || !instring)
+ return 0;
+
+ inbufleft = pdf_string_length(instring);
+ inbufcur = pdf_string_value (instring);
+
+ wbuf[0] = 0xfe;
+ wbuf[1] = 0xff;
+ obufcur = wbuf + 2;
+ obufleft = WBUF_SIZE - 2;
+
+ CMap_decode(cmap,
+ &inbufcur, &inbufleft,
+ &obufcur, &obufleft);
+
+ if (inbufleft > 0) {
+ return -1;
+ }
+
+ pdf_set_string(instring, wbuf, WBUF_SIZE - obufleft);
+
+ return 0;
+}
+
+/* tables/values used in UTF-8 interpretation -
+ code is based on ConvertUTF.[ch] sample code
+ published by the Unicode consortium */
+static unsigned long
+offsetsFromUTF8[6] = {
+ 0x00000000UL,
+ 0x00003080UL,
+ 0x000E2080UL,
+ 0x03C82080UL,
+ 0xFA082080UL,
+ 0x82082080UL
+};
+
+static unsigned char
+bytesFromUTF8[256] = {
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+ 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
+};
+
+static int
+maybe_reencode_utf8(pdf_obj *instring)
+{
+ unsigned char* inbuf;
+ int inlen;
+ int non_ascii = 0;
+ unsigned char* cp;
+ unsigned char* op;
+ unsigned char wbuf[WBUF_SIZE];
+
+ if (!instring)
+ return 0;
+
+ inlen = pdf_string_length(instring);
+ inbuf = pdf_string_value(instring);
+
+ /* check if the input string is strictly ASCII */
+ for (cp = inbuf; cp < inbuf + inlen; ++cp) {
+ if (*cp > 127) {
+ non_ascii = 1;
+ }
+ }
+ if (non_ascii == 0)
+ return 0; /* no need to reencode ASCII strings */
+
+ cp = inbuf;
+ op = wbuf;
+ *op++ = 0xfe;
+ *op++ = 0xff;
+ while (cp < inbuf + inlen) {
+ unsigned long usv = *cp++;
+ int extraBytes = bytesFromUTF8[usv];
+ if (cp + extraBytes > inbuf + inlen)
+ return -1; /* ill-formed, so give up reencoding */
+ switch (extraBytes) { /* note: code falls through cases! */
+ case 5: usv <<= 6; usv += *cp++;
+ case 4: usv <<= 6; usv += *cp++;
+ case 3: usv <<= 6; usv += *cp++;
+ case 2: usv <<= 6; usv += *cp++;
+ case 1: usv <<= 6; usv += *cp++;
+ case 0: ;
+ };
+ usv -= offsetsFromUTF8[extraBytes];
+ if (usv > 0x10FFFF)
+ return -1; /* out of valid Unicode range, give up */
+ if (usv > 0xFFFF) {
+ /* supplementary-plane character: generate high surrogate */
+ unsigned long hi = 0xdc00 + (usv - 0x10000) % 0x0400;
+ if (op > wbuf + WBUF_SIZE - 2)
+ return -1; /* out of space */
+ *op++ = hi / 256;
+ *op++ = hi % 256;
+ usv = 0xd800 + (usv - 0x10000) / 0x0400;
+ /* remaining value in usv is the low surrogate */
+ }
+ if (op > wbuf + WBUF_SIZE - 2)
+ return -1; /* out of space */
+ *op++ = usv / 256;
+ *op++ = usv % 256;
+ }
+
+ pdf_set_string(instring, wbuf, op - wbuf);
+
+ return 0;
+}
+
+static int
+needreencode (pdf_obj *kp, pdf_obj *vp, struct tounicode *cd)
+{
+ int r = 0, i;
+ pdf_obj *tk;
+
+ ASSERT( cd && cd->taintkeys );
+ ASSERT( pdf_obj_typeof(kp) == PDF_NAME );
+ ASSERT( pdf_obj_typeof(vp) == PDF_STRING );
+
+ for (i = 0; i < pdf_array_length(cd->taintkeys); i++) {
+ tk = pdf_get_array(cd->taintkeys, i);
+ ASSERT( tk && pdf_obj_typeof(tk) == PDF_NAME );
+ if (!strcmp(pdf_name_value(kp), pdf_name_value(tk))) {
+ r = 1;
+ break;
+ }
+ }
+ if (r) {
+ /* Check UTF-16BE BOM. */
+ if (pdf_string_length(vp) >= 2 &&
+ !memcmp(pdf_string_value(vp), "\xfe\xff", 2))
+ r = 0;
+ }
+
+ return r;
+}
+
+static int modstrings (pdf_obj *key, pdf_obj *value, void *pdata);
+
+static int
+modstrings (pdf_obj *kp, pdf_obj *vp, void *dp)
+{
+ int r = 0; /* continue */
+
+ ASSERT( pdf_obj_typeof(kp) == PDF_NAME );
+
+ switch (pdf_obj_typeof(vp)) {
+ case PDF_STRING:
+ {
+ CMap *cmap;
+ struct tounicode *cd = dp;
+ if (cd && cd->cmap_id >= 0 && cd->taintkeys) {
+ cmap = CMap_cache_get(cd->cmap_id);
+ if (needreencode(kp, vp, cd)) {
+ r = reencodestring(cmap, vp);
+ }
+ }
+ else {
+ r = maybe_reencode_utf8(vp);
+ }
+ if (r < 0) /* error occured... */
+ WARN("Failed to convert input string to UTF16...");
+ }
+ break;
+ case PDF_DICT:
+ r = pdf_foreach_dict(vp, modstrings, dp);
+ break;
+ case PDF_STREAM:
+ r = pdf_foreach_dict(pdf_stream_dict(vp), modstrings, dp);
+ break;
+ }
+
+ return r;
+}
+
+static pdf_obj *
+my_parse_pdf_dict (const char **pp, const char *endptr, struct tounicode *cd)
+{
+ pdf_obj *dict;
+
+#if 0
+/* disable this test, as we do utf8 reencoding with no cmap */
+ if (cd->cmap_id < 0)
+ return parse_pdf_dict(pp, endptr, NULL);
+#endif
+
+ /* :( */
+ if (cd && cd->unescape_backslash)
+ dict = parse_pdf_tainted_dict(pp, endptr);
+ else {
+ dict = parse_pdf_dict(pp, endptr, NULL);
+ }
+ if (dict)
+ pdf_foreach_dict(dict, modstrings, cd);
+
+ return dict;
+}
+
+#endif /* ENABLE_TOUNICODE */
+
+
+static int
+spc_handler_pdfm_annot (struct spc_env *spe, struct spc_arg *args)
+{
+#ifdef ENABLE_TOUNICODE
+ struct spc_pdf_ *sd = &_pdf_stat;
+#endif /* ENABLE_TOUNICODE */
+ pdf_obj *annot_dict;
+ pdf_rect rect;
+ char *ident = NULL;
+ pdf_coord cp;
+ transform_info ti;
+
+ skip_white(&args->curptr, args->endptr);
+ if (args->curptr[0] == '@') {
+ ident = parse_opt_ident(&args->curptr, args->endptr);
+ skip_white(&args->curptr, args->endptr);
+ }
+
+ transform_info_clear(&ti);
+ if (spc_util_read_dimtrns(spe, &ti, args, NULL, 0) < 0) {
+ if (ident)
+ RELEASE(ident);
+ return -1;
+ }
+
+ if ((ti.flags & INFO_HAS_USER_BBOX) &&
+ ((ti.flags & INFO_HAS_WIDTH) || (ti.flags & INFO_HAS_HEIGHT))) {
+ spc_warn(spe, "You can't specify both bbox and width/height.");
+ if (ident)
+ RELEASE(ident);
+ return -1;
+ }
+
+#ifdef ENABLE_TOUNICODE
+ annot_dict = my_parse_pdf_dict(&args->curptr, args->endptr, &sd->cd);
+#else
+ annot_dict = parse_pdf_dict(&args->curptr, args->endptr, NULL);
+#endif /* ENABLE_TOUNICODE */
+ if (!annot_dict) {
+ spc_warn(spe, "Could not find dictionary object.");
+ if (ident)
+ RELEASE(ident);
+ return -1;
+ } else if (!PDF_OBJ_DICTTYPE(annot_dict)) {
+ spc_warn(spe, "Invalid type: not dictionary object.");
+ if (ident)
+ RELEASE(ident);
+ pdf_release_obj(annot_dict);
+ return -1;
+ }
+
+ cp.x = spe->x_user; cp.y = spe->y_user;
+ pdf_dev_transform(&cp, NULL);
+ if (ti.flags & INFO_HAS_USER_BBOX) {
+ rect.llx = ti.bbox.llx + cp.x;
+ rect.lly = ti.bbox.lly + cp.y;
+ rect.urx = ti.bbox.urx + cp.x;
+ rect.ury = ti.bbox.ury + cp.y;
+ } else {
+ rect.llx = cp.x;
+ rect.lly = cp.y - spe->mag * ti.depth;
+ rect.urx = cp.x + spe->mag * ti.width;
+ rect.ury = cp.y + spe->mag * ti.height;
+ }
+
+ /* Order is important... */
+ if (ident)
+ spc_push_object(ident, pdf_link_obj(annot_dict));
+ /* This add reference. */
+ pdf_doc_add_annot(pdf_doc_current_page_number(), &rect, annot_dict);
+
+ if (ident) {
+ spc_flush_object(ident);
+ RELEASE(ident);
+ }
+ pdf_release_obj(annot_dict);
+
+ return 0;
+}
+
+/* NOTE: This can't have ident. See "Dvipdfm User's Manual". */
+static int
+spc_handler_pdfm_bann (struct spc_env *spe, struct spc_arg *args)
+{
+ struct spc_pdf_ *sd = &_pdf_stat;
+ int error = 0;
+
+ if (sd->annot_dict) {
+ spc_warn(spe, "Can't begin an annotation when one is pending.");
+ return -1;
+ }
+
+ skip_white(&args->curptr, args->endptr);
+
+#ifdef ENABLE_TOUNICODE
+ sd->annot_dict = my_parse_pdf_dict(&args->curptr, args->endptr, &sd->cd);
+#else
+ sd->annot_dict = parse_pdf_dict(&args->curptr, args->endptr, NULL);
+#endif /* ENABLE_TOUNICODE */
+ if (!sd->annot_dict) {
+ spc_warn(spe, "Ignoring annotation with invalid dictionary.");
+ return -1;
+ } else if (!PDF_OBJ_DICTTYPE(sd->annot_dict)) {
+ spc_warn(spe, "Invalid type: not a dictionary object.");
+ pdf_release_obj(sd->annot_dict);
+ sd->annot_dict = NULL;
+ return -1;
+ }
+
+ error = spc_begin_annot(spe, sd->annot_dict);
+
+ return error;
+}
+
+static int
+spc_handler_pdfm_eann (struct spc_env *spe, struct spc_arg *args)
+{
+ struct spc_pdf_ *sd = &_pdf_stat;
+ int error = 0;
+
+ if (!sd->annot_dict) {
+ spc_warn(spe, "Tried to end an annotation without starting one!");
+ return -1;
+ }
+
+ error = spc_end_annot(spe);
+
+ pdf_release_obj(sd->annot_dict);
+ sd->annot_dict = NULL;
+
+ return error;
+}
+
+
+/* Color:.... */
+static int
+spc_handler_pdfm_bcolor (struct spc_env *spe, struct spc_arg *ap)
+{
+ int error;
+ pdf_color fc, sc;
+
+ error = spc_util_read_colorspec(spe, &fc, ap, 0);
+ if (!error) {
+ if (ap->curptr < ap->endptr) {
+ error = spc_util_read_colorspec(spe, &sc, ap, 0);
+ } else {
+ pdf_color_copycolor(&sc, &fc);
+ }
+ }
+
+ if (error)
+ spc_warn(spe, "Invalid color specification?");
+ else {
+ pdf_color_push(&sc, &fc); /* save currentcolor */
+ pdf_dev_set_strokingcolor(&sc);
+ pdf_dev_set_nonstrokingcolor(&fc);
+ }
+
+ return error;
+}
+
+/* Different than "color rgb 1 0 0" ? */
+static int
+spc_handler_pdfm_scolor (struct spc_env *spe, struct spc_arg *ap)
+{
+ int error;
+ pdf_color fc, sc;
+
+ error = spc_util_read_colorspec(spe, &fc, ap, 0);
+ if (!error) {
+ if (ap->curptr < ap->endptr) {
+ error = spc_util_read_colorspec(spe, &sc, ap, 0);
+ } else {
+ pdf_color_copycolor(&sc, &fc);
+ }
+ }
+
+ if (error)
+ spc_warn(spe, "Invalid color specification?");
+ else {
+ pdf_color_set_default(&fc); /* ????? */
+ pdf_dev_set_strokingcolor(&sc);
+ pdf_dev_set_nonstrokingcolor(&fc);
+ }
+
+ return error;
+}
+
+static int
+spc_handler_pdfm_ecolor (struct spc_env *spe, struct spc_arg *args)
+{
+ pdf_color_pop();
+ return 0;
+}
+
+
+static int
+spc_handler_pdfm_btrans (struct spc_env *spe, struct spc_arg *args)
+{
+ pdf_tmatrix M;
+ transform_info ti;
+
+ transform_info_clear(&ti);
+ if (spc_util_read_dimtrns(spe, &ti, args, NULL, 0) < 0) {
+ return -1;
+ }
+
+ /* Create transformation matrix */
+ pdf_copymatrix(&M, &(ti.matrix));
+ M.e += ((1.0 - M.a) * spe->x_user - M.c * spe->y_user);
+ M.f += ((1.0 - M.d) * spe->y_user - M.b * spe->x_user);
+
+ pdf_dev_gsave();
+ pdf_dev_concat(&M);
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm_etrans (struct spc_env *spe, struct spc_arg *args)
+{
+ pdf_dev_grestore();
+
+ /*
+ * Unfortunately, the following line is necessary in case
+ * of a font or color change inside of the save/restore pair.
+ * Anything that was done there must be redone, so in effect,
+ * we make no assumptions about what fonts. We act like we are
+ * starting a new page.
+ */
+ pdf_dev_reset_fonts();
+ pdf_dev_reset_color();
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm_outline (struct spc_env *spe, struct spc_arg *args)
+{
+ struct spc_pdf_ *sd = &_pdf_stat;
+ pdf_obj *item_dict, *tmp;
+ int level, is_open = -1;
+ int current_depth;
+
+ skip_white(&args->curptr, args->endptr);
+
+ /*
+ * pdf:outline is extended to support open/close feature
+ *
+ * pdf:outline 1 ... (as DVIPDFM)
+ * pdf:outline [] 1 ... (open bookmark)
+ * pdf:outline [-] 1 ... (closed bookmark)
+ */
+ if (args->curptr+3 < args->endptr && *args->curptr == '[') {
+ args->curptr++;
+ if (*args->curptr == '-') {
+ args->curptr++;
+ } else {
+ is_open = 1;
+ }
+ args->curptr++;
+ }
+ skip_white(&args->curptr, args->endptr);
+
+ tmp = parse_pdf_object(&args->curptr, args->endptr, NULL);
+ if (!tmp) {
+ spc_warn(spe, "Missing number for outline item depth.");
+ return -1;
+ } else if (!PDF_OBJ_NUMBERTYPE(tmp)) {
+ pdf_release_obj(tmp);
+ spc_warn(spe, "Expecting number for outline item depth.");
+ return -1;
+ }
+
+ item_dict = NULL;
+
+ level = (int) pdf_number_value(tmp);
+ pdf_release_obj(tmp);
+
+ /* What is this? Starting at level 3 and can go down to level 1?
+ *
+ * Here is the original comment:
+ * Make sure we know where the starting level is
+ *
+ * NOTE: added
+ * We need this for converting pages from 3rd to... :(
+ */
+ sd->lowest_level = MIN(sd->lowest_level, level);
+
+ level += 1 - sd->lowest_level;
+
+#ifdef ENABLE_TOUNICODE
+ item_dict = my_parse_pdf_dict(&args->curptr, args->endptr, &sd->cd);
+#else
+ item_dict = parse_pdf_dict(&args->curptr, args->endptr, NULL);
+#endif /* ENABLE_TOUNICODE */
+ if (!item_dict) {
+ spc_warn(spe, "Ignoring invalid dictionary.");
+ return -1;
+ }
+ current_depth = pdf_doc_bookmarks_depth();
+ if (current_depth > level) {
+ while (current_depth-- > level)
+ pdf_doc_bookmarks_up();
+ } else if (current_depth < level) {
+ while (current_depth++ < level)
+ pdf_doc_bookmarks_down();
+ }
+
+ pdf_doc_bookmarks_add(item_dict, is_open);
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm_article (struct spc_env *spe, struct spc_arg *args)
+{
+#ifdef ENABLE_TOUNICODE
+ struct spc_pdf_ *sd = &_pdf_stat;
+#endif /* ENABLE_TOUNICODE */
+ char *ident;
+ pdf_obj *info_dict;
+
+ skip_white (&args->curptr, args->endptr);
+
+ ident = parse_opt_ident(&args->curptr, args->endptr);
+ if (!ident) {
+ spc_warn(spe, "Article name expected but not found.");
+ return -1;
+ }
+
+#ifdef ENABLE_TOUNICODE
+ info_dict = my_parse_pdf_dict(&args->curptr, args->endptr, &sd->cd);
+#else
+ info_dict = parse_pdf_dict(&args->curptr, args->endptr, NULL);
+#endif /* ENABLE_TOUNICODE */
+ if (!info_dict) {
+ spc_warn(spe, "Ignoring article with invalid info dictionary.");
+ RELEASE(ident);
+ return -1;
+ }
+
+ pdf_doc_begin_article(ident, pdf_link_obj(info_dict));
+ spc_push_object(ident, info_dict);
+ RELEASE(ident);
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm_bead (struct spc_env *spe, struct spc_arg *args)
+{
+#ifdef ENABLE_TOUNICODE
+ struct spc_pdf_ *sd = &_pdf_stat;
+#endif /* ENABLE_TOUNICODE */
+ pdf_obj *article;
+ pdf_obj *article_info;
+ char *article_name;
+ pdf_rect rect;
+ long page_no;
+ transform_info ti;
+ pdf_coord cp;
+
+ skip_white(&args->curptr, args->endptr);
+
+ if (args->curptr[0] != '@') {
+ spc_warn(spe, "Article identifier expected but not found.");
+ return -1;
+ }
+
+ article_name = parse_opt_ident(&args->curptr, args->endptr);
+ if (!article_name) {
+ spc_warn(spe, "Article reference expected but not found.");
+ return -1;
+ }
+
+ /* If okay so far, try to get a bounding box */
+ transform_info_clear(&ti);
+ if (spc_util_read_dimtrns(spe, &ti, args, NULL, 0) < 0) {
+ RELEASE(article_name);
+ return -1;
+ }
+
+ if ((ti.flags & INFO_HAS_USER_BBOX) &&
+ ((ti.flags & INFO_HAS_WIDTH) || (ti.flags & INFO_HAS_HEIGHT))) {
+ spc_warn(spe, "You can't specify both bbox and width/height.");
+ RELEASE(article_name);
+ return -1;
+ }
+
+ cp.x = spe->x_user; cp.y = spe->y_user;
+ pdf_dev_transform(&cp, NULL);
+ if (ti.flags & INFO_HAS_USER_BBOX) {
+ rect.llx = ti.bbox.llx + cp.x;
+ rect.lly = ti.bbox.lly + cp.y;
+ rect.urx = ti.bbox.urx + cp.x;
+ rect.ury = ti.bbox.ury + cp.y;
+ } else {
+ rect.llx = cp.x;
+ rect.lly = cp.y - spe->mag * ti.depth;
+ rect.urx = cp.x + spe->mag * ti.width;
+ rect.ury = cp.y + spe->mag * ti.height;
+ }
+
+ skip_white(&args->curptr, args->endptr);
+ if (args->curptr[0] != '<') {
+ article_info = pdf_new_dict();
+ } else {
+#ifdef ENABLE_TOUNICODE
+ article_info = my_parse_pdf_dict(&args->curptr, args->endptr, &sd->cd);
+#else
+ article_info = parse_pdf_dict(&args->curptr, args->endptr, NULL);
+#endif /* ENABLE_TOUNICODE */
+ if (!article_info) {
+ spc_warn(spe, "Error in reading dictionary.");
+ RELEASE(article_name);
+ return -1;
+ }
+ }
+
+ /* Does this article exist yet */
+ article = spc_lookup_object(article_name);
+ if (article) {
+ pdf_merge_dict (article, article_info);
+ pdf_release_obj(article_info);
+ } else {
+ pdf_doc_begin_article(article_name, pdf_link_obj(article_info));
+ spc_push_object(article_name, article_info);
+ }
+ page_no = pdf_doc_current_page_number();
+ pdf_doc_add_bead(article_name, NULL, page_no, &rect);
+
+ RELEASE(article_name);
+ return 0;
+}
+
+static int
+spc_handler_pdfm_image (struct spc_env *spe, struct spc_arg *args)
+{
+ struct spc_pdf_ *sd = &_pdf_stat;
+ int xobj_id;
+ char *ident = NULL;
+ pdf_obj *fspec, *attr = NULL;
+ transform_info ti;
+ long page_no;
+
+ skip_white(&args->curptr, args->endptr);
+ if (args->curptr[0] == '@') {
+ ident = parse_opt_ident(&args->curptr, args->endptr);
+ xobj_id = findresource(sd, ident);
+ if (xobj_id >= 0) {
+ spc_warn(spe, "Object reference name for image \"%s\" already used.", ident);
+ RELEASE(ident);
+ return -1;
+ }
+ }
+
+ transform_info_clear(&ti);
+ page_no = 1;
+ if (spc_util_read_dimtrns(spe, &ti, args, &page_no, 0) < 0) {
+ if (ident)
+ RELEASE(ident);
+ return -1;
+ }
+
+ skip_white(&args->curptr, args->endptr);
+ fspec = parse_pdf_object(&args->curptr, args->endptr, NULL);
+ if (!fspec) {
+ spc_warn(spe, "Missing filename string for pdf:image.");
+ if (ident)
+ RELEASE(ident);
+ return -1;
+ } else if (!PDF_OBJ_STRINGTYPE(fspec)) {
+ spc_warn(spe, "Missing filename string for pdf:image.");
+ pdf_release_obj(fspec);
+ if (ident)
+ RELEASE(ident);
+ return -1;
+ }
+
+ skip_white(&args->curptr, args->endptr);
+ if (args->curptr < args->endptr) {
+ attr = parse_pdf_object(&args->curptr, args->endptr, NULL);
+ if (!attr || !PDF_OBJ_DICTTYPE(attr)) {
+ spc_warn(spe, "Ignore invalid attribute dictionary.");
+ if (attr) pdf_release_obj(attr);
+ }
+ }
+
+ xobj_id = pdf_ximage_findresource(pdf_string_value(fspec), page_no, attr);
+ if (xobj_id < 0) {
+ spc_warn(spe, "Could not find image resource...");
+ pdf_release_obj(fspec);
+ if (ident)
+ RELEASE(ident);
+ return -1;
+ }
+
+ if (!(ti.flags & INFO_DO_HIDE))
+ pdf_dev_put_image(xobj_id, &ti, spe->x_user, spe->y_user);
+
+ if (ident) {
+ addresource(sd, ident, xobj_id);
+ RELEASE(ident);
+ }
+
+ pdf_release_obj(fspec);
+
+ return 0;
+}
+
+/* Use do_names instead. */
+static int
+spc_handler_pdfm_dest (struct spc_env *spe, struct spc_arg *args)
+{
+ pdf_obj *name, *array;
+ int error = 0;
+
+ skip_white(&args->curptr, args->endptr);
+
+ name = parse_pdf_object(&args->curptr, args->endptr, NULL);
+ if (!name) {
+ spc_warn(spe, "PDF string expected for destination name but not found.");
+ return -1;
+ } else if (!PDF_OBJ_STRINGTYPE(name)) {
+ spc_warn(spe, "PDF string expected for destination name but invalid type.");
+ pdf_release_obj(name);
+ return -1;
+ }
+#ifdef ENABLE_TOUNICODE
+ error = maybe_reencode_utf8(name);
+ if (error < 0)
+ WARN("Failed to convert input string to UTF16...");
+#endif
+ array = parse_pdf_object(&args->curptr, args->endptr, NULL);
+ if (!array) {
+ spc_warn(spe, "Destination not specified for pdf:dest.");
+ pdf_release_obj(name);
+ return -1;
+ } else if (!PDF_OBJ_ARRAYTYPE(array)) {
+ spc_warn(spe, "Destination not specified as an array object!");
+ pdf_release_obj(name);
+ pdf_release_obj(array);
+ return -1;
+ }
+
+ error = pdf_doc_add_names("Dests",
+ pdf_string_value (name),
+ pdf_string_length(name),
+ array);
+ pdf_release_obj(name);
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm_names (struct spc_env *spe, struct spc_arg *args)
+{
+ pdf_obj *category, *key, *value, *tmp;
+ int i, size;
+
+ category = parse_pdf_object(&args->curptr, args->endptr, NULL);
+ if (!category) {
+ spc_warn(spe, "PDF name expected but not found.");
+ return -1;
+ } else if (!PDF_OBJ_NAMETYPE(category)) {
+ spc_warn(spe, "PDF name expected but not found.");
+ pdf_release_obj(category);
+ return -1;
+ }
+
+ tmp = parse_pdf_object(&args->curptr, args->endptr, NULL);
+ if (!tmp) {
+ spc_warn(spe, "PDF object expected but not found.");
+ pdf_release_obj(category);
+ return -1;
+ } else if (PDF_OBJ_ARRAYTYPE(tmp)) {
+ size = pdf_array_length(tmp);
+ if (size % 2 != 0) {
+ spc_warn(spe, "Array size not multiple of 2 for pdf:names.");
+ pdf_release_obj(category);
+ pdf_release_obj(tmp);
+ return -1;
+ }
+
+ for (i = 0; i < size / 2; i++) {
+ key = pdf_get_array(tmp, 2 * i);
+ value = pdf_get_array(tmp, 2 * i + 1);
+ if (!PDF_OBJ_STRINGTYPE(key)) {
+ spc_warn(spe, "Name tree key must be string.");
+ pdf_release_obj(category);
+ pdf_release_obj(tmp);
+ return -1;
+ } else if (pdf_doc_add_names(pdf_name_value(category),
+ pdf_string_value (key),
+ pdf_string_length(key),
+ pdf_link_obj(value)) < 0) {
+ spc_warn(spe, "Failed to add Name tree entry...");
+ pdf_release_obj(category);
+ pdf_release_obj(tmp);
+ return -1;
+ }
+ }
+ pdf_release_obj(tmp);
+ } else if (PDF_OBJ_STRINGTYPE(tmp)) {
+ key = tmp;
+ value = parse_pdf_object(&args->curptr, args->endptr, NULL);
+ if (!value) {
+ pdf_release_obj(category);
+ pdf_release_obj(key);
+ spc_warn(spe, "PDF object expected but not found.");
+ return -1;
+ }
+ if (pdf_doc_add_names(pdf_name_value(category),
+ pdf_string_value (key),
+ pdf_string_length(key),
+ value) < 0) {
+ spc_warn(spe, "Failed to add Name tree entry...");
+ pdf_release_obj(category);
+ pdf_release_obj(key);
+ return -1;
+ }
+ pdf_release_obj(key);
+ } else {
+ pdf_release_obj(tmp);
+ pdf_release_obj(category);
+ spc_warn(spe, "Invalid object type for pdf:names.");
+ return -1;
+ }
+ pdf_release_obj(category);
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm_docinfo (struct spc_env *spe, struct spc_arg *args)
+{
+#ifdef ENABLE_TOUNICODE
+ struct spc_pdf_ *sd = &_pdf_stat;
+#endif /* ENABLE_TOUNICODE */
+ pdf_obj *docinfo, *dict;
+
+#ifdef ENABLE_TOUNICODE
+ dict = my_parse_pdf_dict(&args->curptr, args->endptr, &sd->cd);
+#else
+ dict = parse_pdf_dict(&args->curptr, args->endptr, NULL);
+#endif /* ENABLE_TOUNICODE */
+ if (!dict) {
+ spc_warn(spe, "Dictionary object expected but not found.");
+ return -1;
+ }
+
+ docinfo = pdf_doc_docinfo();
+ pdf_merge_dict(docinfo, dict);
+ pdf_release_obj(dict);
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm_docview (struct spc_env *spe, struct spc_arg *args)
+{
+#ifdef ENABLE_TOUNICODE
+ struct spc_pdf_ *sd = &_pdf_stat;
+#endif /* ENABLE_TOUNICODE */
+ pdf_obj *catalog, *dict;
+ pdf_obj *pref_old, *pref_add;
+
+#ifdef ENABLE_TOUNICODE
+ dict = my_parse_pdf_dict(&args->curptr, args->endptr, &sd->cd);
+#else
+ dict = parse_pdf_dict(&args->curptr, args->endptr, NULL);
+#endif /* ENABLE_TOUNICODE */
+ if (!dict) {
+ spc_warn(spe, "Dictionary object expected but not found.");
+ return -1;
+ }
+
+ catalog = pdf_doc_catalog();
+ /* Avoid overriding whole ViewerPreferences */
+ pref_old = pdf_lookup_dict(catalog, "ViewerPreferences");
+ pref_add = pdf_lookup_dict(dict, "ViewerPreferences");
+ if (pref_old && pref_add) {
+ pdf_merge_dict (pref_old, pref_add);
+ pdf_remove_dict(dict, "ViewerPreferences");
+ }
+ pdf_merge_dict (catalog, dict);
+ pdf_release_obj(dict);
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm_close (struct spc_env *spe, struct spc_arg *args)
+{
+ char *ident;
+
+ skip_white(&args->curptr, args->endptr);
+ ident = parse_opt_ident(&args->curptr, args->endptr);
+ if (ident) {
+ spc_flush_object(ident);
+ RELEASE(ident);
+ } else { /* Close all? */
+ spc_clear_objects();
+ }
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm_object (struct spc_env *spe, struct spc_arg *args)
+{
+ char *ident;
+ pdf_obj *object;
+
+ skip_white(&args->curptr, args->endptr);
+ ident = parse_opt_ident(&args->curptr, args->endptr);
+ if (!ident) {
+ spc_warn(spe, "Could not find a object identifier.");
+ return -1;
+ }
+
+ object = parse_pdf_object(&args->curptr, args->endptr, NULL);
+ if (!object) {
+ spc_warn(spe, "Could not find an object definition for \"%s\".", ident);
+ RELEASE(ident);
+ return -1;
+ } else {
+ spc_push_object(ident, object);
+ }
+ RELEASE(ident);
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm_content (struct spc_env *spe, struct spc_arg *args)
+{
+ long len = 0;
+
+ skip_white(&args->curptr, args->endptr);
+ if (args->curptr < args->endptr) {
+ pdf_tmatrix M;
+
+ pdf_setmatrix(&M, 1.0, 0.0, 0.0, 1.0, spe->x_user, spe->y_user);
+ work_buffer[len++] = ' ';
+ work_buffer[len++] = 'q';
+ work_buffer[len++] = ' ';
+ len += pdf_sprint_matrix(work_buffer + len, &M);
+ work_buffer[len++] = ' ';
+ work_buffer[len++] = 'c';
+ work_buffer[len++] = 'm';
+ work_buffer[len++] = ' ';
+
+ pdf_doc_add_page_content(work_buffer, len);
+ len = (long) (args->endptr - args->curptr);
+ pdf_doc_add_page_content(args->curptr, len);
+ pdf_doc_add_page_content(" Q", 2);
+ }
+ args->curptr = args->endptr;
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm_literal (struct spc_env *spe, struct spc_arg *args)
+{
+ int direct = 0;
+
+ skip_white(&args->curptr, args->endptr);
+ while (args->curptr < args->endptr) {
+ if (args->curptr + 7 <= args->endptr &&
+ !strncmp(args->curptr, "reverse", 7)) {
+ args->curptr += 7;
+ WARN("The special \"pdf:literal reverse ...\" is no longer supported.\nIgnore the \"reverse\" option.");
+ } else if (args->curptr + 6 <= args->endptr &&
+ !strncmp(args->curptr, "direct", 6)) {
+ direct = 1;
+ args->curptr += 6;
+ } else {
+ break;
+ }
+ skip_white(&args->curptr, args->endptr);
+ }
+
+ if (args->curptr < args->endptr) {
+ pdf_tmatrix M;
+ if (!direct) {
+ M.a = M.d = 1.0; M.b = M.c = 0.0;
+ M.e = spe->x_user; M.f = spe->y_user;
+ pdf_dev_concat(&M);
+ }
+ pdf_doc_add_page_content(" ", 1);
+ pdf_doc_add_page_content(args->curptr, (long) (args->endptr - args->curptr));
+ if (!direct) {
+ M.e = -spe->x_user; M.f = -spe->y_user;
+ pdf_dev_concat(&M);
+ }
+ }
+
+ args->curptr = args->endptr;
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm_bcontent (struct spc_env *spe, struct spc_arg *args)
+{
+ pdf_tmatrix M;
+ double xpos, ypos;
+
+ pdf_dev_gsave();
+ pdf_dev_get_coord(&xpos, &ypos);
+ pdf_setmatrix(&M, 1.0, 0.0, 0.0, 1.0, spe->x_user - xpos, spe->y_user - ypos);
+ pdf_dev_concat(&M);
+ pdf_dev_push_coord(spe->x_user, spe->y_user);
+ return 0;
+}
+
+static int
+spc_handler_pdfm_econtent (struct spc_env *spe, struct spc_arg *args)
+{
+ pdf_dev_pop_coord();
+ pdf_dev_grestore();
+ return 0;
+}
+
+static int
+spc_handler_pdfm_code (struct spc_env *spe, struct spc_arg *args)
+{
+ skip_white(&args->curptr, args->endptr);
+
+ if (args->curptr < args->endptr) {
+ pdf_doc_add_page_content(" ", 1);
+ pdf_doc_add_page_content(args->curptr, (long) (args->endptr - args->curptr));
+ args->curptr = args->endptr;
+ }
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm_do_nothing (struct spc_env *spe, struct spc_arg *args)
+{
+ args->curptr = args->endptr;
+ return 0;
+}
+
+#define STRING_STREAM 0
+#define FILE_STREAM 1
+
+static int
+spc_handler_pdfm_stream_with_type (struct spc_env *spe, struct spc_arg *args, int type)
+{
+ pdf_obj *fstream;
+ long nb_read;
+ char *ident, *instring, *fullname;
+ pdf_obj *tmp;
+ FILE *fp;
+
+ skip_white(&args->curptr, args->endptr);
+
+ ident = parse_opt_ident(&args->curptr, args->endptr);
+ if (!ident) {
+ spc_warn(spe, "Missing objname for pdf:(f)stream.");
+ return -1;
+ }
+
+ skip_white(&args->curptr, args->endptr);
+
+ tmp = parse_pdf_object(&args->curptr, args->endptr, NULL);
+ if (!tmp) {
+ spc_warn(spe, "Missing input string for pdf:(f)stream.");
+ RELEASE(ident);
+ return -1;
+ } else if (!PDF_OBJ_STRINGTYPE(tmp)) {
+ spc_warn(spe, "Invalid type of input string for pdf:(f)stream.");
+ pdf_release_obj(tmp);
+ RELEASE(ident);
+ return -1;
+ }
+
+ instring = pdf_string_value(tmp);
+
+ switch (type) {
+ case FILE_STREAM:
+ if (!instring) {
+ spc_warn(spe, "Missing filename for pdf:fstream.");
+ pdf_release_obj(tmp);
+ RELEASE(ident);
+ return -1;
+ }
+ fullname = kpse_find_pict(instring);
+ if (!fullname) {
+ spc_warn(spe, "File \"%s\" not found.", instring);
+ pdf_release_obj(tmp);
+ RELEASE(ident);
+ return -1;
+ }
+ fp = DPXFOPEN(fullname, DPX_RES_TYPE_BINARY);
+ if (!fp) {
+ spc_warn(spe, "Could not open file: %s", instring);
+ pdf_release_obj(tmp);
+ RELEASE(ident);
+ RELEASE(fullname);
+ return -1;
+ }
+ fstream = pdf_new_stream(STREAM_COMPRESS);
+ while ((nb_read =
+ fread(work_buffer, sizeof(char), WORK_BUFFER_SIZE, fp)) > 0)
+ pdf_add_stream(fstream, work_buffer, nb_read);
+ MFCLOSE(fp);
+ RELEASE(fullname);
+ break;
+ case STRING_STREAM:
+ fstream = pdf_new_stream(STREAM_COMPRESS);
+ if (instring)
+ pdf_add_stream(fstream, instring, strlen(instring));
+ break;
+ default:
+ pdf_release_obj(tmp);
+ RELEASE(ident);
+ return -1;
+ }
+ pdf_release_obj(tmp);
+
+ /*
+ * Optional dict.
+ *
+ * TODO: check Length, Filter...
+ */
+ skip_white(&args->curptr, args->endptr);
+
+ if (args->curptr[0] == '<') {
+ pdf_obj *stream_dict;
+
+ stream_dict = pdf_stream_dict(fstream);
+
+ tmp = parse_pdf_dict(&args->curptr, args->endptr, NULL);
+ if (!tmp) {
+ spc_warn(spe, "Parsing dictionary failed.");
+ pdf_release_obj(fstream);
+ RELEASE(ident);
+ return -1;
+ }
+ if (pdf_lookup_dict(tmp, "Length")) {
+ pdf_remove_dict(tmp, "Length");
+ } else if (pdf_lookup_dict(tmp, "Filter")) {
+ pdf_remove_dict(tmp, "Filter");
+ }
+ pdf_merge_dict(stream_dict, tmp);
+ pdf_release_obj(tmp);
+ }
+
+ /* Users should explicitly close this. */
+ spc_push_object(ident, fstream);
+ RELEASE(ident);
+
+ return 0;
+}
+
+/*
+ * STREAM: Create a PDF stream object from an input string.
+ *
+ * pdf: stream @objname (input_string) [PDF_DICT]
+ */
+static int
+spc_handler_pdfm_stream (struct spc_env *spe, struct spc_arg *args)
+{
+ return spc_handler_pdfm_stream_with_type (spe, args, STRING_STREAM);
+}
+
+/*
+ * FSTREAM: Create a PDF stream object from an existing file.
+ *
+ * pdf: fstream @objname (filename) [PDF_DICT]
+ */
+static int
+spc_handler_pdfm_fstream (struct spc_env *spe, struct spc_arg *args)
+{
+ return spc_handler_pdfm_stream_with_type (spe, args, FILE_STREAM);
+}
+
+/* Grab page content as follows:
+ *
+ * Reference point = (x_user, y_user)
+ *
+ * Case 1. \special{pdf:bxobj @obj width WD height HT depth DP}
+ *
+ * Grab the box with the lower-left corner (x_user, y_user-DP)
+ * and the upper right corner (x_user+WD, y_user+HT).
+ *
+ * Case 2. \special{pdf:bxobj @obj bbox LLX LLY URX, URY}
+ *
+ * Grab the box with the lower-left corner (x_user+LLX, y_user+LLY)
+ * and the upper right corner (x_user+URX, y_user+URY).
+ *
+ * Note that scale, xscale, yscale, xoffset, yoffset options are ignored.
+ */
+static int
+spc_handler_pdfm_bform (struct spc_env *spe, struct spc_arg *args)
+{
+ int xobj_id;
+ char *ident;
+ pdf_rect cropbox;
+ transform_info ti;
+
+ skip_white(&args->curptr, args->endptr);
+
+ ident = parse_opt_ident(&args->curptr, args->endptr);
+ if (!ident) {
+ spc_warn(spe, "A form XObject must have name.");
+ return -1;
+ }
+
+ transform_info_clear(&ti);
+ if (spc_util_read_dimtrns(spe, &ti, args, NULL, 0) < 0) {
+ RELEASE(ident);
+ return -1;
+ }
+
+ /* A XForm with zero dimension results in a non-invertible transformation
+ * matrix. And it may result in unpredictable behaviour. It might be an
+ * error in Acrobat. Bounding box with zero dimension may cause division
+ * by zero.
+ */
+ if (ti.flags & INFO_HAS_USER_BBOX) {
+ if (ti.bbox.urx - ti.bbox.llx == 0.0 ||
+ ti.bbox.ury - ti.bbox.lly == 0.0) {
+ spc_warn(spe, "Bounding box has a zero dimension.");
+ RELEASE(ident);
+ return -1;
+ }
+ cropbox.llx = ti.bbox.llx;
+ cropbox.lly = ti.bbox.lly;
+ cropbox.urx = ti.bbox.urx;
+ cropbox.ury = ti.bbox.ury;
+ } else {
+ if (ti.width == 0.0 ||
+ ti.depth + ti.height == 0.0) {
+ spc_warn(spe, "Bounding box has a zero dimension.");
+ RELEASE(ident);
+ return -1;
+ }
+ cropbox.llx = 0.0;
+ cropbox.lly = -ti.depth;
+ cropbox.urx = ti.width;
+ cropbox.ury = ti.height;
+ }
+
+ xobj_id = pdf_doc_begin_grabbing(ident, spe->x_user, spe->y_user, &cropbox);
+
+ if (xobj_id < 0) {
+ RELEASE(ident);
+ spc_warn(spe, "Couldn't start form object.");
+ return -1;
+ }
+
+ spc_push_object(ident, pdf_ximage_get_reference(xobj_id));
+ RELEASE(ident);
+
+ return 0;
+}
+
+/* An extra dictionary after exobj must be merged to the form dictionary,
+ * not resource dictionary.
+ * Please use pdf:put @resources (before pdf:exobj) instead.
+ */
+static int
+spc_handler_pdfm_eform (struct spc_env *spe, struct spc_arg *args)
+{
+ pdf_obj *attrib = NULL;
+
+ skip_white(&args->curptr, args->endptr);
+
+ if (args->curptr < args->endptr) {
+ attrib = parse_pdf_dict(&args->curptr, args->endptr, NULL);
+ if (attrib && !PDF_OBJ_DICTTYPE(attrib)) {
+ pdf_release_obj(attrib);
+ attrib = NULL;
+ }
+ }
+ pdf_doc_end_grabbing(attrib);
+
+ return 0;
+}
+
+/* Saved XObjects can be used as follows:
+ *
+ * Reference point = (x_user, y_user)
+ *
+ * Case 1. \special{pdf:uxobj @obj width WD height HT depth DP}
+ *
+ * Scale the XObject to fit in the box
+ * [x_user, y_user-DP, x_user+WD, y_user+HT].
+ *
+ * Case 2. \special{pdf:uxobj @obj xscale XS yscale YS}
+ *
+ * Scale the XObject with XS and YS. Note that width and xscale
+ * or height and yscale cannot be used together.
+ *
+ * Case 3. \special{pdf:bxobj @obj bbox LLX LLY URX, URY}
+ *
+ * Scale the XObject to fit in the box
+ * [x_user+LLX, y_user+LLY, x_user+URX, y_user+URY].
+ *
+ * Note that xoffset and yoffset moves the reference point where the
+ * lower-left corner of the XObject will be put.
+ */
+static int
+spc_handler_pdfm_uxobj (struct spc_env *spe, struct spc_arg *args)
+{
+ struct spc_pdf_ *sd = &_pdf_stat;
+ int xobj_id;
+ char *ident;
+ transform_info ti;
+
+ skip_white(&args->curptr, args->endptr);
+
+ ident = parse_opt_ident(&args->curptr, args->endptr);
+ if (!ident) {
+ spc_warn(spe, "No object identifier given.");
+ return -1;
+ }
+
+ transform_info_clear(&ti);
+ if (args->curptr < args->endptr) {
+ if (spc_util_read_dimtrns(spe, &ti, args, NULL, 0) < 0) {
+ RELEASE(ident);
+ return -1;
+ }
+ }
+
+ /* Dvipdfmx was suddenly changed to use file name to identify
+ * external images. We can't use ident to find image resource
+ * here.
+ */
+ xobj_id = findresource(sd, ident);
+ if (xobj_id < 0) {
+ xobj_id = pdf_ximage_findresource(ident, 0, NULL);
+ if (xobj_id < 0) {
+ spc_warn(spe, "Specified (image) object doesn't exist: %s", ident);
+ RELEASE(ident);
+ return -1;
+ }
+ }
+
+ pdf_dev_put_image(xobj_id, &ti, spe->x_user, spe->y_user);
+ RELEASE(ident);
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm_link (struct spc_env *spe, struct spc_arg *args)
+{
+ return spc_resume_annot(spe);
+}
+
+static int
+spc_handler_pdfm_nolink (struct spc_env *spe, struct spc_arg *args)
+{
+ return spc_suspend_annot(spe);
+}
+
+
+
+/* Handled at BOP */
+static int
+spc_handler_pdfm_pagesize (struct spc_env *spe, struct spc_arg *args)
+{
+ args->curptr = args->endptr;
+
+ return 0;
+}
+
+/* Please remove this.
+ * This should be handled before processing pages!
+ */
+static int
+spc_handler_pdfm_bgcolor (struct spc_env *spe, struct spc_arg *args)
+{
+ int error;
+ pdf_color colorspec;
+
+ error = spc_util_read_colorspec(spe, &colorspec, args, 0);
+ if (error)
+ spc_warn(spe, "No valid color specified?");
+ else {
+ pdf_doc_set_bgcolor(&colorspec);
+ }
+
+ return error;
+}
+
+static int
+spc_handler_pdfm_mapline (struct spc_env *spe, struct spc_arg *ap)
+{
+ fontmap_rec *mrec;
+ char *map_name, opchr;
+ int error = 0;
+
+ skip_white(&ap->curptr, ap->endptr);
+ if (ap->curptr >= ap->endptr) {
+ spc_warn(spe, "Empty mapline special?");
+ return -1;
+ }
+
+ opchr = ap->curptr[0];
+ if (opchr == '-' || opchr == '+')
+ ap->curptr++;
+
+ skip_white(&ap->curptr, ap->endptr);
+
+ switch (opchr) {
+ case '-':
+ map_name = parse_ident(&ap->curptr, ap->endptr);
+ if (map_name) {
+ pdf_remove_fontmap_record(map_name);
+ RELEASE(map_name);
+ } else {
+ spc_warn(spe, "Invalid fontmap line: Missing TFM name.");
+ error = -1;
+ }
+ break;
+ case '+':
+ mrec = NEW(1, fontmap_rec);
+ pdf_init_fontmap_record(mrec);
+ error = pdf_read_fontmap_line(mrec, ap->curptr, (long) (ap->endptr - ap->curptr), is_pdfm_mapline(ap->curptr));
+ if (error)
+ spc_warn(spe, "Invalid fontmap line.");
+ else {
+ pdf_append_fontmap_record(mrec->map_name, mrec);
+ }
+ pdf_clear_fontmap_record(mrec);
+ RELEASE(mrec);
+ break;
+ default:
+ mrec = NEW(1, fontmap_rec);
+ pdf_init_fontmap_record(mrec);
+ error = pdf_read_fontmap_line(mrec, ap->curptr, (long) (ap->endptr - ap->curptr), is_pdfm_mapline(ap->curptr));
+ if (error)
+ spc_warn(spe, "Invalid fontmap line.");
+ else {
+ pdf_insert_fontmap_record(mrec->map_name, mrec);
+ }
+ pdf_clear_fontmap_record(mrec);
+ RELEASE(mrec);
+ break;
+ }
+ if (!error)
+ ap->curptr = ap->endptr;
+
+ return 0;
+}
+
+static int
+spc_handler_pdfm_mapfile (struct spc_env *spe, struct spc_arg *args)
+{
+ char *mapfile;
+ int mode, error = 0;
+
+ skip_white(&args->curptr, args->endptr);
+ if (args->curptr >= args->endptr)
+ return 0;
+
+ switch (args->curptr[0]) {
+ case '-':
+ mode = FONTMAP_RMODE_REMOVE;
+ args->curptr++;
+ break;
+ case '+':
+ mode = FONTMAP_RMODE_APPEND;
+ args->curptr++;
+ break;
+ default:
+ mode = FONTMAP_RMODE_REPLACE;
+ break;
+ }
+
+ mapfile = parse_val_ident(&args->curptr, args->endptr);
+ if (!mapfile) {
+ spc_warn(spe, "No fontmap file specified.");
+ return -1;
+ } else {
+ error = pdf_load_fontmap_file(mapfile, mode);
+ }
+ RELEASE(mapfile);
+
+ return error;
+}
+
+
+#ifdef ENABLE_TOUNICODE
+static int
+spc_handler_pdfm_tounicode (struct spc_env *spe, struct spc_arg *args)
+{
+ struct spc_pdf_ *sd = &_pdf_stat;
+ char *cmap_name;
+
+ /* First clear */
+ sd->cd.cmap_id = -1;
+ sd->cd.unescape_backslash = 0;
+
+ skip_white(&args->curptr, args->endptr);
+ if (args->curptr >= args->endptr) {
+ spc_warn(spe, "Missing CMap name for pdf:tounicode.");
+ return -1;
+ }
+
+ /* _FIXME_
+ * Any valid char allowed for PDF name object should be allowed here.
+ * The argument to this special should be a PDF name obejct.
+ * But it's too late to change this special.
+ */
+ cmap_name = parse_ident(&args->curptr, args->endptr);
+ if (!cmap_name) {
+ spc_warn(spe, "Missing ToUnicode mapping name...");
+ return -1;
+ }
+
+ sd->cd.cmap_id = CMap_cache_find(cmap_name);
+ if (sd->cd.cmap_id < 0) {
+ spc_warn(spe, "Failed to load ToUnicode mapping: %s", cmap_name);
+ RELEASE(cmap_name);
+ return -1;
+ }
+
+ /* Shift-JIS like encoding may contain backslash in 2nd byte.
+ * WARNING: This will add nasty extension to PDF parser.
+ */
+ if (sd->cd.cmap_id >= 0) {
+ if (strstr(cmap_name, "RKSJ") ||
+ strstr(cmap_name, "B5") ||
+ strstr(cmap_name, "GBK") ||
+ strstr(cmap_name, "KSC"))
+ sd->cd.unescape_backslash = 1;
+ }
+ RELEASE(cmap_name);
+ return 0;
+}
+#endif /* ENABLE_TOUNICODE */
+
+
+static struct spc_handler pdfm_handlers[] = {
+ {"annotation", spc_handler_pdfm_annot},
+ {"annotate", spc_handler_pdfm_annot},
+ {"annot", spc_handler_pdfm_annot},
+ {"ann", spc_handler_pdfm_annot},
+
+ {"outline", spc_handler_pdfm_outline},
+ {"out", spc_handler_pdfm_outline},
+
+ {"article", spc_handler_pdfm_article},
+ {"art", spc_handler_pdfm_article},
+
+ {"bead", spc_handler_pdfm_bead},
+ {"thread", spc_handler_pdfm_bead},
+
+ {"destination", spc_handler_pdfm_dest},
+ {"dest", spc_handler_pdfm_dest},
+
+
+ {"object", spc_handler_pdfm_object},
+ {"obj", spc_handler_pdfm_object},
+
+
+ {"docinfo", spc_handler_pdfm_docinfo},
+ {"docview", spc_handler_pdfm_docview},
+
+ {"content", spc_handler_pdfm_content},
+ {"put", spc_handler_pdfm_put},
+ {"close", spc_handler_pdfm_close},
+ {"bop", spc_handler_pdfm_bop},
+ {"eop", spc_handler_pdfm_eop},
+
+ {"image", spc_handler_pdfm_image},
+ {"img", spc_handler_pdfm_image},
+ {"epdf", spc_handler_pdfm_image},
+
+ {"link", spc_handler_pdfm_link},
+ {"nolink", spc_handler_pdfm_nolink},
+
+ {"begincolor", spc_handler_pdfm_bcolor},
+ {"bcolor", spc_handler_pdfm_bcolor},
+ {"bc", spc_handler_pdfm_bcolor},
+
+ {"setcolor", spc_handler_pdfm_scolor},
+ {"scolor", spc_handler_pdfm_scolor},
+ {"sc", spc_handler_pdfm_scolor},
+
+ {"endcolor", spc_handler_pdfm_ecolor},
+ {"ecolor", spc_handler_pdfm_ecolor},
+ {"ec", spc_handler_pdfm_ecolor},
+
+ {"begingray", spc_handler_pdfm_bcolor},
+ {"bgray", spc_handler_pdfm_bcolor},
+ {"bg", spc_handler_pdfm_bcolor},
+
+ {"endgray", spc_handler_pdfm_ecolor},
+ {"egray", spc_handler_pdfm_ecolor},
+ {"eg", spc_handler_pdfm_ecolor},
+
+ {"bgcolor", spc_handler_pdfm_bgcolor},
+ {"bgc", spc_handler_pdfm_bgcolor},
+ {"bbc", spc_handler_pdfm_bgcolor},
+ {"bbg", spc_handler_pdfm_bgcolor},
+
+ {"pagesize", spc_handler_pdfm_pagesize},
+
+ {"bannot", spc_handler_pdfm_bann},
+ {"beginann", spc_handler_pdfm_bann},
+ {"bann", spc_handler_pdfm_bann},
+
+ {"eannot", spc_handler_pdfm_eann},
+ {"endann", spc_handler_pdfm_eann},
+ {"eann", spc_handler_pdfm_eann},
+
+ {"btrans", spc_handler_pdfm_btrans},
+ {"begintransform", spc_handler_pdfm_btrans},
+ {"begintrans", spc_handler_pdfm_btrans},
+ {"bt", spc_handler_pdfm_btrans},
+
+ {"etrans", spc_handler_pdfm_etrans},
+ {"endtransform", spc_handler_pdfm_etrans},
+ {"endtrans", spc_handler_pdfm_etrans},
+ {"et", spc_handler_pdfm_etrans},
+
+ {"bform", spc_handler_pdfm_bform},
+ {"beginxobj", spc_handler_pdfm_bform},
+ {"bxobj", spc_handler_pdfm_bform},
+
+ {"eform", spc_handler_pdfm_eform},
+ {"endxobj", spc_handler_pdfm_eform},
+ {"exobj", spc_handler_pdfm_eform},
+
+ {"usexobj", spc_handler_pdfm_uxobj},
+ {"uxobj", spc_handler_pdfm_uxobj},
+
+#ifdef ENABLE_TOUNICODE
+ {"tounicode", spc_handler_pdfm_tounicode},
+#endif /* ENABLE_TOUNICODE */
+ {"literal", spc_handler_pdfm_literal},
+ {"stream", spc_handler_pdfm_stream},
+ {"fstream", spc_handler_pdfm_fstream},
+ {"names", spc_handler_pdfm_names},
+ {"mapline", spc_handler_pdfm_mapline},
+ {"mapfile", spc_handler_pdfm_mapfile},
+
+ {"bcontent", spc_handler_pdfm_bcontent},
+ {"econtent", spc_handler_pdfm_econtent},
+ {"code", spc_handler_pdfm_code},
+
+ {"minorversion", spc_handler_pdfm_do_nothing},
+ {"encrypt", spc_handler_pdfm_do_nothing},
+};
+
+int
+spc_pdfm_check_special (const char *buf, long len)
+{
+ int r = 0;
+ const char *p, *endptr;
+
+ p = buf;
+ endptr = p + len;
+
+ skip_white(&p, endptr);
+ if (p + strlen("pdf:") <= endptr &&
+ !memcmp(p, "pdf:", strlen("pdf:"))) {
+ r = 1;
+ }
+
+ return r;
+}
+
+int
+spc_pdfm_setup_handler (struct spc_handler *sph,
+ struct spc_env *spe, struct spc_arg *ap)
+{
+ int error = -1, i;
+ char *q;
+
+ ASSERT(sph && spe && ap);
+
+ skip_white(&ap->curptr, ap->endptr);
+ if (ap->curptr + strlen("pdf:") >= ap->endptr ||
+ memcmp(ap->curptr, "pdf:", strlen("pdf:"))) {
+ spc_warn(spe, "Not pdf: special???");
+ return -1;
+ }
+ ap->curptr += strlen("pdf:");
+
+ skip_white(&ap->curptr, ap->endptr);
+ q = parse_c_ident(&ap->curptr, ap->endptr);
+ if (q) {
+ for (i = 0;
+ i < sizeof(pdfm_handlers) / sizeof(struct spc_handler); i++) {
+ if (!strcmp(q, pdfm_handlers[i].key)) {
+ ap->command = pdfm_handlers[i].key;
+ sph->key = "pdf:";
+ sph->exec = pdfm_handlers[i].exec;
+ skip_white(&ap->curptr, ap->endptr);
+ error = 0;
+ break;
+ }
+ }
+ RELEASE(q);
+ }
+
+ return error;
+}
+
diff --git a/Build/source/texk/dvipdf-x/xsrc/spc_tpic.c b/Build/source/texk/dvipdf-x/xsrc/spc_tpic.c
new file mode 100644
index 00000000000..bf8652c0e02
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/spc_tpic.c
@@ -0,0 +1,1151 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+
+#include "numbers.h"
+#include "dpxutil.h"
+
+#include "pdfdoc.h"
+
+#include "pdfdraw.h"
+#include "pdfdev.h"
+
+#include "specials.h"
+#include "spc_tpic.h"
+
+#define DEBUG 1
+#define ENABLE_SPC_NAMESPACE 1
+
+/*
+ * Following "constant" converts milli-inches to
+ * device (in this case PDF stream) coordinates.
+ */
+
+#define MI2DEV (0.072/pdf_dev_scale())
+
+/*
+ * Value for 'sh' command 'g' is interpreted as
+ *
+ * gray color value 1-g for "solid"
+ * opacity value g for "opacity"
+ * shape value g for "shape"
+ */
+#define TPIC_MODE__FILL_SOLID 0
+#define TPIC_MODE__FILL_OPACITY 1
+#define TPIC_MODE__FILL_SHAPE 2
+
+#ifndef ISBLANK
+# define ISBLANK(c) ( (c) == ' ' || (c) == '\t' )
+#endif
+
+static void
+skip_blank (const char **pp, const char *endptr)
+{
+ const char *p = *pp;
+ for ( ; p < endptr && ISBLANK(*p); p++);
+ *pp = p;
+}
+
+struct spc_tpic_
+{
+ struct {
+ int fill;
+ } mode;
+
+ /* state */
+ double pen_size;
+ int fill_shape; /* boolean */
+ double fill_color;
+
+ pdf_coord *points;
+ int num_points;
+ int max_points;
+};
+
+#if 1
+static struct spc_tpic_ _tpic_state;
+#endif
+
+/* We use pdf_doc_add_page_content() here
+ * since we always draw isolated graphics.
+ */
+static void
+tpic__clear (struct spc_tpic_ *tp)
+{
+ if (tp->points) {
+ RELEASE(tp->points);
+ tp->points = NULL;
+ }
+ tp->num_points = 0;
+ tp->max_points = 0;
+ tp->fill_shape = 0;
+ tp->fill_color = 0.0;
+}
+
+
+static pdf_obj *
+create_xgstate (double a /* alpha */, int f_ais /* alpha is shape */)
+{
+ pdf_obj *dict;
+
+ dict = pdf_new_dict();
+ pdf_add_dict(dict,
+ pdf_new_name("Type"),
+ pdf_new_name("ExtGState"));
+ if (f_ais) {
+ pdf_add_dict(dict,
+ pdf_new_name("AIS"),
+ pdf_new_boolean(1));
+ }
+ pdf_add_dict(dict,
+ pdf_new_name("ca"),
+ pdf_new_number(a));
+
+ return dict;
+}
+
+static int
+check_resourcestatus (const char *category, const char *resname)
+{
+ pdf_obj *dict1, *dict2;
+
+ dict1 = pdf_doc_current_page_resources();
+ if (!dict1)
+ return 0;
+
+ dict2 = pdf_lookup_dict(dict1, category);
+ if (dict2 &&
+ pdf_obj_typeof(dict2) == PDF_DICT) {
+ if (pdf_lookup_dict(dict2, resname))
+ return 1;
+ }
+ return 0;
+}
+
+static int
+set_linestyle (double pn, double da)
+{
+ double dp[2]; /* dash pattern */
+
+ pdf_dev_setlinejoin(1);
+ pdf_dev_setmiterlimit(1.4);
+ pdf_dev_setlinewidth(pn);
+ if (da > 0.0) {
+ dp[0] = da * 72.0;
+ pdf_dev_setdash(1, dp, 0);
+ pdf_dev_setlinecap(0);
+ } else if (da < 0.0) {
+ dp[0] = pn;
+ dp[1] = -da * 72.0;
+ pdf_dev_setdash(2, dp, 0);
+ pdf_dev_setlinecap(1);
+ } else {
+ pdf_dev_setlinecap(0);
+ }
+ pdf_doc_add_page_content(" 0 G", 4);
+
+ return 0;
+}
+
+static int
+set_fillstyle (double g, double a, int f_ais)
+{
+ pdf_obj *dict;
+ char resname[32];
+ char buf[32];
+ int alp, len = 0;
+
+ if (a > 0.0) {
+ alp = round(100.0 * a);
+ sprintf(resname, "_Tps_a%03d_", alp);
+ if (!check_resourcestatus("ExtGState", resname)) {
+ dict = create_xgstate(ROUND(0.01 * alp, 0.01), f_ais);
+ pdf_doc_add_page_resource("ExtGState",
+ resname, pdf_ref_obj(dict));
+ pdf_release_obj(dict);
+ }
+ len += sprintf(buf + len, " /%s gs", resname);
+ }
+ len += sprintf(buf + len, " %.2f g", g);
+
+ pdf_doc_add_page_content(buf, len);
+
+ return 0;
+}
+
+
+static void
+showpath (int f_vp, int f_fs) /* visible_path, fill_shape */
+{
+ if (f_vp) {
+ if (f_fs)
+ pdf_dev_flushpath('b', PDF_FILL_RULE_NONZERO);
+ else {
+ pdf_dev_flushpath('S', PDF_FILL_RULE_NONZERO);
+ }
+ } else {
+ /*
+ * Acrobat claims 'Q' as illegal operation when there are unfinished
+ * path (a path without path-painting operator applied)?
+ */
+ if (f_fs)
+ pdf_dev_flushpath('f', PDF_FILL_RULE_NONZERO);
+ else {
+ pdf_dev_newpath();
+ }
+ }
+}
+
+#define CLOSED_PATH(s) (\
+ (s)->points[0].x == (s)->points[(s)->num_points-1].x && \
+ (s)->points[0].y == (s)->points[(s)->num_points-1].y \
+)
+
+static int
+tpic__polyline (struct spc_tpic_ *tp,
+ const pdf_coord *c,
+ int f_vp,
+ double da)
+{
+ pdf_tmatrix M;
+ double pn = tp->pen_size;
+ int f_fs = tp->fill_shape;
+ int f_ais = 0;
+ double g = 0.5;
+ double a = 0.0;
+ int i, error = 0;
+
+ /* Shading is applied only to closed path. */
+ f_fs = CLOSED_PATH(tp) ? f_fs : 0;
+ f_vp = (pn > 0.0) ? f_vp : 0;
+ f_ais = (tp->mode.fill == TPIC_MODE__FILL_SHAPE) ? 1 : 0;
+ switch (tp->mode.fill) {
+ case TPIC_MODE__FILL_SOLID:
+ g = 1.0 - tp->fill_color;
+ a = 0.0;
+ break;
+ case TPIC_MODE__FILL_SHAPE:
+ case TPIC_MODE__FILL_OPACITY:
+ if (tp->fill_color > 0.0) {
+ a = tp->fill_color;
+ g = 0.0;
+ } else {
+ a = 0.0;
+ g = 1.0;
+ }
+ break;
+ }
+
+ if (f_vp || f_fs) {
+ pdf_dev_gsave();
+
+ pdf_setmatrix (&M, 1.0, 0.0, 0.0, -1.0, c->x, c->y);
+ pdf_dev_concat(&M);
+
+ if (f_vp)
+ set_linestyle(pn, da);
+ if (f_fs)
+ set_fillstyle(g, a, f_ais);
+
+ pdf_dev_moveto(tp->points[0].x, tp->points[0].y);
+ for (i = 0; i < tp->num_points; i++)
+ pdf_dev_lineto(tp->points[i].x, tp->points[i].y);
+
+ showpath(f_vp, f_fs);
+
+ pdf_dev_grestore();
+ }
+
+ tpic__clear(tp);
+
+ return error;
+}
+
+/*
+ * Accroding to
+ * "Tpic: Pic for TEX", Tim Morgan, Original by Brian Kernighan, p.20:
+ *
+ * A spline is a smooth curve guided by a set of straight lines just
+ * like the line above. It begins at the same place, ends at the same
+ * place, and in between is tangent to the mid-point of each guiding
+ * line. The syntax for a spline is identical to a (path) line except
+ * for using spline instead of line.
+ *
+ * Spline is not a curve drawn by spline-fitting points p0, p1, ..., pn,
+ * defined by tpic special "pa" command. Instead, a path defined by set
+ * of points p0, p1, ... is guiding line mentioned above.
+ *
+ * Dvipsk draws them as a straight line from p0 to q1 = (p0 + p1)/2,
+ * followed by a quadratic B-spline curve with starting point q1, (off-
+ * curve) control point p1, end point q2 = (p1 + p2)/2, ..., and a
+ * straight line from qn to pn.
+ */
+
+static int
+tpic__spline (struct spc_tpic_ *tp,
+ const pdf_coord *c,
+ int f_vp,
+ double da)
+{
+ double v[6];
+ pdf_tmatrix M;
+ double pn = tp->pen_size;
+ int f_fs = tp->fill_shape;
+ int f_ais = 0;
+ double g = 0.5;
+ double a = 0.0;
+ int i, error = 0;
+
+ f_fs = CLOSED_PATH(tp) ? f_fs : 0;
+ f_vp = (pn > 0.0) ? f_vp : 0;
+ f_ais = (tp->mode.fill == TPIC_MODE__FILL_SHAPE) ? 1 : 0;
+ switch (tp->mode.fill) {
+ case TPIC_MODE__FILL_SOLID:
+ g = 1.0 - tp->fill_color;
+ a = 0.0;
+ break;
+ case TPIC_MODE__FILL_SHAPE:
+ case TPIC_MODE__FILL_OPACITY:
+ if (tp->fill_color > 0.0) {
+ a = tp->fill_color;
+ g = 0.0;
+ } else {
+ a = 0.0;
+ g = 1.0;
+ }
+ break;
+ }
+
+ if ( f_vp || f_fs ) {
+ pdf_dev_gsave();
+
+ pdf_setmatrix (&M, 1.0, 0.0, 0.0, -1.0, c->x, c->y);
+ pdf_dev_concat(&M);
+
+ if (f_vp)
+ set_linestyle(pn, da);
+ if (f_fs)
+ set_fillstyle(g, a, f_ais);
+
+ pdf_dev_moveto(tp->points[0].x, tp->points[0].y);
+
+ v[0] = 0.5 * (tp->points[0].x + tp->points[1].x);
+ v[1] = 0.5 * (tp->points[0].y + tp->points[1].y);
+ pdf_dev_lineto(v[0], v[1]);
+ for (i = 1; i < tp->num_points - 1; i++) {
+ /* B-spline control points */
+ v[0] = 0.5 * (tp->points[i-1].x + tp->points[i].x);
+ v[1] = 0.5 * (tp->points[i-1].y + tp->points[i].y);
+ v[2] = tp->points[i].x;
+ v[3] = tp->points[i].y;
+ v[4] = 0.5 * (tp->points[i].x + tp->points[i+1].x);
+ v[5] = 0.5 * (tp->points[i].y + tp->points[i+1].y);
+ pdf_dev_bspline(v[0], v[1], v[2], v[3], v[4], v[5]);
+ }
+ pdf_dev_lineto(tp->points[i].x, tp->points[i].y);
+
+ showpath(f_vp, f_fs);
+
+ pdf_dev_grestore();
+ }
+ tpic__clear(tp);
+
+ return error;
+}
+
+static int
+tpic__arc (struct spc_tpic_ *tp,
+ const pdf_coord *c,
+ int f_vp,
+ double da,
+ double *v /* 6 numbers */ )
+{
+ pdf_tmatrix M;
+ double pn = tp->pen_size;
+ int f_fs = tp->fill_shape;
+ int f_ais = 0;
+ double g = 0.5;
+ double a = 0.0;
+
+ f_fs = (round(fabs(v[4] - v[5]) + 0.5) >= 360) ? f_fs : 0;
+ f_vp = (pn > 0.0) ? f_vp : 0;
+ f_ais = (tp->mode.fill == TPIC_MODE__FILL_SHAPE) ? 1 : 0;
+ switch (tp->mode.fill) {
+ case TPIC_MODE__FILL_SOLID:
+ g = 1.0 - tp->fill_color;
+ a = 0.0;
+ break;
+ case TPIC_MODE__FILL_SHAPE:
+ case TPIC_MODE__FILL_OPACITY:
+ if (tp->fill_color > 0.0) {
+ a = tp->fill_color;
+ g = 0.0;
+ } else {
+ a = 0.0;
+ g = 1.0;
+ }
+ break;
+ }
+
+ if ( f_vp || f_fs ) {
+ pdf_dev_gsave();
+
+ pdf_setmatrix (&M, 1.0, 0.0, 0.0, -1.0, c->x, c->y);
+ pdf_dev_concat(&M);
+
+ if (f_vp)
+ set_linestyle(pn, da);
+ if (f_fs)
+ set_fillstyle(g, a, f_ais);
+
+ pdf_dev_arcx(v[0], v[1], v[2], v[3], v[4], v[5], +1, 0.0);
+
+ showpath(f_vp, f_fs);
+
+ pdf_dev_grestore();
+ }
+ tpic__clear(tp);
+
+ return 0;
+}
+
+#if 1
+static int
+spc_currentpoint (struct spc_env *spe, long *pg, pdf_coord *cp)
+{
+ *pg = 0;
+ cp->x = spe->x_user;
+ cp->y = spe->y_user;
+ return 0;
+}
+#endif
+
+static int
+spc_handler_tpic_pn (struct spc_env *spe,
+ struct spc_arg *ap ) /* , void *dp) */
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+ char *q;
+
+ ASSERT(spe && ap && tp);
+
+ skip_blank(&ap->curptr, ap->endptr);
+ q = parse_float_decimal(&ap->curptr, ap->endptr);
+ if (!q) {
+ spc_warn(spe, "Invalid pen size specified?");
+ return -1;
+ }
+ tp->pen_size = atof(q) * MI2DEV;
+ RELEASE(q);
+
+ return 0;
+}
+
+static int
+spc_handler_tpic_pa (struct spc_env *spe,
+ struct spc_arg *ap ) /* , void *dp) */
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+ char *q;
+ int i;
+ double v[2];
+
+ ASSERT(spe && ap && tp);
+
+ skip_blank(&ap->curptr, ap->endptr);
+ for (i = 0;
+ i < 2 && ap->curptr < ap->endptr; i++) {
+ q = parse_float_decimal(&ap->curptr, ap->endptr);
+ if (!q) {
+ spc_warn(spe, "Missing numbers for TPIC \"pa\" command.");
+ return -1;
+ }
+ v[i] = atof(q);
+ RELEASE(q);
+ skip_blank(&ap->curptr, ap->endptr);
+ }
+ if (i != 2) {
+ spc_warn(spe, "Invalid arg for TPIC \"pa\" command.");
+ return -1;
+ }
+
+ if (tp->num_points >= tp->max_points) {
+ tp->max_points += 256;
+ tp->points = RENEW(tp->points, tp->max_points, pdf_coord);
+ }
+ tp->points[tp->num_points].x = v[0] * MI2DEV;
+ tp->points[tp->num_points].y = v[1] * MI2DEV;
+ tp->num_points += 1;
+
+ return 0;
+}
+
+static int
+spc_handler_tpic_fp (struct spc_env *spe,
+ struct spc_arg *ap ) /* , void *dp) */
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+ pdf_coord cp;
+ long pg;
+
+ ASSERT(spe && ap && tp);
+
+ if (tp->num_points <= 1) {
+ spc_warn(spe, "Too few points (< 2) for polyline path.");
+ return -1;
+ }
+
+ spc_currentpoint(spe, &pg, &cp);
+
+ return tpic__polyline(tp, &cp, 1, 0.0);
+}
+
+static int
+spc_handler_tpic_ip (struct spc_env *spe,
+ struct spc_arg *ap ) /* , void *dp) */
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+ pdf_coord cp;
+ long pg;
+
+ ASSERT(spe && ap && tp);
+
+ if (tp->num_points <= 1) {
+ spc_warn(spe, "Too few points (< 2) for polyline path.");
+ return -1;
+ }
+
+ spc_currentpoint(spe, &pg, &cp);
+
+ return tpic__polyline(tp, &cp, 0, 0.0);
+}
+
+static int
+spc_handler_tpic_da (struct spc_env *spe,
+ struct spc_arg *ap ) /* , void *dp) */
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+ char *q;
+ double da = 0.0;
+ pdf_coord cp;
+ long pg;
+
+ ASSERT(spe && ap && tp);
+
+ skip_blank(&ap->curptr, ap->endptr);
+ q = parse_float_decimal(&ap->curptr, ap->endptr);
+ if (q) {
+ da = atof(q);
+ RELEASE(q);
+ }
+ if (tp->num_points <= 1) {
+ spc_warn(spe, "Too few points (< 2) for polyline path.");
+ return -1;
+ }
+
+ spc_currentpoint(spe, &pg, &cp);
+
+ return tpic__polyline(tp, &cp, 1, da);
+}
+
+static int
+spc_handler_tpic_dt (struct spc_env *spe,
+ struct spc_arg *ap ) /* , void *dp) */
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+ char *q;
+ double da = 0.0;
+ pdf_coord cp;
+ long pg;
+
+ ASSERT(spe && ap && tp);
+
+ skip_blank(&ap->curptr, ap->endptr);
+ q = parse_float_decimal(&ap->curptr, ap->endptr);
+ if (q) {
+ da = -atof(q);
+ RELEASE(q);
+ }
+ if (tp->num_points <= 1) {
+ spc_warn(spe, "Too few points (< 2) for polyline path.");
+ return -1;
+ }
+
+ spc_currentpoint(spe, &pg, &cp);
+
+ return tpic__polyline(tp, &cp, 1, da);
+}
+
+static int
+spc_handler_tpic_sp (struct spc_env *spe,
+ struct spc_arg *ap ) /* , void *dp) */
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+ char *q;
+ double da = 0.0;
+ pdf_coord cp;
+ long pg;
+
+ ASSERT(spe && ap && tp);
+
+ skip_blank(&ap->curptr, ap->endptr);
+ q = parse_float_decimal(&ap->curptr, ap->endptr);
+ if (q) {
+ da = atof(q);
+ RELEASE(q);
+ }
+ if (tp->num_points <= 2) {
+ spc_warn(spe, "Too few points (< 3) for spline path.");
+ return -1;
+ }
+
+ spc_currentpoint(spe, &pg, &cp);
+
+ return tpic__spline(tp, &cp, 1, da);
+}
+
+static int
+spc_handler_tpic_ar (struct spc_env *spe,
+ struct spc_arg *ap ) /* , void *dp) */
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+ double v[6];
+ pdf_coord cp;
+ long pg;
+ char *q;
+ int i;
+
+ ASSERT(spe && ap && tp);
+
+ skip_blank(&ap->curptr, ap->endptr);
+ for (i = 0;
+ i < 6 && ap->curptr < ap->endptr; i++) {
+ q = parse_float_decimal(&ap->curptr, ap->endptr);
+ if (!q) {
+ spc_warn(spe, "Invalid args. in TPIC \"ar\" command.");
+ return -1;
+ }
+ v[i] = atof(q);
+ RELEASE(q);
+ skip_blank(&ap->curptr, ap->endptr);
+ }
+ if (i != 6) {
+ spc_warn(spe, "Invalid arg for TPIC \"ar\" command.");
+ return -1;
+ }
+
+ v[0] *= MI2DEV; v[1] *= MI2DEV;
+ v[2] *= MI2DEV; v[3] *= MI2DEV;
+ v[4] *= 180.0 / M_PI;
+ v[5] *= 180.0 / M_PI;
+
+ spc_currentpoint(spe, &pg, &cp);
+
+ return tpic__arc(tp, &cp, 1, 0.0, v);
+}
+
+static int
+spc_handler_tpic_ia (struct spc_env *spe,
+ struct spc_arg *ap ) /* , void *dp) */
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+ double v[6];
+ pdf_coord cp;
+ long pg;
+ char *q;
+ int i;
+
+ ASSERT(spe && ap && tp);
+
+ skip_blank(&ap->curptr, ap->endptr);
+ for (i = 0;
+ i < 6 && ap->curptr < ap->endptr; i++) {
+ q = parse_float_decimal(&ap->curptr, ap->endptr);
+ if (!q) {
+ spc_warn(spe, "Invalid args. in TPIC \"ia\" command.");
+ return -1;
+ }
+ v[i] = atof(q);
+ RELEASE(q);
+ skip_blank(&ap->curptr, ap->endptr);
+ }
+ if (i != 6) {
+ spc_warn(spe, "Invalid arg for TPIC \"ia\" command.");
+ return -1;
+ }
+
+ v[0] *= MI2DEV; v[1] *= MI2DEV;
+ v[2] *= MI2DEV; v[3] *= MI2DEV;
+ v[4] *= 180.0 / M_PI;
+ v[5] *= 180.0 / M_PI;
+
+ spc_currentpoint(spe, &pg, &cp);
+
+ return tpic__arc(tp, &cp, 0, 0.0, v);
+}
+
+static int
+spc_handler_tpic_sh (struct spc_env *spe,
+ struct spc_arg *ap ) /* , void *dp) */
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+ char *q;
+
+ ASSERT(spe && ap && tp);
+
+ tp->fill_shape = 1;
+ tp->fill_color = 0.5;
+
+ skip_blank(&ap->curptr, ap->endptr);
+ q = parse_float_decimal(&ap->curptr, ap->endptr);
+ if (q) {
+ tp->fill_color = atof(q);
+ RELEASE(q);
+ }
+
+ return 0;
+}
+
+static int
+spc_handler_tpic_wh (struct spc_env *spe,
+ struct spc_arg *ap ) /* , void *dp) */
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+
+ ASSERT(spe && ap && tp);
+
+ tp->fill_shape = 1;
+ tp->fill_color = 0.0;
+
+ return 0;
+}
+
+static int
+spc_handler_tpic_bk (struct spc_env *spe,
+ struct spc_arg *ap ) /* , void *dp) */
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+
+ ASSERT(spe && ap && tp);
+
+ tp->fill_shape = 1;
+ tp->fill_color = 1.0;
+
+ return 0;
+}
+
+static int
+spc_handler_tpic_tx (struct spc_env *spe,
+ struct spc_arg *ap ) /* , void *dp) */
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+
+ ASSERT(spe && ap && tp);
+
+ spc_warn(spe, "TPIC command \"tx\" not supported.");
+
+ return -1;
+}
+
+
+static int
+spc_handler_tpic__init (struct spc_env *spe,
+ struct spc_arg *ap, void *dp)
+{
+ struct spc_tpic_ *tp = dp;
+
+#if 0
+ tp->mode.fill = TPIC_MODE__FILL_SOLID;
+#endif
+ tp->pen_size = 1.0;
+ tp->fill_shape = 0;
+ tp->fill_color = 0.0;
+
+ tp->points = NULL;
+ tp->num_points = 0;
+ tp->max_points = 0;
+
+ if (tp->mode.fill != TPIC_MODE__FILL_SOLID && pdf_get_version() < 4) {
+ spc_warn(spe, "Tpic shading support requires PDF version 1.4.");
+ tp->mode.fill = TPIC_MODE__FILL_SOLID;
+ }
+
+ return 0;
+}
+
+static int
+spc_handler_tpic__bophook (struct spc_env *spe,
+ struct spc_arg *ap, void *dp)
+{
+ struct spc_tpic_ *tp = dp;
+
+ ASSERT(tp);
+
+ tpic__clear(tp);
+
+ return 0;
+}
+
+static int
+spc_handler_tpic__eophook (struct spc_env *spe,
+ struct spc_arg *ap, void *dp)
+{
+ struct spc_tpic_ *tp = dp;
+
+ ASSERT(tp);
+
+ if (tp->num_points > 0)
+ spc_warn(spe, "Unflushed tpic path at end of the page.");
+ tpic__clear(tp);
+
+ return 0;
+}
+
+static int
+spc_handler_tpic__clean (struct spc_env *spe,
+ struct spc_arg *ap, void *dp)
+{
+ struct spc_tpic_ *tp = dp;
+
+ ASSERT(tp);
+
+ if (tp->num_points > 0)
+ spc_warn(spe, "Unflushed tpic path at end of the document.");
+
+ tpic__clear(tp);
+#if 0
+ RELEASE(tp);
+#endif
+
+ return 0;
+}
+
+void
+tpic_set_fill_mode (int mode)
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+ tp->mode.fill = mode;
+}
+
+
+int
+spc_tpic_at_begin_page (void)
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+ return spc_handler_tpic__bophook(NULL, NULL, tp);
+}
+
+int
+spc_tpic_at_end_page (void)
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+ return spc_handler_tpic__eophook(NULL, NULL, tp);
+}
+
+
+int
+spc_tpic_at_begin_document (void)
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+ return spc_handler_tpic__init(NULL, NULL, tp);
+}
+
+int
+spc_tpic_at_end_document (void)
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+ return spc_handler_tpic__clean(NULL, NULL, tp);
+}
+
+
+#if DEBUG
+#include "pdfparse.h" /* parse_val_ident :( */
+
+static pdf_obj *
+spc_parse_kvpairs (struct spc_env *spe, struct spc_arg *ap)
+{
+ pdf_obj *dict;
+ char *kp, *vp;
+ int error = 0;
+
+ dict = pdf_new_dict();
+
+ skip_blank(&ap->curptr, ap->endptr);
+ while (!error && ap->curptr < ap->endptr) {
+ kp = parse_val_ident(&ap->curptr, ap->endptr);
+ if (!kp)
+ break;
+ skip_blank(&ap->curptr, ap->endptr);
+ if (ap->curptr < ap->endptr &&
+ ap->curptr[0] == '=') {
+ ap->curptr++;
+ skip_blank(&ap->curptr, ap->endptr);
+ if (ap->curptr == ap->endptr) {
+ RELEASE(kp);
+ error = -1;
+ break;
+ }
+ vp = parse_c_string(&ap->curptr, ap->endptr);
+ if (!vp)
+ error = -1;
+ else {
+ pdf_add_dict(dict,
+ pdf_new_name(kp),
+ pdf_new_string(vp, strlen(vp) + 1)); /* NULL terminate */
+ RELEASE(vp);
+ }
+ } else {
+ /* Treated as 'flag' */
+ pdf_add_dict(dict,
+ pdf_new_name(kp),
+ pdf_new_boolean(1));
+ }
+ RELEASE(kp);
+ if (!error)
+ skip_blank(&ap->curptr, ap->endptr);
+ }
+
+ if (error) {
+ pdf_release_obj(dict);
+ dict = NULL;
+ }
+
+ return dict;
+}
+
+static int
+tpic_filter_getopts (pdf_obj *kp, pdf_obj *vp, void *dp)
+{
+ struct spc_tpic_ *tp = dp;
+ char *k, *v;
+ int error = 0;
+
+ ASSERT( kp && vp && tp );
+
+ k = pdf_name_value(kp);
+ if (!strcmp(k, "fill-mode")) {
+ if (pdf_obj_typeof(vp) != PDF_STRING) {
+ WARN("Invalid value for TPIC option fill-mode...");
+ error = -1;
+ } else {
+ v = pdf_string_value(vp);
+ if (!strcmp(v, "shape"))
+ tp->mode.fill = TPIC_MODE__FILL_SHAPE;
+ else if (!strcmp(v, "opacity"))
+ tp->mode.fill = TPIC_MODE__FILL_OPACITY;
+ else if (!strcmp(v, "solid"))
+ tp->mode.fill = TPIC_MODE__FILL_SOLID;
+ else {
+ WARN("Invalid value for TPIC option fill-mode: %s", v);
+ error = -1;
+ }
+ }
+ } else {
+ WARN("Unrecognized option for TPIC special handler: %s", k);
+ error = -1;
+ }
+
+ return error;
+}
+
+static int
+spc_handler_tpic__setopts (struct spc_env *spe,
+ struct spc_arg *ap ) /* , void *dp) */
+{
+ struct spc_tpic_ *tp = &_tpic_state;
+ pdf_obj *dict;
+ int error = 0;
+
+ dict = spc_parse_kvpairs(spe, ap);
+ if (!dict)
+ return -1;
+ error = pdf_foreach_dict(dict, tpic_filter_getopts, tp);
+ if (!error) {
+ if (tp->mode.fill != TPIC_MODE__FILL_SOLID &&
+ pdf_get_version() < 4) {
+ spc_warn(spe, "Transparent fill mode requires PDF version 1.4.");
+ tp->mode.fill = TPIC_MODE__FILL_SOLID;
+ }
+ }
+
+ return error;
+}
+#endif /* DEBUG */
+
+
+static struct spc_handler tpic_handlers[] = {
+ {"pn", spc_handler_tpic_pn},
+ {"pa", spc_handler_tpic_pa},
+ {"fp", spc_handler_tpic_fp},
+ {"ip", spc_handler_tpic_ip},
+ {"da", spc_handler_tpic_da},
+ {"dt", spc_handler_tpic_dt},
+ {"sp", spc_handler_tpic_sp},
+ {"ar", spc_handler_tpic_ar},
+ {"ia", spc_handler_tpic_ia},
+ {"sh", spc_handler_tpic_sh},
+ {"wh", spc_handler_tpic_wh},
+ {"bk", spc_handler_tpic_bk},
+ {"tx", spc_handler_tpic_tx}
+};
+
+int
+spc_tpic_check_special (const char *buf, long len)
+{
+ int istpic = 0;
+ char *q;
+ const char *p, *endptr;
+ int i, hasnsp = 0;
+
+ p = buf;
+ endptr = p + len;
+
+ skip_blank(&p, endptr);
+#if ENABLE_SPC_NAMESPACE
+ if (p + strlen("tpic:") < endptr &&
+ !memcmp(p, "tpic:", strlen("tpic:")))
+ {
+ p += strlen("tpic:");
+ hasnsp = 1;
+ }
+#endif
+ q = parse_c_ident(&p, endptr);
+
+ if (!q)
+ istpic = 0;
+ else if (q && hasnsp && !strcmp(q, "__setopt__")) {
+#if DEBUG
+ istpic = 1;
+#endif
+ RELEASE(q);
+ } else {
+ for (i = 0;
+ i < sizeof(tpic_handlers)/sizeof(struct spc_handler); i++) {
+ if (!strcmp(q, tpic_handlers[i].key)) {
+ istpic = 1;
+ break;
+ }
+ }
+ RELEASE(q);
+ }
+
+ return istpic;
+}
+
+
+int
+spc_tpic_setup_handler (struct spc_handler *sph,
+ struct spc_env *spe, struct spc_arg *ap)
+{
+ char *q;
+ int i, hasnsp = 0, error = -1;
+
+ ASSERT(sph && spe && ap);
+
+ skip_blank(&ap->curptr, ap->endptr);
+#if ENABLE_SPC_NAMESPACE
+ if (ap->curptr + strlen("tpic:") < ap->endptr &&
+ !memcmp(ap->curptr, "tpic:", strlen("tpic:")))
+ {
+ ap->curptr += strlen("tpic:");
+ hasnsp = 1;
+ }
+#endif
+ q = parse_c_ident(&ap->curptr, ap->endptr);
+
+ if (!q)
+ error = -1;
+ else if (q && hasnsp && !strcmp(q, "__setopt__")) {
+#if DEBUG
+ ap->command = "__setopt__";
+ sph->key = "tpic:";
+ sph->exec = spc_handler_tpic__setopts;
+ skip_blank(&ap->curptr, ap->endptr);
+ error = 0;
+#endif
+ RELEASE(q);
+ } else {
+ for (i = 0;
+ i < sizeof(tpic_handlers)/sizeof(struct spc_handler); i++) {
+ if (!strcmp(q, tpic_handlers[i].key)) {
+ ap->command = tpic_handlers[i].key;
+ sph->key = "tpic:";
+ sph->exec = tpic_handlers[i].exec;
+ skip_blank(&ap->curptr, ap->endptr);
+ error = 0;
+ break;
+ }
+ }
+ RELEASE(q);
+ }
+
+ return error;
+}
+
+
+#if 0
+int
+spc_load_tpic_special (struct spc_env *spe, pdf_obj *lopts)
+{
+ struct spc_def *spd;
+ struct spc_tpic_ *sd;
+
+ sd = NEW(1, struct spc_tpic_);
+
+ spd = NEW(1, struct spc_def);
+ spc_init_def(spd);
+
+ spc_def_init (spd, &spc_handler_tpic__init);
+ spc_def_setopts(spd, &spc_handler_tpic__setopts);
+ spc_def_bophook(spd, &spc_handler_tpic__bophook);
+ spc_def_eophook(spd, &spc_handler_tpic__eophook);
+ spc_def_clean (spd, &spc_handler_tpic__clean);
+
+ spc_def_func(spd, "pn", &spc_handler_tpic_pn);
+ spc_def_func(spd, "pa", &spc_handler_tpic_pa);
+ spc_def_func(spd, "fp", &spc_handler_tpic_fp);
+ spc_def_func(spd, "ip", &spc_handler_tpic_ip);
+ spc_def_func(spd, "da", &spc_handler_tpic_da);
+ spc_def_func(spd, "dt", &spc_handler_tpic_dt);
+ spc_def_func(spd, "sp", &spc_handler_tpic_sp);
+ spc_def_func(spd, "ar", &spc_handler_tpic_ar);
+ spc_def_func(spd, "ia", &spc_handler_tpic_ia);
+ spc_def_func(spd, "sh", &spc_handler_tpic_sh);
+ spc_def_func(spd, "wh", &spc_handler_tpic_wh);
+ spc_def_func(spd, "bk", &spc_handler_tpic_bk);
+ spc_def_func(spd, "tx", &spc_handler_tpic_tx);
+
+ spc_add_special(spe, "tpic", spd, sd);
+
+ return 0;
+}
+#endif /* 0 */
+
diff --git a/Build/source/texk/dvipdf-x/xsrc/spc_util.c b/Build/source/texk/dvipdf-x/xsrc/spc_util.c
new file mode 100644
index 00000000000..7ea4f5aa929
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/spc_util.c
@@ -0,0 +1,796 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2007-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+#include "dpxutil.h"
+
+#include "pdfdev.h"
+#include "pdfparse.h"
+#include "pdfcolor.h"
+#include "pdfdraw.h"
+
+#include "specials.h"
+
+#include "spc_util.h"
+
+
+#ifndef ISBLANK
+#define ISBLANK(c) ((c) == ' ' || (c) == '\t')
+#endif
+static void
+skip_blank (const char **pp, const char *endptr)
+{
+ const char *p = *pp;
+ for ( ; p < endptr && ISBLANK(*p); p++);
+ *pp = p;
+}
+
+
+/* From pdfcolor.c */
+static int pdf_color_namedcolor (pdf_color *color, const char *colorname);
+
+int
+spc_util_read_numbers (double *values, int num_values,
+ struct spc_env *spe, struct spc_arg *args)
+{
+ int count;
+ char *q;
+
+ skip_blank(&args->curptr, args->endptr);
+ for (count = 0;
+ count < num_values &&
+ args->curptr < args->endptr; ) {
+ q = parse_float_decimal(&args->curptr, args->endptr);
+ if (!q)
+ break;
+ else {
+ values[count] = atof(q);
+ RELEASE(q);
+ skip_blank(&args->curptr, args->endptr);
+ count++;
+ }
+ }
+
+ return count;
+}
+
+static void
+rgb_color_from_hsv (pdf_color *color, double h, double s, double v)
+{
+ double r, g, b;
+ ASSERT( color );
+ r = g = b = v;
+ if (s != 0.0) {
+ double h6, f, v1, v2, v3;
+ int i;
+ h6 = h * 6; /* 360 / 60 */
+ i = (int) h6;
+ f = h6 - i;
+ v1 = v * (1 - s);
+ v2 = v * (1 - s * f);
+ v3 = v * (1 - s * (1 - f));
+ switch (i) {
+ case 0: r = v ; g = v3; b = v1; break;
+ case 1: r = v2; g = v ; b = v1; break;
+ case 2: r = v1; g = v ; b = v3; break;
+ case 3: r = v1; g = v2; b = v ; break;
+ case 4: r = v3; g = v1; b = v ; break;
+ case 5: r = v ; g = v1; b = v2; break;
+ case 6: r = v ; g = v1; b = v2; break;
+ }
+ }
+ pdf_color_rgbcolor(color, r, g, b);
+}
+
+static int
+spc_read_color_color (struct spc_env *spe, pdf_color *colorspec, struct spc_arg *ap)
+{
+ char *q;
+ double cv[4];
+ int nc;
+ int error = 0;
+
+ q = parse_c_ident(&ap->curptr, ap->endptr);
+ if (!q) {
+ spc_warn(spe, "No valid color specified?");
+ return -1;
+ }
+ skip_blank(&ap->curptr, ap->endptr);
+
+ if (!strcmp(q, "rgb")) { /* Handle rgb color */
+ nc = spc_util_read_numbers(cv, 3, spe, ap);
+ if (nc != 3) {
+ spc_warn(spe, "Invalid value for RGB color specification.");
+ error = -1;
+ } else {
+ pdf_color_rgbcolor(colorspec, cv[0], cv[1], cv[2]);
+ }
+ } else if (!strcmp(q, "cmyk")) { /* Handle cmyk color */
+ nc = spc_util_read_numbers(cv, 4, spe, ap);
+ if (nc != 4) {
+ spc_warn(spe, "Invalid value for CMYK color specification.");
+ error = -1;
+ } else {
+ pdf_color_cmykcolor(colorspec, cv[0], cv[1], cv[2], cv[3]);
+ }
+ } else if (!strcmp(q, "gray")) { /* Handle gray */
+ nc = spc_util_read_numbers(cv, 1, spe, ap);
+ if (nc != 1) {
+ spc_warn(spe, "Invalid value for gray color specification.");
+ error = -1;
+ } else {
+ pdf_color_graycolor(colorspec, cv[0]);
+ }
+ } else if (!strcmp(q, "hsb")) {
+ nc = spc_util_read_numbers(cv, 3, spe, ap);
+ if (nc != 3) {
+ spc_warn(spe, "Invalid value for HSB color specification.");
+ error = -1;
+ } else {
+ rgb_color_from_hsv(colorspec, cv[0], cv[1], cv[2]);
+ spc_warn(spe, "HSB color converted to RGB: hsb: <%g, %g, %g> ==> rgb: <%g, %g, %g>",
+ cv[0], cv[1], cv[2],
+ colorspec->values[0], colorspec->values[1], colorspec->values[2]);
+ }
+ } else { /* Must be a "named" color */
+ error = pdf_color_namedcolor(colorspec, q);
+ if (error)
+ spc_warn(spe, "Unrecognized color name: %s", q);
+ }
+ RELEASE(q);
+
+ return error;
+}
+
+/* Argumaent for this is PDF_Number or PDF_Array.
+ * But we ignore that since we don't want to add
+ * dependency to pdfxxx and @foo can not be
+ * allowed for color specification. "pdf" here
+ * means pdf: special syntax.
+ */
+static int
+spc_read_color_pdf (struct spc_env *spe, pdf_color *colorspec, struct spc_arg *ap)
+{
+ double cv[4]; /* at most four */
+ int nc, isarry = 0;
+ int error = 0;
+ char *q;
+
+ skip_blank(&ap->curptr, ap->endptr);
+
+ if (ap->curptr[0] == '[') {
+ ap->curptr++; skip_blank(&ap->curptr, ap->endptr);
+ isarry = 1;
+ }
+
+ nc = spc_util_read_numbers(cv, 4, spe, ap);
+ switch (nc) {
+ case 1:
+ pdf_color_graycolor(colorspec, cv[0]);
+ break;
+ case 3:
+ pdf_color_rgbcolor (colorspec, cv[0], cv[1], cv[2]);
+ break;
+ case 4:
+ pdf_color_cmykcolor(colorspec, cv[0], cv[1], cv[2], cv[3]);
+ break;
+ default:
+ /* Try to read the color names defined in dvipsname.def */
+ q = parse_c_ident(&ap->curptr, ap->endptr);
+ if (!q) {
+ spc_warn(spe, "No valid color specified?");
+ return -1;
+ }
+ error = pdf_color_namedcolor(colorspec, q);
+ if (error)
+ spc_warn(spe, "Unrecognized color name: %s", q);
+ RELEASE(q);
+ break;
+ }
+
+ if (!error && isarry) {
+ skip_blank(&ap->curptr, ap->endptr);
+ if (ap->curptr >= ap->endptr || ap->curptr[0] != ']') {
+ spc_warn(spe, "Unbalanced '[' and ']' in color specification.");
+ error = -1;
+ } else {
+ ap->curptr++;
+ }
+ }
+
+ return error;
+}
+
+
+/* This is for reading *single* color specification. */
+int
+spc_util_read_colorspec (struct spc_env *spe, pdf_color *colorspec, struct spc_arg *ap, int syntax)
+{
+ int error = 0;
+
+ ASSERT(colorspec && spe && ap);
+
+ skip_blank(&ap->curptr, ap->endptr);
+ if (ap->curptr >= ap->endptr) {
+ return -1;
+ }
+
+ if (syntax)
+ error = spc_read_color_color(spe, colorspec, ap);
+ else
+ error = spc_read_color_pdf(spe, colorspec, ap);
+
+ skip_blank(&ap->curptr, ap->endptr);
+
+ return error;
+}
+
+
+/* This need to allow 'true' prefix for unit and
+ * length value must be divided by current magnification.
+ */
+int
+spc_util_read_length (struct spc_env *spe, double *vp /* ret. */, struct spc_arg *ap)
+{
+ char *q;
+ double v, u = 1.0;
+ const char *ukeys[] = {
+#define K_UNIT__PT 0
+#define K_UNIT__IN 1
+#define K_UNIT__CM 2
+#define K_UNIT__MM 3
+#define K_UNIT__BP 4
+ "pt", "in", "cm", "mm", "bp", NULL
+ };
+ int k, error = 0;
+
+ q = parse_float_decimal(&ap->curptr, ap->endptr);
+ if (!q)
+ return -1;
+
+ v = atof(q);
+ RELEASE(q);
+
+ skip_white(&ap->curptr, ap->endptr);
+ q = parse_c_ident(&ap->curptr, ap->endptr);
+ if (q) {
+ char *qq = q;
+ if (strlen(q) >= strlen("true") &&
+ !memcmp(q, "true", strlen("true"))) {
+ u /= spe->mag != 0.0 ? spe->mag : 1.0; /* inverse magnify */
+ q += strlen("true");
+ }
+ if (strlen(q) == 0) {
+ RELEASE(qq);
+ skip_white(&ap->curptr, ap->endptr);
+ qq = q = parse_c_ident(&ap->curptr, ap->endptr);
+ }
+ if (q) {
+ for (k = 0; ukeys[k] && strcmp(ukeys[k], q); k++);
+ switch (k) {
+ case K_UNIT__PT: u *= 72.0 / 72.27; break;
+ case K_UNIT__IN: u *= 72.0; break;
+ case K_UNIT__CM: u *= 72.0 / 2.54 ; break;
+ case K_UNIT__MM: u *= 72.0 / 25.4 ; break;
+ case K_UNIT__BP: u *= 1.0 ; break;
+ default:
+ spc_warn(spe, "Unknown unit of measure: %s", q);
+ error = -1;
+ break;
+ }
+ RELEASE(qq);
+ }
+ else {
+ spc_warn(spe, "Missing unit of measure after \"true\"");
+ error = -1;
+ }
+ }
+
+ *vp = v * u;
+ return error;
+}
+
+
+/*
+ * Compute a transformation matrix
+ * transformations are applied in the following
+ * order: scaling, rotate, displacement.
+ */
+static void
+make_transmatrix (pdf_tmatrix *M,
+ double xoffset, double yoffset,
+ double xscale, double yscale,
+ double rotate)
+{
+ double c, s;
+
+ c = cos(rotate);
+ s = sin(rotate);
+
+ M->a = xscale * c; M->b = xscale * s;
+ M->c = -yscale * s; M->d = yscale * c;
+ M->e = xoffset; M->f = yoffset;
+}
+
+static int
+spc_read_dimtrns_dvips (struct spc_env *spe, transform_info *t, struct spc_arg *ap)
+{
+ static const char *_dtkeys[] = {
+#define K_TRN__HOFFSET 0
+#define K_TRN__VOFFSET 1
+ "hoffset", "voffset",
+#define K_DIM__HSIZE 2
+#define K_DIM__VSIZE 3
+ "hsize", "vsize",
+#define K_TRN__HSCALE 4
+#define K_TRN__VSCALE 5
+ "hscale", "vscale",
+#define K_TRN__ANGLE 6
+ "angle",
+#define K__CLIP 7
+ "clip",
+#define K_DIM__LLX 8
+#define K_DIM__LLY 9
+#define K_DIM__URX 10
+#define K_DIM__URY 11
+ "llx", "lly", "urx", "ury",
+#define K_DIM__RWI 12
+#define K_DIM__RHI 13
+ "rwi", "rhi",
+ NULL
+ };
+ double xoffset, yoffset, xscale, yscale, rotate;
+ int error = 0;
+
+ xoffset = yoffset = rotate = 0.0; xscale = yscale = 1.0;
+
+ skip_blank(&ap->curptr, ap->endptr);
+ while (!error && ap->curptr < ap->endptr) {
+ char *kp, *vp;
+ int k;
+
+ kp = parse_c_ident(&ap->curptr, ap->endptr);
+ if (!kp)
+ break;
+
+ for (k = 0; _dtkeys[k] && strcmp(kp, _dtkeys[k]); k++);
+ if (!_dtkeys[k]) {
+ spc_warn(spe, "Unrecognized dimension/transformation key: %s", kp);
+ error = -1;
+ RELEASE(kp);
+ break;
+ }
+
+ skip_blank(&ap->curptr, ap->endptr);
+ if (k == K__CLIP) {
+ t->flags |= INFO_DO_CLIP;
+ RELEASE(kp);
+ continue; /* not key-value */
+ }
+
+ if (ap->curptr < ap->endptr && ap->curptr[0] == '=') {
+ ap->curptr++;
+ skip_blank(&ap->curptr, ap->endptr);
+ }
+
+ vp = NULL;
+ if (ap->curptr[0] == '\'' || ap->curptr[0] == '\"') {
+ char qchr = ap->curptr[0];
+ ap->curptr++;
+ skip_blank(&ap->curptr, ap->endptr);
+ vp = parse_float_decimal(&ap->curptr, ap->endptr);
+ skip_blank(&ap->curptr, ap->endptr);
+ if (vp && qchr != ap->curptr[0]) {
+ spc_warn(spe, "Syntax error in dimension/transformation specification.");
+ error = -1;
+ RELEASE(vp); vp = NULL;
+ }
+ ap->curptr++;
+ } else {
+ vp = parse_float_decimal(&ap->curptr, ap->endptr);
+ }
+ if (!error && !vp) {
+ spc_warn(spe, "Missing value for dimension/transformation: %s", kp);
+ error = -1;
+ }
+ RELEASE(kp);
+ if (!vp || error) {
+ break;
+ }
+
+ switch (k) {
+ case K_TRN__HOFFSET:
+ xoffset = atof(vp);
+ break;
+ case K_TRN__VOFFSET:
+ yoffset = atof(vp);
+ break;
+ case K_DIM__HSIZE:
+ t->width = atof(vp);
+ t->flags |= INFO_HAS_WIDTH;
+ break;
+ case K_DIM__VSIZE:
+ t->height = atof(vp);
+ t->flags |= INFO_HAS_HEIGHT;
+ break;
+ case K_TRN__HSCALE:
+ xscale = atof(vp) / 100.0;
+ break;
+ case K_TRN__VSCALE:
+ yscale = atof(vp) / 100.0;
+ break;
+ case K_TRN__ANGLE:
+ rotate = M_PI * atof(vp) / 180.0;
+ break;
+ case K_DIM__LLX:
+ t->bbox.llx = atof(vp);
+ t->flags |= INFO_HAS_USER_BBOX;
+ break;
+ case K_DIM__LLY:
+ t->bbox.lly = atof(vp);
+ t->flags |= INFO_HAS_USER_BBOX;
+ break;
+ case K_DIM__URX:
+ t->bbox.urx = atof(vp);
+ t->flags |= INFO_HAS_USER_BBOX;
+ break;
+ case K_DIM__URY:
+ t->bbox.ury = atof(vp);
+ t->flags |= INFO_HAS_USER_BBOX;
+ break;
+ case K_DIM__RWI:
+ t->width = atof(vp) / 10.0;
+ t->flags |= INFO_HAS_WIDTH;
+ break;
+ case K_DIM__RHI:
+ t->height = atof(vp) / 10.0;
+ t->flags |= INFO_HAS_HEIGHT;
+ break;
+ }
+ skip_blank(&ap->curptr, ap->endptr);
+ RELEASE(vp);
+ }
+ make_transmatrix(&(t->matrix), xoffset, yoffset, xscale, yscale, rotate);
+
+ return error;
+}
+
+
+static int
+spc_read_dimtrns_pdfm (struct spc_env *spe, transform_info *p, struct spc_arg *ap, long *page_no)
+{
+ int has_scale, has_xscale, has_yscale, has_rotate, has_matrix;
+ const char *_dtkeys[] = {
+#define K_DIM__WIDTH 0
+#define K_DIM__HEIGHT 1
+#define K_DIM__DEPTH 2
+ "width", "height", "depth",
+#define K_TRN__SCALE 3
+#define K_TRN__XSCALE 4
+#define K_TRN__YSCALE 5
+#define K_TRN__ROTATE 6
+ "scale", "xscale", "yscale", "rotate",
+#define K_TRN__BBOX 7
+ "bbox", /* See "Dvipdfmx User's Manual", p.5 */
+#define K_TRN__MATRIX 8
+ "matrix",
+#undef K__CLIP
+#define K__CLIP 9
+ "clip",
+#define K__PAGE 10
+ "page",
+#define K__HIDE 11
+ "hide",
+ NULL
+ };
+ double xscale, yscale, rotate;
+ int error = 0;
+
+ has_xscale = has_yscale = has_scale = has_rotate = has_matrix = 0;
+ xscale = yscale = 1.0; rotate = 0.0;
+ p->flags |= INFO_DO_CLIP; /* default: do clipping */
+ p->flags &= ~INFO_DO_HIDE; /* default: do clipping */
+
+ skip_blank(&ap->curptr, ap->endptr);
+
+ while (!error && ap->curptr < ap->endptr) {
+ char *kp, *vp;
+ int k;
+
+ kp = parse_c_ident(&ap->curptr, ap->endptr);
+ if (!kp)
+ break;
+
+ skip_blank(&ap->curptr, ap->endptr);
+ for (k = 0; _dtkeys[k] && strcmp(_dtkeys[k], kp); k++);
+ switch (k) {
+ case K_DIM__WIDTH:
+ error = spc_util_read_length(spe, &p->width , ap);
+ p->flags |= INFO_HAS_WIDTH;
+ break;
+ case K_DIM__HEIGHT:
+ error = spc_util_read_length(spe, &p->height, ap);
+ p->flags |= INFO_HAS_HEIGHT;
+ break;
+ case K_DIM__DEPTH:
+ error = spc_util_read_length(spe, &p->depth , ap);
+ p->flags |= INFO_HAS_HEIGHT;
+ break;
+ case K_TRN__SCALE:
+ vp = parse_float_decimal(&ap->curptr, ap->endptr);
+ if (!vp)
+ error = -1;
+ else {
+ xscale = yscale = atof(vp);
+ has_scale = 1;
+ RELEASE(vp);
+ }
+ break;
+ case K_TRN__XSCALE:
+ vp = parse_float_decimal(&ap->curptr, ap->endptr);
+ if (!vp)
+ error = -1;
+ else {
+ xscale = atof(vp);
+ has_xscale = 1;
+ RELEASE(vp);
+ }
+ break;
+ case K_TRN__YSCALE:
+ vp = parse_float_decimal(&ap->curptr, ap->endptr);
+ if (!vp)
+ error = -1;
+ else {
+ yscale = atof(vp);
+ has_yscale = 1;
+ RELEASE(vp);
+ }
+ break;
+ case K_TRN__ROTATE:
+ vp = parse_float_decimal(&ap->curptr, ap->endptr);
+ if (!vp)
+ error = -1;
+ else {
+ rotate = M_PI * atof(vp) / 180.0;
+ has_rotate = 1;
+ RELEASE(vp);
+ }
+ break;
+ case K_TRN__BBOX:
+ {
+ double v[4];
+ if (spc_util_read_numbers(v, 4, spe, ap) != 4)
+ error = -1;
+ else {
+ p->bbox.llx = v[0];
+ p->bbox.lly = v[1];
+ p->bbox.urx = v[2];
+ p->bbox.ury = v[3];
+ p->flags |= INFO_HAS_USER_BBOX;
+ }
+ }
+ break;
+ case K_TRN__MATRIX:
+ {
+ double v[6];
+ if (spc_util_read_numbers(v, 6, spe, ap) != 6)
+ error = -1;
+ else {
+ pdf_setmatrix(&(p->matrix), v[0], v[1], v[2], v[3], v[4], v[5]);
+ has_matrix = 1;
+ }
+ }
+ break;
+ case K__CLIP:
+ vp = parse_float_decimal(&ap->curptr, ap->endptr);
+ if (!vp)
+ error = -1;
+ else {
+ if (atof(vp))
+ p->flags |= INFO_DO_CLIP;
+ else
+ p->flags &= ~INFO_DO_CLIP;
+ RELEASE(vp);
+ }
+ break;
+ case K__PAGE:
+ {
+ double page;
+ if (page_no && spc_util_read_numbers(&page, 1, spe, ap) == 1)
+ *page_no = (long) page;
+ else
+ error = -1;
+ }
+ break;
+ case K__HIDE:
+ p->flags |= INFO_DO_HIDE;
+ break;
+ default:
+ error = -1;
+ break;
+ }
+ if (error)
+ spc_warn(spe, "Unrecognized key or invalid value for dimension/transformation: %s", kp);
+ else
+ skip_blank(&ap->curptr, ap->endptr);
+ RELEASE(kp);
+ }
+
+ if (!error) {
+ /* Check consistency */
+ if (has_xscale && (p->flags & INFO_HAS_WIDTH)) {
+ spc_warn(spe, "Can't supply both width and xscale. Ignore xscale.");
+ xscale = 1.0;
+ } else if (has_yscale &&
+ (p->flags & INFO_HAS_HEIGHT)) {
+ spc_warn(spe, "Can't supply both height/depth and yscale. Ignore yscale.");
+ yscale = 1.0;
+ } else if (has_scale &&
+ (has_xscale || has_yscale)) {
+ spc_warn(spe, "Can't supply overall scale along with axis scales.");
+ error = -1;
+ } else if (has_matrix &&
+ (has_scale || has_xscale || has_yscale || has_rotate)) {
+ spc_warn(spe, "Can't supply transform matrix along with scales or rotate. Ignore scales and rotate.");
+ }
+ }
+
+ if (!has_matrix) {
+ make_transmatrix(&(p->matrix), 0.0, 0.0, xscale, yscale, rotate);
+ }
+
+ if (!(p->flags & INFO_HAS_USER_BBOX)) {
+ p->flags &= ~INFO_DO_CLIP; /* no clipping needed */
+ }
+
+ return error;
+}
+
+int
+spc_util_read_dimtrns (struct spc_env *spe, transform_info *ti, struct spc_arg *args, long *page_no, int syntax)
+{
+ ASSERT(ti && spe && args);
+
+ if (syntax) {
+ ASSERT(!page_no);
+ return spc_read_dimtrns_dvips(spe, ti, args);
+ } else {
+ return spc_read_dimtrns_pdfm (spe, ti, args, page_no);
+ }
+
+ return -1;
+}
+
+
+/* Color names */
+#ifdef rgb
+#undef rgb
+#endif
+#ifdef cmyk
+#undef cmyk
+#endif
+#define gray(g) {1, {g}}
+#define rgb8(r,g,b) {3, {((r)/255.0), ((g)/255.0), ((b)/255.0), 0.0}}
+#define cmyk(c,m,y,k) {4, {(c), (m), (y), (k)}}
+
+static struct colordef_
+{
+ const char *key;
+ pdf_color color;
+} colordefs[] = {
+ {"GreenYellow", cmyk(0.15, 0.00, 0.69, 0.00)},
+ {"Yellow", cmyk(0.00, 0.00, 1.00, 0.00)},
+ {"Goldenrod", cmyk(0.00, 0.10, 0.84, 0.00)},
+ {"Dandelion", cmyk(0.00, 0.29, 0.84, 0.00)},
+ {"Apricot", cmyk(0.00, 0.32, 0.52, 0.00)},
+ {"Peach", cmyk(0.00, 0.50, 0.70, 0.00)},
+ {"Melon", cmyk(0.00, 0.46, 0.50, 0.00)},
+ {"YellowOrange", cmyk(0.00, 0.42, 1.00, 0.00)},
+ {"Orange", cmyk(0.00, 0.61, 0.87, 0.00)},
+ {"BurntOrange", cmyk(0.00, 0.51, 1.00, 0.00)},
+ {"Bittersweet", cmyk(0.00, 0.75, 1.00, 0.24)},
+ {"RedOrange", cmyk(0.00, 0.77, 0.87, 0.00)},
+ {"Mahogany", cmyk(0.00, 0.85, 0.87, 0.35)},
+ {"Maroon", cmyk(0.00, 0.87, 0.68, 0.32)},
+ {"BrickRed", cmyk(0.00, 0.89, 0.94, 0.28)},
+ {"Red", cmyk(0.00, 1.00, 1.00, 0.00)},
+ {"OrangeRed", cmyk(0.00, 1.00, 0.50, 0.00)},
+ {"RubineRed", cmyk(0.00, 1.00, 0.13, 0.00)},
+ {"WildStrawberry", cmyk(0.00, 0.96, 0.39, 0.00)},
+ {"Salmon", cmyk(0.00, 0.53, 0.38, 0.00)},
+ {"CarnationPink", cmyk(0.00, 0.63, 0.00, 0.00)},
+ {"Magenta", cmyk(0.00, 1.00, 0.00, 0.00)},
+ {"VioletRed", cmyk(0.00, 0.81, 0.00, 0.00)},
+ {"Rhodamine", cmyk(0.00, 0.82, 0.00, 0.00)},
+ {"Mulberry", cmyk(0.34, 0.90, 0.00, 0.02)},
+ {"RedViolet", cmyk(0.07, 0.90, 0.00, 0.34)},
+ {"Fuchsia", cmyk(0.47, 0.91, 0.00, 0.08)},
+ {"Lavender", cmyk(0.00, 0.48, 0.00, 0.00)},
+ {"Thistle", cmyk(0.12, 0.59, 0.00, 0.00)},
+ {"Orchid", cmyk(0.32, 0.64, 0.00, 0.00)},
+ {"DarkOrchid", cmyk(0.40, 0.80, 0.20, 0.00)},
+ {"Purple", cmyk(0.45, 0.86, 0.00, 0.00)},
+ {"Plum", cmyk(0.50, 1.00, 0.00, 0.00)},
+ {"Violet", cmyk(0.79, 0.88, 0.00, 0.00)},
+ {"RoyalPurple", cmyk(0.75, 0.90, 0.00, 0.00)},
+ {"BlueViolet", cmyk(0.86, 0.91, 0.00, 0.04)},
+ {"Periwinkle", cmyk(0.57, 0.55, 0.00, 0.00)},
+ {"CadetBlue", cmyk(0.62, 0.57, 0.23, 0.00)},
+ {"CornflowerBlue", cmyk(0.65, 0.13, 0.00, 0.00)},
+ {"MidnightBlue", cmyk(0.98, 0.13, 0.00, 0.43)},
+ {"NavyBlue", cmyk(0.94, 0.54, 0.00, 0.00)},
+ {"RoyalBlue", cmyk(1.00, 0.50, 0.00, 0.00)},
+ {"Blue", cmyk(1.00, 1.00, 0.00, 0.00)},
+ {"Cerulean", cmyk(0.94, 0.11, 0.00, 0.00)},
+ {"Cyan", cmyk(1.00, 0.00, 0.00, 0.00)},
+ {"ProcessBlue", cmyk(0.96, 0.00, 0.00, 0.00)},
+ {"SkyBlue", cmyk(0.62, 0.00, 0.12, 0.00)},
+ {"Turquoise", cmyk(0.85, 0.00, 0.20, 0.00)},
+ {"TealBlue", cmyk(0.86, 0.00, 0.34, 0.02)},
+ {"Aquamarine", cmyk(0.82, 0.00, 0.30, 0.00)},
+ {"BlueGreen", cmyk(0.85, 0.00, 0.33, 0.00)},
+ {"Emerald", cmyk(1.00, 0.00, 0.50, 0.00)},
+ {"JungleGreen", cmyk(0.99, 0.00, 0.52, 0.00)},
+ {"SeaGreen", cmyk(0.69, 0.00, 0.50, 0.00)},
+ {"Green", cmyk(1.00, 0.00, 1.00, 0.00)},
+ {"ForestGreen", cmyk(0.91, 0.00, 0.88, 0.12)},
+ {"PineGreen", cmyk(0.92, 0.00, 0.59, 0.25)},
+ {"LimeGreen", cmyk(0.50, 0.00, 1.00, 0.00)},
+ {"YellowGreen", cmyk(0.44, 0.00, 0.74, 0.00)},
+ {"SpringGreen", cmyk(0.26, 0.00, 0.76, 0.00)},
+ {"OliveGreen", cmyk(0.64, 0.00, 0.95, 0.40)},
+ {"RawSienna", cmyk(0.00, 0.72, 1.00, 0.45)},
+ {"Sepia", cmyk(0.00, 0.83, 1.00, 0.70)},
+ {"Brown", cmyk(0.00, 0.81, 1.00, 0.60)},
+ {"Tan", cmyk(0.14, 0.42, 0.56, 0.00)},
+ /* Adobe Reader 7 and 8 had problem when gray and cmyk black colors
+ * are mixed. No problem with Previewer.app.
+ * It happens when \usepackage[dvipdfm]{graphicx} and then called
+ * \usepackage{color} without dvipdfm option. */
+ {"Gray", gray(0.5)},
+ {"Black", gray(0.0)},
+ {"White", gray(1.0)},
+ {NULL}
+};
+
+
+static int
+pdf_color_namedcolor (pdf_color *color, const char *name)
+{
+ int i;
+ for (i = 0; colordefs[i].key; i++) {
+ if (!strcmp(colordefs[i].key, name)) {
+ pdf_color_copycolor(color, &colordefs[i].color);
+ return 0;
+ }
+ }
+ return -1;
+}
+
diff --git a/Build/source/texk/dvipdf-x/xsrc/spc_util.h b/Build/source/texk/dvipdf-x/xsrc/spc_util.h
new file mode 100644
index 00000000000..db5b16cf245
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/spc_util.h
@@ -0,0 +1,44 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _SPC_UTIL_H_
+#define _SPC_UTIL_H_
+
+#include "pdfcolor.h"
+#include "pdfdev.h"
+
+#include "specials.h"
+
+/* syntax 1: ((rgb|cmyk|hsb|gray) colorvalues)|colorname
+ * syntax 0: pdf_number|pdf_array
+ *
+ * This is for reading *single* color specification.
+ */
+extern int spc_util_read_colorspec (struct spc_env *spe, pdf_color *colorspec, struct spc_arg *args, int syntax);
+extern int spc_util_read_dimtrns (struct spc_env *spe, transform_info *dimtrns, struct spc_arg *args, long *page, int syntax);
+extern int spc_util_read_length (struct spc_env *spe, double *length, struct spc_arg *ap);
+
+extern int spc_util_read_numbers (double *values, int num_values, struct spc_env *spe, struct spc_arg *args);
+
+#endif /* _SPC_UTIL_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/specials.c b/Build/source/texk/dvipdf-x/xsrc/specials.c
new file mode 100644
index 00000000000..0b9800eb81b
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/specials.c
@@ -0,0 +1,619 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <stdarg.h>
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+#include "numbers.h"
+
+#include "dvi.h"
+
+#include "pdfobj.h"
+#include "pdfparse.h"
+#include "pdfdoc.h"
+#include "pdfnames.h"
+
+#include "pdfdraw.h"
+#include "pdfdev.h"
+
+#include "spc_pdfm.h"
+#include "spc_tpic.h"
+#include "spc_html.h"
+#include "spc_misc.h"
+#include "spc_color.h"
+#include "spc_dvips.h"
+#ifdef XETEX
+#include "spc_xtx.h"
+#endif
+
+#include "specials.h"
+
+static int verbose = 0;
+void
+spc_set_verbose (void)
+{
+ verbose++;
+}
+
+
+void
+spc_warn (struct spc_env *spe, const char *fmt, ...)
+{
+ va_list ap;
+ static char buf[1024];
+
+ va_start(ap, fmt);
+
+ vsprintf(buf, fmt, ap);
+ WARN(buf);
+
+ va_end(ap);
+
+ return;
+}
+
+
+/* This is currently just to make other spc_xxx to not directly
+ * call dvi_xxx.
+ */
+int
+spc_begin_annot (struct spc_env *spe, pdf_obj *dict)
+{
+ pdf_doc_begin_annot(dict);
+ dvi_tag_depth(); /* Tell dvi interpreter to handle line-break. */
+ return 0;
+}
+
+int
+spc_end_annot (struct spc_env *spe)
+{
+ dvi_untag_depth();
+ pdf_doc_end_annot();
+ return 0;
+}
+
+int
+spc_resume_annot (struct spc_env *spe)
+{
+ dvi_link_annot(1);
+ return 0;
+}
+
+int
+spc_suspend_annot (struct spc_env *spe)
+{
+ dvi_link_annot(0);
+ return 0;
+}
+
+
+
+static struct ht_table *named_objects = NULL;
+
+/* reserved keys */
+static const char *_rkeys[] = {
+#define K_OBJ__XPOS 0
+#define K_OBJ__YPOS 1
+ "xpos", "ypos",
+#define K_OBJ__THISPAGE 2
+#define K_OBJ__PREVPAGE 3
+#define K_OBJ__NEXTPAGE 4
+ "thispage", "prevpage", "nextpage",
+#define K_OBJ__RESOURCES 5
+ "resources",
+#define K_OBJ__PAGES 6
+#define K_OBJ__NAMES 7
+ "pages", "names",
+#define K_OBJ__CATALOG 8
+#define K_OBJ__DOCINFO 9
+ "catalog", "docinfo",
+#if 0
+#define K_OBJ__TRAILER 10
+ "trailer",
+#endif /* NYI */
+ NULL
+};
+
+/* pageN where N is a positive integer.
+ * Note that page need not exist at this time.
+ */
+static int
+ispageref (const char *key)
+{
+ const char *p;
+ if (strlen(key) <= strlen("page") ||
+ memcmp(key, "page", strlen("page")))
+ return 0;
+ else {
+ for (p = key + 4; *p && *p >= '0' && *p <= '9'; p++);
+ if (*p != '\0')
+ return 0;
+ }
+ return 1;
+}
+
+/*
+ * The following routine returns copies, not the original object.
+ */
+pdf_obj *
+spc_lookup_reference (const char *key)
+{
+ pdf_obj *value = NULL;
+ pdf_coord cp;
+ int k;
+
+ ASSERT(named_objects);
+
+ if (!key)
+ return NULL;
+
+ for (k = 0; _rkeys[k] && strcmp(key, _rkeys[k]); k++);
+ switch (k) {
+ /* xpos and ypos must be position in device space here. */
+ case K_OBJ__XPOS:
+ cp.x = dvi_dev_xpos(); cp.y = 0.0;
+ pdf_dev_transform(&cp, NULL);
+ value = pdf_new_number(ROUND(cp.x, .01));
+ break;
+ case K_OBJ__YPOS:
+ cp.x = 0.0; cp.y = dvi_dev_ypos();
+ pdf_dev_transform(&cp, NULL);
+ value = pdf_new_number(ROUND(cp.y, .01));
+ break;
+ case K_OBJ__THISPAGE:
+ value = pdf_doc_this_page_ref();
+ break;
+ case K_OBJ__PREVPAGE:
+ value = pdf_doc_prev_page_ref();
+ break;
+ case K_OBJ__NEXTPAGE:
+ value = pdf_doc_next_page_ref();
+ break;
+ case K_OBJ__PAGES:
+ value = pdf_ref_obj(pdf_doc_page_tree());
+ break;
+ case K_OBJ__NAMES:
+ value = pdf_ref_obj(pdf_doc_names());
+ break;
+ case K_OBJ__RESOURCES:
+ value = pdf_ref_obj(pdf_doc_current_page_resources());
+ break;
+ case K_OBJ__CATALOG:
+ value = pdf_ref_obj(pdf_doc_catalog());
+ break;
+ case K_OBJ__DOCINFO:
+ value = pdf_ref_obj(pdf_doc_docinfo());
+ break;
+ default:
+ if (ispageref(key))
+ value = pdf_doc_ref_page(atoi(key + 4));
+ else {
+ value = pdf_names_lookup_reference(named_objects, key, strlen(key));
+ }
+ break;
+ }
+
+ if (!value) {
+ ERROR("Object reference %s not exist.", key);
+ }
+
+ return value;
+}
+
+pdf_obj *
+spc_lookup_object (const char *key)
+{
+ pdf_obj *value = NULL;
+ pdf_coord cp;
+ int k;
+
+ ASSERT(named_objects);
+
+ if (!key)
+ return NULL;
+
+ for (k = 0; _rkeys[k] && strcmp(key, _rkeys[k]); k++);
+ switch (k) {
+ case K_OBJ__XPOS:
+ cp.x = dvi_dev_xpos(); cp.y = 0.0;
+ pdf_dev_transform(&cp, NULL);
+ value = pdf_new_number(ROUND(cp.x, .01));
+ break;
+ case K_OBJ__YPOS:
+ cp.x = 0.0; cp.y = dvi_dev_ypos();
+ pdf_dev_transform(&cp, NULL);
+ value = pdf_new_number(ROUND(cp.y, .01));
+ break;
+ case K_OBJ__THISPAGE:
+ value = pdf_doc_this_page();
+ break;
+ case K_OBJ__PAGES:
+ value = pdf_doc_page_tree();
+ break;
+ case K_OBJ__NAMES:
+ value = pdf_doc_names();
+ break;
+ case K_OBJ__RESOURCES:
+ value = pdf_doc_current_page_resources();
+ break;
+ case K_OBJ__CATALOG:
+ value = pdf_doc_catalog();
+ break;
+ case K_OBJ__DOCINFO:
+ value = pdf_doc_docinfo();
+ break;
+ default:
+ value = pdf_names_lookup_object(named_objects, key, strlen(key));
+ break;
+ }
+
+/* spc_handler_pdfm_bead() in spc_pdfm.c controls NULL too.
+ if (!value) {
+ ERROR("Object reference %s not exist.", key);
+ }
+*/
+
+ return value;
+}
+
+void
+spc_push_object (const char *key, pdf_obj *value)
+{
+ int error = 0;
+
+ if (!key || !value)
+ return;
+
+ if (PDF_OBJ_INDIRECTTYPE(value)) {
+ pdf_names_add_reference(named_objects,
+ key, strlen(key), value);
+ } else {
+ error = pdf_names_add_object(named_objects,
+ key, strlen(key), value);
+ if (!error) {
+ /* _FIXME_:
+ * Objects created by pdf:obj must always
+ * be written to output regardless of if
+ * they are actually used in document.
+ */
+ pdf_obj *obj_ref = pdf_names_lookup_reference(named_objects,
+ key, strlen(key));
+ if (obj_ref)
+ pdf_release_obj(obj_ref);
+ }
+ }
+
+ return;
+}
+
+void
+spc_flush_object (const char *key)
+{
+ pdf_names_close_object(named_objects, key, strlen(key));
+}
+
+void
+spc_clear_objects (void)
+{
+ pdf_delete_name_tree(&named_objects);
+ named_objects = pdf_new_name_tree();
+}
+
+
+static int
+spc_handler_unknown (struct spc_env *spe,
+ struct spc_arg *args)
+{
+ ASSERT(spe && args);
+
+ args->curptr = args->endptr;
+
+ return -1;
+}
+
+static void
+init_special (struct spc_handler *special,
+ struct spc_env *spe,
+ struct spc_arg *args,
+ const char *p, long size,
+ double x_user, double y_user, double mag)
+{
+
+ special->key = NULL;
+ special->exec = (spc_handler_fn_ptr) &spc_handler_unknown;
+
+ spe->x_user = x_user;
+ spe->y_user = y_user;
+ spe->mag = mag;
+ spe->pg = pdf_doc_current_page_number(); /* _FIXME_ */
+
+ args->curptr = p;
+ args->endptr = args->curptr + size;
+ args->base = args->curptr;
+ args->command = NULL;
+
+ return;
+}
+
+static void
+check_garbage (struct spc_arg *args)
+{
+ ASSERT(args);
+
+ if (args->curptr >= args->endptr)
+ return;
+
+ skip_white(&args->curptr, args->endptr);
+ if (args->curptr < args->endptr) {
+ WARN("Unparsed material at end of special ignored.");
+ dump(args->curptr, args->endptr);
+ }
+
+ return;
+}
+
+static struct {
+ const char *key;
+ int (*bodhk_func) ();
+ int (*eodhk_func) ();
+ int (*bophk_func) ();
+ int (*eophk_func) ();
+ int (*check_func) (const char *, long);
+ int (*setup_func) (struct spc_handler *, struct spc_env *, struct spc_arg *);
+} known_specials[] = {
+
+ {"pdf:",
+ spc_pdfm_at_begin_document,
+ spc_pdfm_at_end_document,
+ NULL,
+ NULL,
+ spc_pdfm_check_special,
+ spc_pdfm_setup_handler
+ },
+
+#ifdef XETEX
+ {"x:",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ spc_xtx_check_special,
+ spc_xtx_setup_handler
+ },
+#endif
+
+ {"ps:",
+#ifdef XETEX
+ spc_dvips_at_begin_document,
+ spc_dvips_at_end_document,
+ spc_dvips_at_begin_page,
+#else
+ NULL,
+ NULL,
+ NULL,
+#endif
+ spc_dvips_at_end_page,
+ spc_dvips_check_special,
+ spc_dvips_setup_handler
+ },
+
+ {"color",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ spc_color_check_special,
+ spc_color_setup_handler
+ },
+
+ {"tpic",
+ spc_tpic_at_begin_document,
+ spc_tpic_at_end_document,
+ spc_tpic_at_begin_page,
+ spc_tpic_at_end_page,
+ spc_tpic_check_special,
+ spc_tpic_setup_handler
+ },
+
+ {"html:",
+ spc_html_at_begin_document,
+ spc_html_at_end_document,
+ spc_html_at_begin_page,
+ spc_html_at_end_page,
+ spc_html_check_special,
+ spc_html_setup_handler
+ },
+
+ {"unknown",
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ spc_misc_check_special,
+ spc_misc_setup_handler
+ },
+
+ {NULL} /* end */
+};
+
+int
+spc_exec_at_begin_page (void)
+{
+ int error = 0;
+ int i;
+
+ for (i = 0; known_specials[i].key != NULL; i++) {
+ if (known_specials[i].bophk_func) {
+ error = known_specials[i].bophk_func();
+ }
+ }
+
+ return error;
+}
+
+int
+spc_exec_at_end_page (void)
+{
+ int error = 0;
+ int i;
+
+ for (i = 0; known_specials[i].key != NULL; i++) {
+ if (known_specials[i].eophk_func) {
+ error = known_specials[i].eophk_func();
+ }
+ }
+
+ return error;
+}
+
+int
+spc_exec_at_begin_document (void)
+{
+ int error = 0;
+ int i;
+
+ ASSERT(!named_objects);
+
+ named_objects = pdf_new_name_tree();
+
+ for (i = 0; known_specials[i].key != NULL; i++) {
+ if (known_specials[i].bodhk_func) {
+ error = known_specials[i].bodhk_func();
+ }
+ }
+
+ return error;
+}
+
+int
+spc_exec_at_end_document (void)
+{
+ int error = 0;
+ int i;
+
+ for (i = 0; known_specials[i].key != NULL; i++) {
+ if (known_specials[i].eodhk_func) {
+ error = known_specials[i].eodhk_func();
+ }
+ }
+
+ if (named_objects) {
+ pdf_delete_name_tree(&named_objects);
+ }
+
+ return error;
+}
+
+static void
+print_error (const char *name, struct spc_env *spe, struct spc_arg *ap)
+{
+ const char *p;
+ char ebuf[64];
+ int i;
+ long pg = spe->pg;
+ pdf_coord c;
+
+ c.x = spe->x_user; c.y = spe->y_user;
+ pdf_dev_transform(&c, NULL);
+
+ if (ap->command && name) {
+ WARN("Interpreting special command %s (%s) failed.", ap->command, name);
+ WARN(">> at page=\"%ld\" position=\"(%g, %g)\" (in PDF)", pg, c.x, c.y);
+ }
+ for (i = 0, p = ap->base; i < 63 && p < ap->endptr; p++) {
+ if (isprint(*p))
+ ebuf[i++] = *p;
+ else if (i + 4 < 63)
+ i += sprintf(ebuf + i, "\\x%02x", (unsigned char)*p);
+ else
+ break;
+ }
+ ebuf[i] = '\0';
+ if (ap->curptr < ap->endptr) {
+ while (i-- > 60)
+ ebuf[i] = '.';
+ }
+ WARN(">> xxx \"%s\"", ebuf);
+
+ if (ap->curptr < ap->endptr) {
+ for (i = 0, p = ap->curptr; i < 63 && p < ap->endptr; p++) {
+ if (isprint(*p))
+ ebuf[i++] = *p;
+ else if (i + 4 < 63)
+ i += sprintf(ebuf + i, "\\x%02x", (unsigned char)*p);
+ else
+ break;
+ }
+ ebuf[i] = '\0';
+ if (ap->curptr < ap->endptr) {
+ while (i-- > 60)
+ ebuf[i] = '.';
+ }
+ WARN(">> Reading special command stopped around >>%s<<", ebuf);
+
+ ap->curptr = ap->endptr;
+ }
+}
+
+int
+spc_exec_special (const char *buffer, long size,
+ double x_user, double y_user, double mag)
+{
+ int error = -1;
+ int i, found;
+ struct spc_env spe;
+ struct spc_arg args;
+ struct spc_handler special;
+
+ if (verbose > 3) {
+ dump(buffer, buffer + size);
+ }
+
+ init_special(&special, &spe, &args, buffer, size, x_user, y_user, mag);
+
+ for (i = 0; known_specials[i].key != NULL; i++) {
+ found = known_specials[i].check_func(buffer, size);
+ if (found) {
+ error = known_specials[i].setup_func(&special, &spe, &args);
+ if (!error) {
+ error = special.exec(&spe, &args);
+ }
+ if (error) {
+ print_error(known_specials[i].key, &spe, &args);
+ }
+ break;
+ }
+ }
+
+ check_garbage(&args);
+
+ return error;
+}
+
diff --git a/Build/source/texk/dvipdf-x/xsrc/tfm.c b/Build/source/texk/dvipdf-x/xsrc/tfm.c
new file mode 100644
index 00000000000..3622b16f071
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/tfm.c
@@ -0,0 +1,1209 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <string.h>
+
+#include "system.h"
+#include "mem.h"
+#include "mfileio.h"
+#include "error.h"
+
+#include "numbers.h"
+#include "dpxutil.h"
+
+#include "tfm.h"
+
+#define TFM_FORMAT 1
+#define OFM_FORMAT 2
+
+#define FWBASE ((double) (1<<20))
+
+static int verbose = 0;
+
+
+#ifndef WITHOUT_ASCII_PTEX
+/*
+ * ID is 9 for vertical JFM file.
+ */
+#define JFM_ID 11
+#define JFMV_ID 9
+#define IS_JFM(i) ((i) == JFM_ID || (i) == JFMV_ID)
+#endif /* !WITHOUT_ASCII_PTEX */
+
+/*
+ * TFM Record structure:
+ * Multiple TFM's may be read in at once.
+ */
+
+struct tfm_font
+{
+#ifndef WITHOUT_ASCII_PTEX
+ UNSIGNED_BYTE id;
+ UNSIGNED_BYTE nt;
+#endif /* !WITHOUT_ASCII_PTEX */
+#ifndef WITHOUT_OMEGA
+ SIGNED_QUAD level;
+#endif /* !WITHOUT_OMEGA */
+ UNSIGNED_QUAD wlenfile;
+ UNSIGNED_QUAD wlenheader;
+ UNSIGNED_QUAD bc, ec;
+ UNSIGNED_QUAD nwidths, nheights, ndepths;
+ UNSIGNED_QUAD nitcor, nlig, nkern, nextens;
+ UNSIGNED_QUAD nfonparm;
+#ifndef WITHOUT_OMEGA
+ UNSIGNED_QUAD fontdir;
+ UNSIGNED_QUAD nco, ncw, npc;
+#endif /* !WITHOUT_OMEGA */
+ SIGNED_QUAD *header;
+#ifndef WITHOUT_ASCII_PTEX
+ UNSIGNED_PAIR *chartypes;
+#endif /* !WITHOUT_ASCII_PTEX */
+ UNSIGNED_QUAD *char_info;
+ UNSIGNED_PAIR *width_index;
+ UNSIGNED_BYTE *height_index;
+ UNSIGNED_BYTE *depth_index;
+ SIGNED_QUAD *width;
+ SIGNED_QUAD *height;
+ SIGNED_QUAD *depth;
+};
+
+static void
+tfm_font_init (struct tfm_font *tfm)
+{
+ tfm->header = NULL;
+#ifndef WITHOUT_ASCII_PTEX
+ tfm->id = 0;
+ tfm->nt = 0;
+ tfm->chartypes = NULL;
+#endif /* !WITHOUT_ASCII_PTEX */
+#ifndef WITHOUT_OMEGA
+ tfm->level = 0;
+ tfm->fontdir = 0;
+ tfm->nco = tfm->ncw = tfm->npc = 0;
+#endif
+ tfm->char_info = NULL;
+ tfm->width_index = NULL;
+ tfm->height_index = NULL;
+ tfm->depth_index = NULL;
+ tfm->width = tfm->height = tfm->depth = NULL;
+}
+
+static void
+tfm_font_clear (struct tfm_font *tfm)
+{
+ if (tfm) {
+ if (tfm->header) {
+ RELEASE(tfm->header);
+ tfm->header = NULL;
+ }
+ if (tfm->char_info) {
+ RELEASE(tfm->char_info);
+ tfm->char_info = NULL;
+ }
+ if (tfm->width) {
+ RELEASE(tfm->width);
+ tfm->width = NULL;
+ }
+ if (tfm->height) {
+ RELEASE(tfm->height);
+ tfm->height = NULL;
+ }
+ if (tfm->depth) {
+ RELEASE(tfm->depth);
+ tfm->depth = NULL;
+ }
+#ifndef WITHOUT_ASCII_PTEX
+ if (tfm->chartypes) {
+ RELEASE(tfm->chartypes);
+ tfm->chartypes = NULL;
+ }
+#endif /* !WITHOUT_ASCII_PTEX */
+ if (tfm->width_index) {
+ RELEASE(tfm->width_index);
+ tfm->width_index = NULL;
+ }
+ if (tfm->height_index) {
+ RELEASE(tfm->height_index);
+ tfm->height_index = NULL;
+ }
+ if (tfm->depth_index) {
+ RELEASE(tfm->depth_index);
+ tfm->depth_index = NULL;
+ }
+ }
+}
+
+
+struct coverage
+{
+ long first_char;
+ unsigned short num_chars;
+};
+
+/*
+ * All characters in the same range have same metrics.
+ */
+
+struct range_map {
+ unsigned short num_coverages;
+ struct coverage *coverages;
+ unsigned short *indices;
+};
+
+/* Special case of num_coverages = 1 */
+struct char_map
+{
+ struct coverage coverage;
+ unsigned short *indices;
+};
+
+static void
+release_char_map (struct char_map *map)
+{
+ if (map->indices)
+ RELEASE(map->indices);
+ map->indices = NULL;
+ RELEASE(map);
+}
+
+static void
+release_range_map (struct range_map *map)
+{
+ if (map->coverages)
+ RELEASE(map->coverages);
+ if (map->indices)
+ RELEASE(map->indices);
+ map->coverages = NULL;
+ map->indices = NULL;
+ RELEASE(map);
+}
+
+static long
+lookup_char (const struct char_map *map, long charcode)
+{
+ if (charcode >= map->coverage.first_char &&
+ charcode <= map->coverage.first_char + map->coverage.num_chars)
+ return map->indices[charcode - map->coverage.first_char];
+ else
+ return -1;
+
+ return -1;
+}
+
+static long
+lookup_range (const struct range_map *map, long charcode)
+{
+ long idx;
+
+ for (idx = map->num_coverages - 1; idx >= 0 &&
+ charcode >= map->coverages[idx].first_char; idx--) {
+ if (charcode <=
+ map->coverages[idx].first_char + map->coverages[idx].num_chars)
+ return map->indices[idx];
+ }
+
+ return -1;
+}
+
+#define SOURCE_TYPE_TFM 0
+#define SOURCE_TYPE_JFM 1
+#define SOURCE_TYPE_OFM 2
+
+#define MAPTYPE_NONE 0
+#define MAPTYPE_CHAR 1
+#define MAPTYPE_RANGE 2
+
+#define FONT_DIR_HORIZ 0
+#define FONT_DIR_VERT 1
+
+struct font_metric
+{
+ char *tex_name;
+ fixword designsize;
+ char *codingscheme;
+
+ int fontdir;
+ long firstchar, lastchar;
+
+ fixword *widths;
+ fixword *heights;
+ fixword *depths;
+
+ struct {
+ int type;
+ void *data;
+ } charmap;
+
+ int source;
+};
+
+static void
+fm_init (struct font_metric *fm)
+{
+ fm->tex_name = NULL;
+ fm->firstchar = 0;
+ fm->lastchar = 0;
+ fm->fontdir = FONT_DIR_HORIZ;
+ fm->codingscheme = NULL;
+ fm->designsize = 0;
+
+ fm->widths = NULL;
+ fm->heights = NULL;
+ fm->depths = NULL;
+
+ fm->charmap.type = MAPTYPE_NONE;
+ fm->charmap.data = NULL;
+
+ fm->source = SOURCE_TYPE_TFM;
+}
+
+static void
+fm_clear (struct font_metric *fm)
+{
+ if (fm) {
+ if (fm->tex_name)
+ RELEASE(fm->tex_name);
+ if (fm->widths)
+ RELEASE(fm->widths);
+ if (fm->heights)
+ RELEASE(fm->heights);
+ if (fm->depths)
+ RELEASE(fm->depths);
+ if (fm->codingscheme)
+ RELEASE(fm->codingscheme);
+
+ switch (fm->charmap.type) {
+ case MAPTYPE_CHAR:
+ release_char_map(fm->charmap.data);
+ break;
+ case MAPTYPE_RANGE:
+ release_range_map(fm->charmap.data);
+ break;
+ }
+ }
+}
+
+#ifndef MAX_FONTS
+#define MAX_FONTS 16
+#endif
+
+struct font_metric *fms = NULL;
+static unsigned numfms = 0, max_fms = 0;
+
+static void
+fms_need (unsigned n)
+{
+ if (n > max_fms) {
+ max_fms = MAX(max_fms + MAX_FONTS, n);
+ fms = RENEW(fms, max_fms, struct font_metric);
+ }
+}
+
+void
+tfm_set_verbose (void)
+{
+ verbose++;
+}
+
+
+static long
+fread_fwords (SIGNED_QUAD *words, SIGNED_QUAD nmemb, FILE *fp)
+{
+ long i;
+
+ for (i = 0; i < nmemb; i++)
+ words[i] = get_signed_quad(fp);
+
+ return nmemb*4;
+}
+
+static long
+fread_uquads (UNSIGNED_QUAD *quads, SIGNED_QUAD nmemb, FILE *fp)
+{
+ long i;
+
+ for (i = 0; i < nmemb; i++) {
+ quads[i] = get_unsigned_quad(fp);
+ }
+
+ return nmemb*4;
+}
+
+/*
+ * TFM and JFM
+ */
+static void
+tfm_check_size (struct tfm_font *tfm, SIGNED_QUAD tfm_file_size)
+{
+ UNSIGNED_QUAD expected_size = 6;
+
+ /* Removed the warning message caused by EC TFM metric files.
+ *
+ if (tfm->wlenfile != tfm_file_size / 4) {
+ WARN("TFM file size is %ld bytes but it says it is %ld bytes!",
+ tfm_file_size, tfm->wlenfile * 4);
+ if (tfm_file_size > tfm->wlenfile * 4) {
+ WARN("Proceeding nervously...");
+ } else {
+ ERROR("Can't proceed...");
+ }
+ }
+ */
+ if (tfm_file_size < tfm->wlenfile * 4) {
+ ERROR("Can't proceed...");
+ }
+
+ expected_size += (tfm->ec - tfm->bc + 1);
+ expected_size += tfm->wlenheader;
+ expected_size += tfm->nwidths;
+ expected_size += tfm->nheights;
+ expected_size += tfm->ndepths;
+ expected_size += tfm->nitcor;
+ expected_size += tfm->nlig;
+ expected_size += tfm->nkern;
+ expected_size += tfm->nextens;
+ expected_size += tfm->nfonparm;
+#ifndef WITHOUT_ASCII_PTEX
+ if (IS_JFM(tfm->id)) {
+ expected_size += tfm->nt + 1;
+ }
+#endif /* !WITHOUT_ASCII_PTEX */
+ if (expected_size != tfm->wlenfile) {
+ WARN("TFM file size is expected to be %ld bytes but it says it is %ld bytes!",
+ expected_size * 4, tfm->wlenfile * 4);
+ if (tfm_file_size > expected_size *4) {
+ WARN("Proceeding nervously...");
+ } else {
+ ERROR("Can't proceed...");
+ }
+ }
+}
+
+static void
+tfm_get_sizes (FILE *tfm_file, SIGNED_QUAD tfm_file_size, struct tfm_font *tfm)
+{
+#ifndef WITHOUT_ASCII_PTEX
+ {
+ UNSIGNED_PAIR first_hword;
+
+ /*
+ * The first half word of TFM/JFM is TFM ID for JFM or size of
+ * TFM file in word for TFM. TFM with 9*4 or 11*4 bytes is not
+ * expected to be a valid TFM. So, we always assume that TFMs
+ * starting with 00 09 or 00 0B is JFM.
+ */
+ first_hword = get_unsigned_pair(tfm_file);
+ if (IS_JFM(first_hword)) {
+ tfm->id = first_hword;
+ tfm->nt = get_unsigned_pair(tfm_file);
+ tfm->wlenfile = get_unsigned_pair(tfm_file);
+ } else {
+ tfm->wlenfile = first_hword;
+ }
+ }
+#else /* WITHOUT_ASCII_PTEX */
+ tfm->wlenfile = get_unsigned_pair(tfm_file);
+#endif /* !WITHOUT_ASCII_PTEX */
+
+ tfm->wlenheader = get_unsigned_pair(tfm_file);
+ tfm->bc = get_unsigned_pair(tfm_file);
+ tfm->ec = get_unsigned_pair(tfm_file);
+ if (tfm->ec < tfm->bc) {
+ ERROR("TFM file error: ec(%u) < bc(%u) ???", tfm->ec, tfm->bc);
+ }
+ tfm->nwidths = get_unsigned_pair(tfm_file);
+ tfm->nheights = get_unsigned_pair(tfm_file);
+ tfm->ndepths = get_unsigned_pair(tfm_file);
+ tfm->nitcor = get_unsigned_pair(tfm_file);
+ tfm->nlig = get_unsigned_pair(tfm_file);
+ tfm->nkern = get_unsigned_pair(tfm_file);
+ tfm->nextens = get_unsigned_pair(tfm_file);
+ tfm->nfonparm = get_unsigned_pair(tfm_file);
+
+ tfm_check_size(tfm, tfm_file_size);
+
+ return;
+}
+
+#ifndef WITHOUT_ASCII_PTEX
+static void
+jfm_do_char_type_array (FILE *tfm_file, struct tfm_font *tfm)
+{
+ UNSIGNED_PAIR charcode;
+ UNSIGNED_PAIR chartype;
+ long i;
+
+ tfm->chartypes = NEW(65536, UNSIGNED_PAIR);
+ for (i = 0; i < 65536; i++) {
+ tfm->chartypes[i] = 0;
+ }
+ for (i = 0; i < tfm->nt; i++) {
+ charcode = get_unsigned_pair(tfm_file);
+ chartype = get_unsigned_pair(tfm_file);
+ tfm->chartypes[charcode] = chartype;
+ }
+}
+
+static void
+jfm_make_charmap (struct font_metric *fm, struct tfm_font *tfm)
+{
+ if (tfm->nt > 1) {
+ struct char_map *map;
+ long code;
+
+ fm->charmap.type = MAPTYPE_CHAR;
+ fm->charmap.data = map = NEW(1, struct char_map);
+ map->coverage.first_char = 0;
+ map->coverage.num_chars = 0xFFFFu;
+ map->indices = NEW(0x10000L, unsigned short);
+
+ for (code = 0; code <= 0xFFFFu; code++) {
+ map->indices[code] = tfm->chartypes[code];
+ }
+ } else {
+ struct range_map *map;
+
+ fm->charmap.type = MAPTYPE_RANGE;
+ fm->charmap.data = map = NEW(1, struct range_map);
+ map->num_coverages = 1;
+ map->coverages = NEW(map->num_coverages, struct coverage);
+ map->coverages[0].first_char = 0;
+ map->coverages[0].num_chars = 0xFFFFu;
+ map->indices = NEW(1, unsigned short);
+ map->indices[0] = 0; /* Only default type used. */
+ }
+}
+#endif /* !WITHOUT_ASCII_PTEX */
+
+static void
+tfm_unpack_arrays (struct font_metric *fm, struct tfm_font *tfm)
+{
+ UNSIGNED_QUAD charinfo;
+ UNSIGNED_PAIR width_index, height_index, depth_index;
+ int i;
+
+ fm->widths = NEW(256, fixword);
+ fm->heights = NEW(256, fixword);
+ fm->depths = NEW(256, fixword);
+ for (i = 0; i < 256; i++) {
+ fm->widths [i] = 0;
+ fm->heights[i] = 0;
+ fm->depths [i] = 0;
+ }
+
+ for (i = tfm->bc; i <= tfm->ec; i++ ) {
+ charinfo = tfm->char_info[i - tfm->bc];
+ width_index = (charinfo / 16777216ul);
+ height_index = (charinfo / 0x100000ul) & 0xf;
+ depth_index = (charinfo / 0x10000ul) & 0xf;
+ fm->widths [i] = tfm->width [width_index];
+ fm->heights[i] = tfm->height[height_index];
+ fm->depths [i] = tfm->depth [depth_index];
+ }
+
+ return;
+}
+
+static int
+sput_bigendian (char *s, SIGNED_QUAD v, int n)
+{
+ int i;
+
+ for (i = n-1; i >= 0; i--) {
+ s[i] = (char) (v & 0xff);
+ v >>= 8;
+ }
+
+ return n;
+}
+
+static void
+tfm_unpack_header (struct font_metric *fm, struct tfm_font *tfm)
+{
+ if (tfm->wlenheader < 12) {
+ fm->codingscheme = NULL;
+ } else {
+ int i, len;
+ char *p;
+
+ len = (tfm->header[2] >> 24);
+ if (len < 0 || len > 39)
+ ERROR("Invalid TFM header.");
+ if (len > 0) {
+ fm->codingscheme = NEW(40, char);
+ p = fm->codingscheme;
+ p += sput_bigendian(p, tfm->header[2], 3);
+ for (i = 1; i <= len / 4; i++) {
+ p += sput_bigendian(p, tfm->header[2+i], 4);
+ }
+ fm->codingscheme[len] = '\0';
+ } else {
+ fm->codingscheme = NULL;
+ }
+ }
+
+ fm->designsize = tfm->header[1];
+}
+
+#ifndef WITHOUT_OMEGA
+
+static void
+ofm_check_size_one (struct tfm_font *tfm, SIGNED_QUAD ofm_file_size)
+{
+ UNSIGNED_QUAD ofm_size = 14;
+
+ ofm_size += 2*(tfm->ec - tfm->bc + 1);
+ ofm_size += tfm->wlenheader;
+ ofm_size += tfm->nwidths;
+ ofm_size += tfm->nheights;
+ ofm_size += tfm->ndepths;
+ ofm_size += tfm->nitcor;
+ ofm_size += 2*(tfm->nlig);
+ ofm_size += tfm->nkern;
+ ofm_size += 2*(tfm->nextens);
+ ofm_size += tfm->nfonparm;
+ if (tfm->wlenfile != ofm_file_size / 4 ||
+ tfm->wlenfile != ofm_size) {
+ ERROR("OFM file problem. Table sizes don't agree.");
+ }
+}
+
+static void
+ofm_get_sizes (FILE *ofm_file, UNSIGNED_QUAD ofm_file_size, struct tfm_font *tfm)
+{
+ tfm->level = get_signed_quad(ofm_file);
+
+ tfm->wlenfile = get_signed_quad(ofm_file);
+ tfm->wlenheader = get_signed_quad(ofm_file);
+ tfm->bc = get_signed_quad(ofm_file);
+ tfm->ec = get_signed_quad(ofm_file);
+ if (tfm->ec < tfm->bc) {
+ ERROR("OFM file error: ec(%u) < bc(%u) ???", tfm->ec, tfm->bc);
+ }
+ tfm->nwidths = get_signed_quad(ofm_file);
+ tfm->nheights = get_signed_quad(ofm_file);
+ tfm->ndepths = get_signed_quad(ofm_file);
+ tfm->nitcor = get_signed_quad(ofm_file);
+ tfm->nlig = get_signed_quad(ofm_file);
+ tfm->nkern = get_signed_quad(ofm_file);
+ tfm->nextens = get_signed_quad(ofm_file);
+ tfm->nfonparm = get_signed_quad(ofm_file);
+ tfm->fontdir = get_signed_quad(ofm_file);
+ if (tfm->fontdir) {
+ WARN("I may be interpreting a font direction incorrectly.");
+ }
+ if (tfm->level == 0) {
+ ofm_check_size_one(tfm, ofm_file_size);
+ } else if (tfm->level == 1) {
+ tfm->nco = get_signed_quad(ofm_file);
+ tfm->ncw = get_signed_quad(ofm_file);
+ tfm->npc = get_signed_quad(ofm_file);
+ seek_absolute(ofm_file, 4*(tfm->nco - tfm->wlenheader));
+ } else {
+ ERROR("Can't handle OFM files with level > 1");
+ }
+
+ return;
+}
+
+static void
+ofm_do_char_info_zero (FILE *tfm_file, struct tfm_font *tfm)
+{
+ UNSIGNED_QUAD num_chars;
+
+ num_chars = tfm->ec - tfm->bc + 1;
+ if (num_chars != 0) {
+ UNSIGNED_QUAD i;
+
+ tfm->width_index = NEW(num_chars, UNSIGNED_PAIR);
+ tfm->height_index = NEW(num_chars, UNSIGNED_BYTE);
+ tfm->depth_index = NEW(num_chars, UNSIGNED_BYTE);
+ for (i = 0; i < num_chars; i++) {
+ tfm->width_index [i] = get_unsigned_pair(tfm_file);
+ tfm->height_index[i] = get_unsigned_byte(tfm_file);
+ tfm->depth_index [i] = get_unsigned_byte(tfm_file);
+ /* Ignore remaining quad */
+ get_unsigned_quad(tfm_file);
+ }
+ }
+}
+
+static void
+ofm_do_char_info_one (FILE *tfm_file, struct tfm_font *tfm)
+{
+ UNSIGNED_QUAD num_char_infos;
+ UNSIGNED_QUAD num_chars;
+
+ num_char_infos = tfm->ncw / (3 + (tfm->npc / 2));
+ num_chars = tfm->ec - tfm ->bc + 1;
+
+ if (num_chars != 0) {
+ UNSIGNED_QUAD i;
+ UNSIGNED_QUAD char_infos_read;
+
+ tfm->width_index = NEW(num_chars, UNSIGNED_PAIR);
+ tfm->height_index = NEW(num_chars, UNSIGNED_BYTE);
+ tfm->depth_index = NEW(num_chars, UNSIGNED_BYTE);
+ char_infos_read = 0;
+ for (i = 0; i < num_chars &&
+ char_infos_read < num_char_infos; i++) {
+ int repeats, j;
+
+ tfm->width_index [i] = get_unsigned_pair(tfm_file);
+ tfm->height_index[i] = get_unsigned_byte(tfm_file);
+ tfm->depth_index [i] = get_unsigned_byte(tfm_file);
+ /* Ignore next quad */
+ get_unsigned_quad(tfm_file);
+ repeats = get_unsigned_pair(tfm_file);
+ /* Skip params */
+ for (j = 0; j < tfm->npc; j++) {
+ get_unsigned_pair(tfm_file);
+ }
+ /* Remove word padding if necessary */
+ if (ISEVEN(tfm->npc)){
+ get_unsigned_pair(tfm_file);
+ }
+ char_infos_read++;
+ if (i + repeats > num_chars) {
+ ERROR("Repeats causes number of characters to be exceeded.");
+ }
+ for (j = 0; j < repeats; j++) {
+ tfm->width_index [i+j+1] = tfm->width_index [i];
+ tfm->height_index[i+j+1] = tfm->height_index[i];
+ tfm->depth_index [i+j+1] = tfm->depth_index [i];
+ }
+ /* Skip ahead because we have already handled repeats */
+ i += repeats;
+ }
+ }
+}
+
+static void
+ofm_unpack_arrays (struct font_metric *fm,
+ struct tfm_font *tfm, UNSIGNED_QUAD num_chars)
+{
+ long i;
+
+ fm->widths = NEW(tfm->bc + num_chars, fixword);
+ fm->heights = NEW(tfm->bc + num_chars, fixword);
+ fm->depths = NEW(tfm->bc + num_chars, fixword);
+ for (i = 0; i < num_chars; i++) {
+ fm->widths [tfm->bc + i] = tfm->width [ tfm->width_index [i] ];
+ fm->heights[tfm->bc + i] = tfm->height[ tfm->height_index[i] ];
+ fm->depths [tfm->bc + i] = tfm->depth [ tfm->depth_index [i] ];
+ }
+}
+
+static void
+read_ofm (struct font_metric *fm, FILE *ofm_file, UNSIGNED_QUAD ofm_file_size)
+{
+ struct tfm_font tfm;
+
+ tfm_font_init(&tfm);
+
+ ofm_get_sizes(ofm_file, ofm_file_size, &tfm);
+
+ if (tfm.level < 0 || tfm.level > 1)
+ ERROR ("OFM level %d not supported.", tfm.level);
+
+ if (tfm.wlenheader > 0) {
+ tfm.header = NEW(tfm.wlenheader, fixword);
+ fread_fwords(tfm.header, tfm.wlenheader, ofm_file);
+ }
+ if (tfm.level == 0) {
+ ofm_do_char_info_zero(ofm_file, &tfm);
+ } else if (tfm.level == 1) {
+ ofm_do_char_info_one(ofm_file, &tfm);
+ }
+ if (tfm.nwidths > 0) {
+ tfm.width = NEW(tfm.nwidths, fixword);
+ fread_fwords(tfm.width, tfm.nwidths, ofm_file);
+ }
+ if (tfm.nheights > 0) {
+ tfm.height = NEW(tfm.nheights, fixword);
+ fread_fwords(tfm.height, tfm.nheights, ofm_file);
+ }
+ if (tfm.ndepths > 0) {
+ tfm.depth = NEW(tfm.ndepths, fixword);
+ fread_fwords(tfm.depth, tfm.ndepths, ofm_file);
+ }
+
+ ofm_unpack_arrays(fm, &tfm, tfm.ec - tfm.bc + 1);
+ tfm_unpack_header(fm, &tfm);
+ fm->firstchar = tfm.bc;
+ fm->lastchar = tfm.ec;
+ fm->source = SOURCE_TYPE_OFM;
+
+ tfm_font_clear(&tfm);
+
+ return;
+}
+#endif /* !WITHOUT_OMEGA */
+
+static void
+read_tfm (struct font_metric *fm, FILE *tfm_file, UNSIGNED_QUAD tfm_file_size)
+{
+ struct tfm_font tfm;
+
+ tfm_font_init(&tfm);
+
+ tfm_get_sizes(tfm_file, tfm_file_size, &tfm);
+ fm->firstchar = tfm.bc;
+ fm->lastchar = tfm.ec;
+ if (tfm.wlenheader > 0) {
+ tfm.header = NEW(tfm.wlenheader, fixword);
+ fread_fwords(tfm.header, tfm.wlenheader, tfm_file);
+ }
+#ifndef WITHOUT_ASCII_PTEX
+ if (IS_JFM(tfm.id)) {
+ jfm_do_char_type_array(tfm_file, &tfm);
+ jfm_make_charmap(fm, &tfm);
+ fm->firstchar = 0;
+ fm->lastchar = 0xFFFFl;
+ fm->fontdir = (tfm.id == JFMV_ID) ? FONT_DIR_VERT : FONT_DIR_HORIZ;
+ fm->source = SOURCE_TYPE_JFM;
+ }
+#endif /* !WITHOUT_ASCII_PTEX */
+ if (tfm.ec - tfm.bc + 1 > 0) {
+ tfm.char_info = NEW(tfm.ec - tfm.bc + 1, UNSIGNED_QUAD);
+ fread_uquads(tfm.char_info, tfm.ec - tfm.bc + 1, tfm_file);
+ }
+ if (tfm.nwidths > 0) {
+ tfm.width = NEW(tfm.nwidths, fixword);
+ fread_fwords(tfm.width, tfm.nwidths, tfm_file);
+ }
+ if (tfm.nheights > 0) {
+ tfm.height = NEW(tfm.nheights, fixword);
+ fread_fwords(tfm.height, tfm.nheights, tfm_file);
+ }
+ if (tfm.ndepths > 0) {
+ tfm.depth = NEW(tfm.ndepths, fixword);
+ fread_fwords(tfm.depth, tfm.ndepths, tfm_file);
+ }
+ tfm_unpack_arrays(fm, &tfm);
+ tfm_unpack_header(fm, &tfm);
+
+ tfm_font_clear(&tfm);
+
+ return;
+}
+
+int
+tfm_open (const char *tfm_name, int must_exist)
+{
+ FILE *tfm_file;
+ int i, format = TFM_FORMAT;
+ UNSIGNED_QUAD tfm_file_size;
+ char *file_name = NULL;
+
+ for (i = 0; i < numfms; i++) {
+ if (!strcmp(tfm_name, fms[i].tex_name))
+ return i;
+ }
+
+ /*
+ * The procedure to search tfm or ofm files:
+ * 1. Search tfm file with the given name with the must_exist flag unset.
+ * 2. Search ofm file with the given name with the must_exist flag unset.
+ * 3. If not found and must_exist flag is set, try again to search
+ * tfm file with the must_exist flag set.
+ * 4. If not found and must_exist flag is not set, return -1.
+ */
+
+
+ /*
+ * We first look for OFM and then TFM.
+ * The reason for this change is incompatibility introduced when dvipdfmx
+ * started to write correct glyph metrics to output PDF for CID fonts.
+ * I'll not explain this in detail... This change is mostly specific to
+ * Japanese support.
+ */
+#if 0
+ if ((file_name = kpse_find_file(tfm_name, kpse_tfm_format, 0))) {
+ format = TFM_FORMAT;
+ } else if ((file_name = kpse_find_file(tfm_name, kpse_ofm_format, 0))) {
+ format = OFM_FORMAT;
+ }
+#endif
+ {
+ char *ofm_name, *suffix;
+
+ suffix = strrchr(tfm_name, '.');
+ if (!suffix || (strcmp(suffix, ".tfm") != 0 &&
+ strcmp(suffix, ".ofm") != 0)) {
+ ofm_name = NEW(strlen(tfm_name) + strlen(".ofm") + 1, char);
+ strcpy(ofm_name, tfm_name);
+ strcat(ofm_name, ".ofm");
+ } else {
+ ofm_name = NULL;
+ }
+ if (ofm_name &&
+ (file_name = kpse_find_file(ofm_name, kpse_ofm_format, 0)) != NULL) {
+ format = OFM_FORMAT;
+ } else if ((file_name =
+ kpse_find_file(tfm_name, kpse_tfm_format, 0)) != NULL) {
+ format = TFM_FORMAT;
+ } else if ((file_name =
+ kpse_find_file(tfm_name, kpse_ofm_format, 0)) != NULL) {
+ format = OFM_FORMAT;
+ }
+ if (ofm_name)
+ RELEASE(ofm_name);
+ }
+
+ /*
+ * In case that must_exist is set, MiKTeX returns always non-NULL value
+ * even if the tfm file is not found.
+ */
+ if (file_name == NULL) {
+ if (must_exist) {
+ if ((file_name = kpse_find_file(tfm_name, kpse_tfm_format, 1)) != NULL)
+ format = TFM_FORMAT;
+ else {
+ ERROR("Unable to find TFM file \"%s\".", tfm_name);
+ }
+ } else {
+ return -1;
+ }
+ }
+
+ tfm_file = MFOPEN(file_name, FOPEN_RBIN_MODE);
+ if (!tfm_file) {
+ ERROR("Could not open specified TFM/OFM file \"%s\".", tfm_name);
+ }
+
+ if (verbose) {
+ if (format == TFM_FORMAT)
+ MESG("(TFM:%s", tfm_name);
+ else if (format == OFM_FORMAT)
+ MESG("(OFM:%s", tfm_name);
+ if (verbose > 1)
+ MESG("[%s]", file_name);
+ }
+
+ RELEASE(file_name);
+
+ tfm_file_size = file_size(tfm_file);
+ if (tfm_file_size < 24) {
+ ERROR("TFM/OFM file too small to be a valid file.");
+ }
+
+ fms_need(numfms + 1);
+ fm_init(fms + numfms);
+
+#ifndef WITHOUT_OMEGA
+ if (format == OFM_FORMAT)
+ read_ofm(&fms[numfms], tfm_file, tfm_file_size);
+ else
+#endif /* !WITHOUT_OMEGA */
+ {
+ read_tfm(&fms[numfms], tfm_file, tfm_file_size);
+ }
+
+ MFCLOSE(tfm_file);
+
+ fms[numfms].tex_name = NEW(strlen(tfm_name)+1, char);
+ strcpy(fms[numfms].tex_name, tfm_name);
+
+ if (verbose)
+ MESG(")");
+
+ return numfms++;
+}
+
+void
+tfm_close_all (void)
+{
+ int i;
+
+ if (fms) {
+ for (i = 0; i < numfms; i++) {
+ fm_clear(&(fms[i]));
+ }
+ RELEASE(fms);
+ }
+}
+
+#define CHECK_ID(n) do {\
+ if ((n) < 0 || (n) >= numfms)\
+ ERROR("TFM: Invalid TFM ID: %d", (n));\
+} while (0)
+
+fixword
+tfm_get_fw_width (int font_id, SIGNED_QUAD ch)
+{
+ struct font_metric *fm;
+ long idx = 0;
+
+ CHECK_ID(font_id);
+
+ fm = &(fms[font_id]);
+ if (ch >= fm->firstchar && ch <= fm->lastchar) {
+ switch (fm->charmap.type) {
+ case MAPTYPE_CHAR:
+ idx = lookup_char(fm->charmap.data, ch);
+ if (idx < 0)
+ ERROR("Invalid char: %ld\n", ch);
+ break;
+ case MAPTYPE_RANGE:
+ idx = lookup_range(fm->charmap.data, ch);
+ if (idx < 0)
+ ERROR("Invalid char: %ld\n", ch);
+ break;
+ default:
+ idx = ch;
+ }
+ } else {
+ ERROR("Invalid char: %ld\n", ch);
+ }
+
+ return fm->widths[idx];
+}
+
+fixword
+tfm_get_fw_height (int font_id, SIGNED_QUAD ch)
+{
+ struct font_metric *fm;
+ long idx = 0;
+
+ CHECK_ID(font_id);
+
+ fm = &(fms[font_id]);
+ if (ch >= fm->firstchar && ch <= fm->lastchar) {
+ switch (fm->charmap.type) {
+ case MAPTYPE_CHAR:
+ idx = lookup_char(fm->charmap.data, ch);
+ if (idx < 0)
+ ERROR("Invalid char: %ld\n", ch);
+ break;
+ case MAPTYPE_RANGE:
+ idx = lookup_range(fm->charmap.data, ch);
+ if (idx < 0)
+ ERROR("Invalid char: %ld\n", ch);
+ break;
+ default:
+ idx = ch;
+ }
+ } else {
+ ERROR("Invalid char: %ld\n", ch);
+ }
+
+ return fm->heights[idx];
+}
+
+fixword
+tfm_get_fw_depth (int font_id, SIGNED_QUAD ch)
+{
+ struct font_metric *fm;
+ long idx = 0;
+
+ CHECK_ID(font_id);
+
+ fm = &(fms[font_id]);
+ if (ch >= fm->firstchar && ch <= fm->lastchar) {
+ switch (fm->charmap.type) {
+ case MAPTYPE_CHAR:
+ idx = lookup_char(fm->charmap.data, ch);
+ if (idx < 0)
+ ERROR("Invalid char: %ld\n", ch);
+ break;
+ case MAPTYPE_RANGE:
+ idx = lookup_range(fm->charmap.data, ch);
+ if (idx < 0)
+ ERROR("Invalid char: %ld\n", ch);
+ break;
+ default:
+ idx = ch;
+ }
+ } else {
+ ERROR("Invalid char: %ld\n", ch);
+ }
+
+ return fm->depths[idx];
+}
+
+
+/*
+ * tfm_get_width returns the width of the font
+ * as a (double) fraction of the design size.
+ */
+double
+tfm_get_width (int font_id, SIGNED_QUAD ch)
+{
+ return ((double) tfm_get_fw_width(font_id, ch)/FWBASE);
+}
+
+#if 0
+double
+tfm_get_height (int font_id, SIGNED_QUAD ch)
+{
+ return ((double) tfm_get_fw_height(font_id, ch)/FWBASE);
+}
+
+double
+tfm_get_depth (int font_id, SIGNED_QUAD ch)
+{
+ return ((double) tfm_get_fw_depth(font_id, ch)/FWBASE);
+}
+#endif
+
+/* tfm_string_xxx() do not work for OFM... */
+fixword
+tfm_string_width (int font_id, const unsigned char *s, unsigned len)
+{
+ fixword result = 0;
+ struct font_metric *fm;
+ unsigned i;
+
+ CHECK_ID(font_id);
+
+ fm = &(fms[font_id]);
+#ifndef WITHOUT_ASCII_PTEX
+ if (fm->source == SOURCE_TYPE_JFM) {
+ for (i = 0; i < len/2; i++) {
+ SIGNED_QUAD ch;
+
+ ch = (s[2*i] << 8)|s[2*i+1];
+ result += tfm_get_fw_width(font_id, ch);
+ }
+ } else
+#endif
+ for (i = 0; i < len; i++) {
+ result += tfm_get_fw_width(font_id, s[i]);
+ }
+
+ return result;
+}
+
+fixword
+tfm_string_depth (int font_id, const unsigned char *s, unsigned len)
+{
+ fixword result = 0;
+ struct font_metric *fm;
+ unsigned i;
+
+ CHECK_ID(font_id);
+
+ fm = &(fms[font_id]);
+#ifndef WITHOUT_ASCII_PTEX
+ if (fm->source == SOURCE_TYPE_JFM) {
+ for (i = 0; i < len/2; i++) {
+ SIGNED_QUAD ch;
+
+ ch = (s[2*i] << 8)|s[2*i+1];
+ result += tfm_get_fw_depth(font_id, ch);
+ }
+ } else
+#endif
+ for (i = 0; i < len; i++) {
+ result = MAX(result, tfm_get_fw_depth(font_id, s[i]));
+ }
+
+ return result;
+}
+
+fixword
+tfm_string_height (int font_id, const unsigned char *s, unsigned len)
+{
+ fixword result = 0;
+ struct font_metric *fm;
+ unsigned i;
+
+ CHECK_ID(font_id);
+
+ fm = &(fms[font_id]);
+#ifndef WITHOUT_ASCII_PTEX
+ if (fm->source == SOURCE_TYPE_JFM) {
+ for (i = 0; i < len/2; i++) {
+ SIGNED_QUAD ch;
+
+ ch = (s[2*i] << 8)|s[2*i+1];
+ result += tfm_get_fw_height(font_id, ch);
+ }
+ } else
+#endif
+ for (i = 0; i < len; i++) {
+ result = MAX(result, tfm_get_fw_height(font_id, s[i]));
+ }
+
+ return result;
+}
+
+double
+tfm_get_design_size (int font_id)
+{
+ CHECK_ID(font_id);
+
+ return (double) (fms[font_id].designsize)/FWBASE*(72.0/72.27);
+}
+
+#if 0
+char *
+tfm_get_codingscheme (int font_id)
+{
+ CHECK_ID(font_id);
+
+ return fms[font_id].codingscheme;
+}
+
+#ifndef WITHOUT_ASCII_PTEX
+/* Vertical version of JFM */
+int
+tfm_is_vert (int font_id)
+{
+ CHECK_ID(font_id);
+
+ return (fms[font_id].fontdir == FONT_DIR_VERT) ? 1 : 0;
+}
+#else /* WITHOUT_ASCII_PTEX */
+int
+tfm_is_vert (int font_id)
+{
+ return 0;
+}
+#endif /* !WITHOUT_ASCII_PTEX */
+#endif
+
+int
+tfm_exists (const char *tfm_name)
+{
+ char *fullname;
+
+ fullname = kpse_find_file(tfm_name, kpse_ofm_format, 0);
+ if (fullname) {
+ RELEASE(fullname);
+ return 1;
+ }
+ fullname = kpse_find_file(tfm_name, kpse_tfm_format, 0);
+ if (fullname) {
+ RELEASE(fullname);
+ return 1;
+ }
+
+ return 0;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/truetype.c b/Build/source/texk/dvipdf-x/xsrc/truetype.c
new file mode 100644
index 00000000000..4b8a7e59de1
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/truetype.c
@@ -0,0 +1,1009 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2007-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "system.h"
+
+#include "numbers.h"
+#include "error.h"
+#include "mem.h"
+
+#include "dpxfile.h"
+#include "dpxutil.h"
+
+#include "pdfobj.h"
+#include "pdfresource.h"
+#include "pdffont.h"
+
+#include "pdfencoding.h"
+#include "unicode.h"
+#include "agl.h"
+
+/* TrueType */
+#include "sfnt.h"
+#include "tt_cmap.h"
+#include "tt_table.h"
+#include "tt_glyf.h"
+#include "tt_post.h"
+#include "tt_gsub.h"
+#include "tt_aux.h"
+
+#include "truetype.h"
+
+#include "tfm.h"
+
+/* Modifying this has no effect :P */
+#ifdef ENABLE_NOEMBED
+# undef ENABLE_NOEMBED
+#endif
+
+int
+pdf_font_open_truetype (pdf_font *font)
+{
+ char *ident;
+ int index, encoding_id;
+ pdf_obj *fontdict, *descriptor;
+ sfnt *sfont;
+ int embedding = 1; /* Must be embedded. */
+ FILE *fp = NULL;
+ int length, error = 0;
+
+ ASSERT( font );
+
+ ident = pdf_font_get_ident(font);
+ index = pdf_font_get_index(font);
+
+ ASSERT( ident );
+
+#ifdef XETEX
+ sfont = sfnt_open(pdf_font_get_ft_face(font), SFNT_TYPE_TTC | SFNT_TYPE_TRUETYPE);
+ if (!sfont)
+ return -1;
+#else
+ fp = DPXFOPEN(ident, DPX_RES_TYPE_TTFONT);
+ if (!fp) {
+ fp = DPXFOPEN(ident, DPX_RES_TYPE_DFONT);
+ if (!fp) return -1;
+ sfont = dfont_open(fp, index);
+ } else {
+ sfont = sfnt_open(fp);
+ }
+#endif
+
+ if (!sfont) {
+ WARN("Could not open TrueType font: %s", ident);
+ if (fp)
+ DPXFCLOSE(fp);
+ return -1;
+ }
+
+ if (sfont->type == SFNT_TYPE_TTC) {
+ unsigned long offset;
+ offset = ttc_read_offset(sfont, index);
+ if (offset == 0) ERROR("Invalid TTC index in %s.", ident);
+ error = sfnt_read_table_directory(sfont, offset);
+ } else {
+ error = sfnt_read_table_directory(sfont, sfont->offset);
+ }
+
+ if (error) {
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+ return -1; /* Silently */
+ }
+
+ /* Reading fontdict before checking fonttype conflicts with PKFONT
+ * because pdf_font_get_resource() always makes a dictionary.
+ */
+ encoding_id = pdf_font_get_encoding(font);
+ fontdict = pdf_font_get_resource(font);
+ descriptor = pdf_font_get_descriptor(font);
+#ifdef ENABLE_NOEMBED
+ embedding = pdf_font_get_flag(font, PDF_FONT_FLAG_NOEMBED) ? 0 : 1;
+#endif /* ENABLE_NOEMBED */
+
+ ASSERT( fontdict && descriptor );
+
+ {
+ char fontname[256];
+ int n;
+ pdf_obj *tmp;
+
+ memset(fontname, 0, 256);
+ length = tt_get_ps_fontname(sfont, fontname, 255);
+ if (length < 1) {
+ length = MIN(strlen(ident), 255);
+ strncpy(fontname, ident, length);
+ }
+ fontname[length] = '\0';
+ for (n = 0; n < length; n++) {
+ if (fontname[n] == 0) {
+ memmove(fontname + n, fontname + n + 1, length - n - 1);
+ }
+ }
+ if (strlen(fontname) == 0)
+ ERROR("Can't find valid fontname for \"%s\".", ident);
+ pdf_font_set_fontname(font, fontname);
+
+ tmp = tt_get_fontdesc(sfont, &embedding, -1, 1, fontname);
+ if (!tmp) {
+ ERROR("Could not obtain necessary font info.");
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+ return -1;
+ }
+ ASSERT(pdf_obj_typeof(tmp) == PDF_DICT);
+
+ pdf_merge_dict(descriptor, tmp);
+ pdf_release_obj(tmp);
+ }
+
+ if (!embedding) {
+ if (encoding_id >= 0 &&
+ !pdf_encoding_is_predefined(encoding_id)) {
+ ERROR("Custom encoding not allowed for non-embedded TrueType font.");
+ sfnt_close(sfont);
+ return -1;
+ } else {
+ /* There are basically no guarantee for font substitution
+ * can work with "symblic" fonts. At least all glyphs
+ * contained in the font must be identified; glyphs covers
+ * by this instance of font should contain glyphs only from
+ * Adobe Standard Latin Set. We allow non-embedded font
+ * only to predefined encodings for this reason. Note that
+ * "builtin" encoding means "MacRoman" here.
+ */
+ pdf_obj *tmp;
+ long flags;
+
+#ifndef ENABLE_NOEMBED
+ ERROR("Font file=\"%s\" can't be embedded due to liscence restrictions.", ident);
+#endif /* ENABLE_NOEMBED */
+ pdf_font_set_flags(font, PDF_FONT_FLAG_NOEMBED);
+ tmp = pdf_lookup_dict(descriptor, "Flags");
+ if (tmp && pdf_obj_typeof(tmp) == PDF_NUMBER) {
+ flags = (long) pdf_number_value(tmp);
+ flags &= (1 << 2); /* clear Symbolic */
+ flags |= (1 << 5); /* set Nonsymbolic */
+ pdf_add_dict(descriptor, pdf_new_name("Flags"), pdf_new_number(flags));
+ }
+ }
+ }
+
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+
+ pdf_add_dict(fontdict,
+ pdf_new_name("Type"), pdf_new_name("Font"));
+ pdf_add_dict(fontdict,
+ pdf_new_name("Subtype"), pdf_new_name("TrueType"));
+
+ return 0;
+}
+
+/*
+ * The 'name' table should be preserved since it contains copyright
+ * information, but it might cause problem when there are invalid
+ * table entries (wrongly encoded text which is often the case in
+ * CJK fonts). Acrobat does not use 'name' table. Unicode TrueType
+ * fonts may have 10K bytes 'name' table...
+ *
+ * We preserve the 'OS/2' table too, since it contains the license
+ * information. PDF applications should use this table to decide
+ * whether the font is embedded only for the purpose of preview &
+ * printing. Otherwise, we must encrypt the document. Acrobat does
+ * not use 'OS/2' table, though...
+ */
+static struct
+{
+ const char *name;
+ int must_exist;
+} required_table[] = {
+ {"OS/2", 0}, {"head", 1}, {"hhea", 1}, {"loca", 1}, {"maxp", 1},
+ {"name", 1}, {"glyf", 1}, {"hmtx", 1}, {"fpgm", 0}, {"cvt ", 0},
+ {"prep", 0}, {"cmap", 1}, {NULL, 0}
+};
+
+static void
+do_widths (pdf_font *font, double *widths)
+{
+ pdf_obj *fontdict;
+ pdf_obj *tmparray;
+ int code, firstchar, lastchar, tfm_id;
+ char *usedchars;
+
+ fontdict = pdf_font_get_resource (font);
+ usedchars = pdf_font_get_usedchars (font);
+
+ tmparray = pdf_new_array();
+ for (firstchar = 255, lastchar = 0, code = 0; code < 256; code++) {
+ if (usedchars[code]) {
+ if (code < firstchar) firstchar = code;
+ if (code > lastchar) lastchar = code;
+ }
+ }
+ if (firstchar > lastchar) {
+ WARN("No glyphs actually used???");
+ pdf_release_obj(tmparray);
+ return;
+ }
+ tfm_id = tfm_open(pdf_font_get_mapname(font), 0);
+ for (code = firstchar; code <= lastchar; code++) {
+ if (usedchars[code]) {
+ double width;
+ if (tfm_id < 0) /* tfm is not found */
+ width = widths[code];
+ else
+ width = 1000. * tfm_get_width(tfm_id, code);
+ pdf_add_array(tmparray,
+ pdf_new_number(ROUND(width, 0.1)));
+ } else {
+ pdf_add_array(tmparray, pdf_new_number(0.0));
+ }
+ }
+
+ if (pdf_array_length(tmparray) > 0) {
+ pdf_add_dict(fontdict,
+ pdf_new_name("Widths"), pdf_ref_obj(tmparray));
+ }
+ pdf_release_obj(tmparray);
+
+ pdf_add_dict(fontdict,
+ pdf_new_name("FirstChar"), pdf_new_number(firstchar));
+ pdf_add_dict(fontdict,
+ pdf_new_name("LastChar"), pdf_new_number(lastchar));
+
+ return;
+}
+
+static int verbose = 0;
+
+#define PDFUNIT(v) ((double) (ROUND(1000.0*(v)/(glyphs->emsize), 1)))
+
+/*
+ * There are several issues in TrueType font support in PDF.
+ * How PDF viewers select TrueType cmap table is not so clear.
+ * Most reliable way seem to reencode font and sort glyphs as
+ * charcode == gid and to use Mac-Roman format 0 subtable.
+ * It does not work with encodings that uses full 256 range since
+ * GID = 0 is reserved for .notdef, so GID = 256 is not accessible.
+ */
+static int
+do_builtin_encoding (pdf_font *font, const char *usedchars, sfnt *sfont)
+{
+ struct tt_glyphs *glyphs;
+ char *cmap_table;
+ tt_cmap *ttcm;
+ USHORT gid, idx;
+ int code, count;
+ double widths[256];
+
+ ttcm = tt_cmap_read(sfont, TT_MAC, TT_MAC_ROMAN);
+ if (!ttcm) {
+ WARN("Could not read Mac-Roman TrueType cmap table...");
+ return -1;
+ }
+
+ cmap_table = NEW(274, char);
+ memset(cmap_table, 0, 274);
+ sfnt_put_ushort(cmap_table, 0); /* Version */
+ sfnt_put_ushort(cmap_table+2, 1); /* Number of subtables */
+ sfnt_put_ushort(cmap_table+4, TT_MAC); /* Platform ID */
+ sfnt_put_ushort(cmap_table+6, TT_MAC_ROMAN); /* Encoding ID */
+ sfnt_put_ulong (cmap_table+8, 12); /* Offset */
+ sfnt_put_ushort(cmap_table+12, 0); /* Format */
+ sfnt_put_ushort(cmap_table+14, 262); /* Length */
+ sfnt_put_ushort(cmap_table+16, 0); /* Language */
+
+ glyphs = tt_build_init();
+
+ if (verbose > 2)
+ MESG("[glyphs:/.notdef");
+
+ count = 1; /* .notdef */
+ for (code = 0; code < 256; code++) {
+ if (!usedchars[code])
+ continue;
+
+ if (verbose > 2)
+ MESG("/.c0x%02x", code);
+
+ gid = tt_cmap_lookup(ttcm, code);
+ if (gid == 0) {
+ WARN("Glyph for character code=0x%02x missing in font font-file=\"%s\".",
+ code, pdf_font_get_ident(font));
+ idx = 0;
+ } else {
+ idx = tt_find_glyph(glyphs, gid);
+ if (idx == 0)
+ idx = tt_add_glyph(glyphs, (USHORT)gid, (USHORT)count); /* count returned. */
+ }
+ cmap_table[18+code] = idx & 0xff; /* bug here */
+ count++;
+ }
+ tt_cmap_release(ttcm);
+
+ if (verbose > 2)
+ MESG("]");
+
+ if (tt_build_tables(sfont, glyphs) < 0) {
+ WARN("Packing TrueType font into SFNT failed!");
+ tt_build_finish(glyphs);
+ RELEASE(cmap_table);
+ return -1;
+ }
+
+ for (code = 0; code < 256; code++) {
+ if (usedchars[code]) {
+ idx = tt_get_index(glyphs, (USHORT) cmap_table[18+code]);
+ widths[code] = PDFUNIT(glyphs->gd[idx].advw);
+ } else {
+ widths[code] = 0.0;
+ }
+ }
+ do_widths(font, widths);
+
+ if (verbose > 1)
+ MESG("[%d glyphs]", glyphs->num_glyphs);
+
+ tt_build_finish(glyphs);
+
+ sfnt_set_table(sfont, "cmap", cmap_table, 274);
+
+ return 0;
+}
+
+/* Order of lookup should be
+ * post, unicode+otl
+ */
+struct glyph_mapper
+{
+ tt_cmap *codetogid;
+ otl_gsub *gsub;
+ sfnt *sfont;
+ struct tt_post_table *nametogid;
+};
+
+
+/* WARNING: This modifies glyphname itself */
+static int
+agl_decompose_glyphname (char *glyphname, char **nptrs, int size, char **suffix)
+{
+ char *q, *p = glyphname;
+ int n;
+
+ q = strchr(p, '.'); /* chop every thing after *first* dot */
+ if (!q)
+ *suffix = NULL;
+ else {
+ *q = '\0'; q++;
+ *suffix = q;
+ }
+
+ nptrs[0] = p;
+ for (n = 1; p && *p; n++) {
+ p = strchr(p, '_');
+ if (!p || p[1] == '\0')
+ break;
+ if (n >= size)
+ ERROR("Uh ah..."); /* _FIXME_ */
+ *p = '\0'; p++;
+ nptrs[n] = p;
+ }
+
+ return n;
+}
+
+static int
+select_gsub (const char *feat, struct glyph_mapper *gm)
+{
+ int idx, error = 0;
+
+ if (!feat || *feat == 0 || !gm || !gm->gsub)
+ return -1;
+
+ /* First treat as is */
+ idx = otl_gsub_select(gm->gsub, "*", "*", feat);
+ if (idx >= 0)
+ return 0;
+
+ if (verbose > 1)
+ MESG("\ntrutype>> Try loading OTL GSUB for \"*.*.%s\"...", feat);
+ error = otl_gsub_add_feat(gm->gsub, "*", "*", feat, gm->sfont);
+ if (!error) {
+ idx = otl_gsub_select(gm->gsub, "*", "*", feat);
+ return (idx >= 0 ? 0 : -1);
+ }
+
+ return -1;
+}
+
+static int findparanoiac (const char *glyph_name, USHORT *gid, struct glyph_mapper *gm);
+static int resolve_glyph (const char *glyph_name, USHORT *gid, struct glyph_mapper *gm);
+
+/* Apply GSUB. This is a bit tricky... */
+static int
+selectglyph (USHORT in, const char *suffix, struct glyph_mapper *gm, USHORT *out)
+{
+ char *s, *q, t[5];
+ const char *r;
+ int n, error = 0;
+
+ ASSERT(suffix && gm && out);
+ ASSERT(suffix && *suffix != 0);
+
+ s = NEW(strlen(suffix) + 1, char);
+ strcpy(s, suffix);
+
+ /* First try converting suffix to feature tag.
+ * agl.c currently only knows less ambiguos cases;
+ * e.g., 'sc', 'superior', etc.
+ */
+ r = agl_suffix_to_otltag(s);
+ if (r) { /* We found feature tag for 'suffix'. */
+ error = select_gsub(r, gm); /* no fallback for this */
+ if (!error)
+ error = otl_gsub_apply(gm->gsub, &in);
+ } else { /* 'suffix' may represent feature tag. */
+ /* Try loading GSUB only when length of 'suffix' is less
+ * than or equal to 4. tt_gsub give a warning otherwise.
+ */
+ if (strlen(s) > 4)
+ error = -1; /* Uh */
+ else if (strlen(s) == 4)
+ error = select_gsub(s, gm);
+ else { /* less than 4. pad ' '. */
+ memset(t, ' ', 4); t[4] = '\0';
+ memcpy(t, s, strlen(s));
+ error = select_gsub(t, gm);
+ }
+ if (!error) /* 'suffix' represents feature tag. */
+ error = otl_gsub_apply(gm->gsub, &in);
+ else { /* other case: alt1, nalt10... (alternates) */
+ for (q = s + strlen(s) - 1; q > s && *q >= '0' && *q <= '9'; q--);
+ if (q == s)
+ error = -1;
+ else { /* starting at 1 */
+ n = atoi(q + 1) - 1; q[1] = '\0';
+ if (strlen(s) > 4)
+ error = -1;
+ else { /* This may be alternate substitution. */
+ memset(t, ' ', 4); t[4] = '\0';
+ memcpy(t, s, strlen(s));
+ error = select_gsub(s, gm);
+ if (!error)
+ error = otl_gsub_apply_alt(gm->gsub, (USHORT)n, (USHORT *)&in);
+ }
+ }
+ }
+ }
+ RELEASE(s);
+
+ *out = in;
+ return error;
+}
+
+
+/* Compose glyphs via ligature substitution. */
+static int
+composeglyph (USHORT *glyphs, int n_glyphs,
+ const char *feat, struct glyph_mapper *gm, USHORT *gid)
+{
+ int error = 0;
+ char t[5] = {' ', ' ', ' ', ' ', 0};
+
+ ASSERT(glyphs && n_glyphs > 0 && gm && gid);
+
+ if (!feat || feat[0] == '\0') /* meaning "Unknown" */
+ error = select_gsub("(?lig|lig?|?cmp|cmp?|frac|afrc)", gm);
+ else {
+ if (strlen(feat) > 4)
+ error = -1;
+ else {
+ memcpy(t, feat, strlen(feat));
+ error = select_gsub(t, gm);
+ }
+ }
+
+ if (!error)
+ error = otl_gsub_apply_lig(gm->gsub, (USHORT *)glyphs, (USHORT)n_glyphs,
+ (USHORT *)gid);
+
+ return error;
+}
+
+/* This may be called by findparanoiac(). */
+static int
+composeuchar (long *unicodes, int n_unicodes,
+ const char *feat, struct glyph_mapper *gm, USHORT *gid)
+{
+ USHORT *gids;
+ int i, error = 0;
+
+ if (!gm->codetogid)
+ return -1;
+
+ gids = NEW(n_unicodes, USHORT);
+ for (i = 0;
+ !error && i < n_unicodes; i++) {
+ gids[i] = tt_cmap_lookup(gm->codetogid, unicodes[i]);
+ error = (gids[i] == 0) ? -1 : 0;
+ }
+
+ if (!error)
+ error = composeglyph(gids, n_unicodes, feat, gm, gid);
+
+ RELEASE(gids);
+
+ return error;
+}
+
+/* Search 'post' table. */
+static int
+findposttable (const char *glyph_name, USHORT *gid, struct glyph_mapper *gm)
+{
+ if (!gm->nametogid)
+ return -1;
+
+ *gid = tt_lookup_post_table(gm->nametogid, glyph_name);
+#if 0
+ if (verbose > 1)
+ {
+ if (*gid > 0)
+ MESG("%s =post=> 0x%04X\n", glyph_name, *gid);
+ }
+#endif
+
+ return (*gid == 0 ? -1 : 0);
+}
+
+/* This is wrong. We must care about '.'. */
+#define is_comp(n) (strchr((n), '_') != NULL)
+
+/* Glyph names are concatinated with '_'. */
+static int
+findcomposite (const char *glyphname, USHORT *gid, struct glyph_mapper *gm)
+{
+ char *gname, *suffix = NULL;
+ USHORT gids[32];
+ char *nptrs[32];
+ int i, n_comp;
+ int error = 0;
+
+ error = findposttable(glyphname, gid, gm);
+ if (!error)
+ return 0;
+
+ gname = NEW(strlen(glyphname) + 1, char);
+ strcpy(gname, glyphname);
+
+ memset(gids, 0, 32 * sizeof(USHORT));
+ n_comp = agl_decompose_glyphname(gname, nptrs, 32, &suffix);
+ for (error = 0, i = 0; !error && i < n_comp; i++) {
+ error = resolve_glyph(nptrs[i], &gids[i], gm);
+ if (error)
+ WARN("Could not resolve glyph \"%s\" (%dth component of glyph \"%s\").",
+ nptrs[i], i, glyphname);
+ }
+
+ if (!error) {
+ if (suffix &&
+ (!strcmp(suffix, "liga") || !strcmp(suffix, "dlig") ||
+ !strcmp(suffix, "hlig") || !strcmp(suffix, "frac") ||
+ !strcmp(suffix, "ccmp") || !strcmp(suffix, "afrc")
+ )
+ ) {
+ error = composeglyph(gids, n_comp, suffix, gm, gid);
+ } else { /* first try composing glyph */
+ error = composeglyph(gids, n_comp, NULL, gm, gid);
+ if (!error && suffix) /* a_b_c.vert */
+ error = selectglyph(*gid, suffix, gm, gid);
+ }
+ }
+ RELEASE(gname);
+
+ return error;
+}
+
+/* glyphname should not have suffix here */
+static int
+findparanoiac (const char *glyphname, USHORT *gid, struct glyph_mapper *gm)
+{
+ agl_name *agln;
+ USHORT idx = 0U;
+ int error = 0;
+
+ agln = agl_lookup_list(glyphname);
+ while (agln && idx == 0) {
+ if (agln->suffix) {
+ error = findparanoiac(agln->name, &idx, gm);
+ if (error)
+ return error;
+
+ error = selectglyph(idx, agln->suffix, gm, &idx);
+ if (error) {
+ WARN("Variant \"%s\" for glyph \"%s\" might not be found.",
+ agln->suffix, agln->name);
+ WARN("Using glyph name without suffix instead...");
+ error = 0; /* ignore */
+ }
+ } else {
+ if (agln->n_components == 1)
+ idx = tt_cmap_lookup(gm->codetogid, agln->unicodes[0]);
+ else if (agln->n_components > 1) {
+ if (verbose >= 0) /* give warning */
+ WARN("Glyph \"%s\" looks like a composite glyph...",
+ agln->name);
+ error = composeuchar(agln->unicodes, agln->n_components, NULL, gm, &idx);
+ if (verbose >= 0) {
+ if (error)
+ WARN("Not found...");
+ else {
+ int _i, _n = 0;
+ char *_p, _buf[256];
+ WARN(">> Composite glyph glyph-name=\"%s\" found at glyph-id=\"%u\".",
+ agln->name, idx);
+ for (_p = _buf, _i = 0; _i < agln->n_components && _n < 245; _i++) {
+ _p[_n++] = _i == 0 ? '<' : ' ';
+ if (agln->unicodes[_i] >= 0x10000)
+ _n += sprintf(_p+_n, "U+%06lX", agln->unicodes[_i]);
+ else
+ _n += sprintf(_p+_n, "U+%04lX", agln->unicodes[_i]);
+ _p[_n++] = _i == agln->n_components - 1 ? '>' : ',';
+ }
+ _p[_n++] = '\0';
+ WARN(">> Input Unicode seq.=\"%s\" ==> glyph-id=\"%u\" in font-file=\"_please_try_-v_\".", _buf, idx);
+ }
+ }
+ } else ASSERT(0); /* Boooo */
+ }
+ agln = agln->alternate;
+ }
+
+ *gid = idx;
+ return (idx == 0 ? -1 : 0);
+}
+
+static int
+resolve_glyph (const char *glyphname, USHORT *gid, struct glyph_mapper *gm)
+{
+ int error = 0;
+ char *name, *suffix = NULL;
+ long ucv;
+
+ ASSERT(glyphname);
+
+ /*
+ * First we try glyph name to GID mapping using post table if post table
+ * is available. If post table is not available or glyph is not listed
+ * in the post table, then we try Unicode if Windows-Unicode TrueType
+ * cmap is available.
+ */
+ error = findposttable(glyphname, gid, gm);
+ if (!error)
+ return 0;
+
+ if (!gm->codetogid)
+ return -1;
+
+ name = agl_chop_suffix(glyphname, &suffix);
+ if (!name) /* .notdef, .foo */
+ error = -1;
+ else if (agl_name_is_unicode(name)) {
+ ucv = agl_name_convert_unicode(name);
+ *gid = tt_cmap_lookup(gm->codetogid, ucv);
+ error = (*gid == 0) ? -1 : 0;
+ } else {
+ error = findparanoiac(name, gid, gm);
+ }
+ if (!error && suffix) {
+ error = selectglyph(*gid, suffix, gm, gid);
+ if (error) {
+ WARN("Variant \"%s\" for glyph \"%s\" might not be found.",
+ suffix, name);
+ WARN("Using glyph name without suffix instead...");
+ error = 0; /* ignore */
+ }
+ }
+ if (suffix)
+ RELEASE(suffix);
+ if (name)
+ RELEASE(name);
+
+ return error;
+}
+
+/* Things are complicated. We still need to use PostScript
+ * glyph names. But OpenType fonts may not have PS name to
+ * glyph mapping. We use Unicode plus OTL GSUB for finding
+ * glyphs in this case.
+ */
+static int
+setup_glyph_mapper (struct glyph_mapper *gm, sfnt *sfont)
+{
+ gm->sfont = sfont;
+ gm->nametogid = tt_read_post_table(sfont);
+ gm->codetogid = tt_cmap_read(sfont, TT_WIN, TT_WIN_UCS4);
+ if (!gm->codetogid)
+ gm->codetogid = tt_cmap_read(sfont, TT_WIN, TT_WIN_UNICODE);
+
+ if (!gm->nametogid && !gm->codetogid)
+ return -1;
+
+ gm->gsub = otl_gsub_new();
+
+ return 0;
+}
+
+static void
+clean_glyph_mapper (struct glyph_mapper *gm)
+{
+ if (gm->gsub)
+ otl_gsub_release(gm->gsub);
+ if (gm->codetogid)
+ tt_cmap_release (gm->codetogid);
+ if (gm->nametogid)
+ tt_release_post_table(gm->nametogid);
+
+ gm->gsub = NULL;
+ gm->codetogid = NULL;
+ gm->nametogid = NULL;
+ gm->sfont = NULL;
+
+ return;
+}
+
+static int
+do_custom_encoding (pdf_font *font,
+ char **encoding, const char *usedchars, sfnt *sfont)
+{
+ struct tt_glyphs *glyphs;
+ char *cmap_table;
+ int code, count;
+ double widths[256];
+ struct glyph_mapper gm;
+ USHORT idx, gid;
+ int error = 0;
+
+ ASSERT(font && encoding && usedchars && sfont);
+
+ error = setup_glyph_mapper(&gm, sfont);
+ if (error) {
+ WARN("No post table nor Unicode cmap found in font: %s",
+ pdf_font_get_ident(font));
+ WARN(">> I can't find glyphs without this!");
+ return -1;
+ }
+
+ cmap_table = NEW(274, char);
+ memset(cmap_table, 0, 274);
+ sfnt_put_ushort(cmap_table, 0); /* Version */
+ sfnt_put_ushort(cmap_table+2, 1); /* Number of subtables */
+ sfnt_put_ushort(cmap_table+4, TT_MAC); /* Platform ID */
+ sfnt_put_ushort(cmap_table+6, TT_MAC_ROMAN); /* Encoding ID */
+ sfnt_put_ulong (cmap_table+8, 12); /* Offset */
+ sfnt_put_ushort(cmap_table+12, 0); /* Format */
+ sfnt_put_ushort(cmap_table+14, 262); /* Length */
+ sfnt_put_ushort(cmap_table+16, 0); /* Language */
+
+ glyphs = tt_build_init();
+
+ count = 1; /* +1 for .notdef */
+ for (code = 0; code < 256; code++) {
+ if (!usedchars[code])
+ continue;
+
+ if (!encoding[code] || !strcmp(encoding[code], ".notdef")) {
+ WARN("Character code=\"0x%02X\" mapped to \".notdef\" glyph used in font font-file=\"%s\"",
+ code, pdf_font_get_ident(font));
+ WARN(">> Maybe incorrect encoding specified?");
+ idx = 0;
+ } else {
+ if (is_comp(encoding[code]))
+ error = findcomposite(encoding[code], &gid, &gm);
+ else
+ error = resolve_glyph(encoding[code], &gid, &gm);
+
+ /*
+ * Older versions of gs had problem with glyphs (other than .notdef)
+ * mapped to gid = 0.
+ */
+ if (error) {
+ WARN("Glyph \"%s\" not available in font \"%s\".",
+ encoding[code], pdf_font_get_ident(font));
+ } else {
+ if (verbose > 1)
+ MESG("truetype>> Glyph glyph-name=\"%s\" found at glyph-id=\"%u\".\n", encoding[code], gid);
+ }
+ idx = tt_find_glyph(glyphs, gid);
+ if (idx == 0) {
+ idx = tt_add_glyph(glyphs, (USHORT)gid, (USHORT)count); /* count returned. */
+ count++;
+ }
+ }
+ cmap_table[18 + code] = idx & 0xff; /* bug here */
+ }
+ clean_glyph_mapper(&gm);
+
+ if (tt_build_tables(sfont, glyphs) < 0) {
+ WARN("Packing TrueType font into SFNT file faild..."); /* _FIXME_: wrong message */
+ tt_build_finish(glyphs);
+ RELEASE(cmap_table);
+ return -1;
+ }
+
+ for (code = 0; code < 256; code++) {
+ if (usedchars[code]) {
+ idx = tt_get_index(glyphs, (USHORT) cmap_table[18+code]);
+ widths[code] = PDFUNIT(glyphs->gd[idx].advw);
+ } else {
+ widths[code] = 0.0;
+ }
+ }
+ do_widths(font, widths);
+
+ if (verbose > 1)
+ MESG("[%d glyphs]", glyphs->num_glyphs);
+
+ tt_build_finish(glyphs);
+
+ sfnt_set_table(sfont, "cmap", cmap_table, 274);
+
+ return 0;
+}
+
+int
+pdf_font_load_truetype (pdf_font *font)
+{
+ pdf_obj *descriptor = pdf_font_get_descriptor(font);
+ char *ident = pdf_font_get_ident(font);
+ int encoding_id = pdf_font_get_encoding(font);
+ char *usedchars = pdf_font_get_usedchars(font);
+#ifdef ENABLE_NOEMBED
+ int embedding = pdf_font_get_flag(font, PDF_FONT_FLAG_NOEMBED) ? 0 : 1;
+#endif /* ENABLE_NOEMBED */
+ int index = pdf_font_get_index(font);
+ char **enc_vec;
+ pdf_obj *fontfile;
+ FILE *fp = NULL;
+ sfnt *sfont;
+ int i, error = 0;
+
+ if (!pdf_font_is_in_use(font))
+ return 0;
+
+ verbose = pdf_font_get_verbose();
+
+#ifdef XETEX
+ sfont = sfnt_open(pdf_font_get_ft_face(font), SFNT_TYPE_TTC | SFNT_TYPE_TRUETYPE);
+#else
+ if (!fp) {
+ fp = DPXFOPEN(ident, DPX_RES_TYPE_DFONT);
+ if (!fp) ERROR("Unable to open TrueType/dfont font file: %s", ident); /* Should find *truetype* here */
+ sfont = dfont_open(fp, index);
+ } else {
+ sfont = sfnt_open(fp);
+ }
+#endif
+
+ if (!sfont) {
+ ERROR("Unable to open TrueType/dfont file: %s", ident);
+ if (fp)
+ DPXFCLOSE(fp);
+ return -1;
+ } else if (sfont->type != SFNT_TYPE_TRUETYPE &&
+ sfont->type != SFNT_TYPE_TTC &&
+ sfont->type != SFNT_TYPE_DFONT) {
+ ERROR("Font \"%s\" not a TrueType/dfont font?", ident);
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+ return -1;
+ }
+
+ if (sfont->type == SFNT_TYPE_TTC) {
+ unsigned long offset;
+ offset = ttc_read_offset(sfont, index);
+ if (offset == 0) ERROR("Invalid TTC index in %s.", ident);
+ error = sfnt_read_table_directory(sfont, ttc_read_offset(sfont, offset));
+ } else {
+ error = sfnt_read_table_directory(sfont, sfont->offset);
+ }
+
+ if (error) {
+ ERROR("Reading SFND table dir failed for font-file=\"%s\"... Not a TrueType font?", ident);
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+ return -1;
+ }
+
+ /*
+ * Create new TrueType cmap table with MacRoman encoding.
+ */
+ if (encoding_id < 0)
+ error = do_builtin_encoding(font, usedchars, sfont);
+ else {
+ enc_vec = pdf_encoding_get_encoding(encoding_id);
+ error = do_custom_encoding(font, enc_vec, usedchars, sfont);
+ }
+ if (error) {
+ ERROR("Error occured while creating font subfont for \"%s\"", ident);
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+ return -1;
+ }
+
+#if ENABLE_NOEMBED
+ if (!embedding) {
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+ return 0;
+ }
+#endif /* ENABLE_NOEMBED */
+
+ /*
+ * TODO: post table?
+ */
+
+ for (i = 0; required_table[i].name != NULL; i++) {
+ if (sfnt_require_table(sfont,
+ required_table[i].name,
+ required_table[i].must_exist) < 0) {
+ ERROR("Required TrueType table \"%s\" does not exist in font: %s",
+ required_table[i].name, ident);
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+ return -1;
+ }
+ }
+
+ /*
+ * FontFile2
+ */
+ fontfile = sfnt_create_FontFile_stream(sfont);
+ if (!fontfile)
+ ERROR("Could not created FontFile stream for \"%s\".", ident);
+
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+
+ if (verbose > 1)
+ MESG("[%ld bytes]", pdf_stream_length(fontfile));
+
+ pdf_add_dict(descriptor,
+ pdf_new_name("FontFile2"), pdf_ref_obj(fontfile)); /* XXX */
+ pdf_release_obj(fontfile);
+
+ return 0;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/tt_aux.c b/Build/source/texk/dvipdf-x/xsrc/tt_aux.c
new file mode 100644
index 00000000000..4a07da531e7
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/tt_aux.c
@@ -0,0 +1,294 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif /* HAVE_CONFIG_H */
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+#include "numbers.h"
+
+#include "pdfobj.h"
+
+#include "sfnt.h"
+#include "tt_table.h"
+#include "tt_post.h"
+#include "tt_aux.h"
+
+static int verbose = 0;
+
+void tt_aux_set_verbose(void)
+{
+ ++verbose;
+}
+
+ULONG ttc_read_offset (sfnt *sfont, int ttc_idx)
+{
+ ULONG offset = 0, num_dirs = 0;
+
+ if (sfont == NULL ||
+#ifdef XETEX
+ sfont->ft_face == NULL
+#else
+ sfont->stream == NULL
+#endif
+ )
+ ERROR("file not opened");
+
+ if (sfont->type != SFNT_TYPE_TTC)
+ ERROR("ttc_read_offset(): invalid font type");
+
+ sfnt_seek_set (sfont, 4); /* skip version tag */
+
+ /* version = */ sfnt_get_ulong(sfont);
+ num_dirs = sfnt_get_ulong(sfont);
+ if (ttc_idx < 0 || ttc_idx > num_dirs - 1)
+ ERROR("Invalid TTC index number");
+
+ sfnt_seek_set (sfont, 12 + ttc_idx * 4);
+ offset = sfnt_get_ulong (sfont);
+
+ return offset;
+}
+
+/*
+ Build FontDescriptor (except FontName) from TrueType tables:
+
+ Most information found in FontDescriptor is used only when automatic
+ font substitution is needed. (in the case of missing/broken font data)
+ Some PDF viewers may ignore embedded TrueType glyph data. Especially,
+ any embedded TrueType data for CID-keyed (CIDFontType 2) font is ignored
+ by PDF viewers that only support PDF versions 1.2 or earlier.
+
+ We use those tables to obtain various values of FontDescriptor.
+
+ head: required
+
+ xMin, xMax, yMin, yMax - FontBBox
+ unitsPerEm - conversion to PDF unit (points). see PDFUNIT bellow.
+ The head table must exist in any TrueType font.
+
+ hhea: required
+
+ When the OS/2 table (Windows and OS/2 only) is not available,
+ Ascender and Descender values can be used to estimate Ascent
+ and Descent. The hhea table is required for all TrueType fonts.
+ MaxWidth can be obtained from this table.
+
+ OS/2: required for Windows and OS/2 TrueType, and OpenType
+
+ fsType - liscensing information
+ sCapHeight - CapHeight (version 2 only)
+
+ The sCapHeight is only available in newer TrueType fonts which has
+ version 2 OS/2 table and generally not available. Instead, we can
+ use height of uppercase letter `H'. But we don't use it, we simply
+ use Ascent value.
+
+ sTypoAscender, sTypoDescender - Ascent and Descent
+ usWeightClass - roughly estimate StemV.
+
+ Estimation is based on the following expression:
+
+ stemv = (os2->usWeightClass/65)*(os2->usWeightClass/65)+50
+
+ . I've found this expression in some Adobe document (lost). We use
+ this expression also, otherwise, we must analyze glyph data.
+
+ xAvgCharWidth - AvgWidth (optional)
+ sFamilyClass - Flags
+ sFamilyClass and panose - Panose in Style dictionary (optional)
+
+ post: required
+
+ italicAngle - ItalicAngle
+
+*/
+
+
+#ifndef PDFUNIT
+#define PDFUNIT(v) (ROUND((1000.0*(v))/(head->unitsPerEm),1))
+#endif
+
+/* Flags: should not come here */
+#define FIXEDWIDTH (1 << 0) /* Fixed-width font */
+#define SERIF (1 << 1) /* Serif font */
+#define SYMBOLIC (1 << 2) /* Symbolic font */
+#define SCRIPT (1 << 3) /* Script font */
+#define STANDARD (1 << 5) /* Uses the Adobe Standard Character Set */
+#define ITALIC (1 << 6) /* Italic */
+#define ALLCAP (1 << 16) /* All-cap font */
+#define SMALLCAP (1 << 17) /* Small-cap font */
+#define FORCEBOLD (1 << 18) /* Force bold at small text sizes */
+pdf_obj *tt_get_fontdesc (sfnt *sfont, int *embed, int stemv, int type, const char* fontname)
+{
+ pdf_obj *descriptor = NULL;
+ pdf_obj *bbox = NULL;
+ int flag = SYMBOLIC;
+ /* TrueType tables */
+ struct tt_head_table *head;
+ struct tt_os2__table *os2;
+ struct tt_post_table *post;
+
+ if (!sfont) {
+ ERROR("font file not opened");
+ }
+
+ os2 = tt_read_os2__table(sfont);
+ head = tt_read_head_table(sfont);
+ post = tt_read_post_table(sfont);
+ if (!post) {
+ RELEASE(os2);
+ RELEASE(head);
+ return NULL;
+ }
+
+ descriptor = pdf_new_dict();
+ pdf_add_dict (descriptor,
+ pdf_new_name ("Type"),
+ pdf_new_name ("FontDescriptor"));
+
+ if (*embed && os2) {
+ /*
+ License:
+
+ "Preview & Print embedding" (0x004) requires the document containing
+ Preview & Print font to be opened in read-only mode. However, licensing
+ information are lost when fonts are embedded in PDF document and
+ the only way to make the PDF document "read-only" is to encrypt it.
+ But we have no support for encryption yet. We do not embed any fonts
+ with "Preview & Print embedding" setting.
+
+ 2001/11/22: Changed to allow `Preview & Print' only fonts embedding
+
+ 2006/04/19: Added support for always_embed option
+ */
+ if (os2->fsType == 0x0000 || (os2->fsType & 0x0008)) {
+ /* the least restrictive license granted takes precedence. */
+ *embed = 1;
+ } else if (os2->fsType & 0x0004) {
+ if (verbose > 0)
+ MESG("** NOTICE: Font \"%s\" permits \"Preview & Print\" embedding only **\n", fontname);
+ *embed = 1;
+ } else {
+ if (always_embed) {
+ MESG("** NOTICE: Font \"%s\" may be subject to embedding restrictions **\n", fontname);
+ *embed = 1;
+ }
+ else {
+ WARN("Embedding of font \"%s\" disabled due to license restrictions", fontname);
+ *embed = 0;
+ }
+ }
+ }
+
+ if (os2) {
+ pdf_add_dict (descriptor,
+ pdf_new_name ("Ascent"),
+ pdf_new_number (PDFUNIT(os2->sTypoAscender)));
+ pdf_add_dict (descriptor,
+ pdf_new_name ("Descent"),
+ pdf_new_number (PDFUNIT(os2->sTypoDescender)));
+ if (stemv < 0) /* if not given by the option '-v' */
+ stemv = (os2->usWeightClass/65.)*(os2->usWeightClass/65.)+50;
+ pdf_add_dict (descriptor,
+ pdf_new_name ("StemV"),
+ pdf_new_number (stemv));
+ if (os2->version == 0x0002) {
+ pdf_add_dict (descriptor,
+ pdf_new_name("CapHeight"),
+ pdf_new_number(PDFUNIT(os2->sCapHeight))
+ );
+ /* optional */
+ pdf_add_dict (descriptor,
+ pdf_new_name("XHeight"),
+ pdf_new_number(PDFUNIT(os2->sxHeight))
+ );
+ } else { /* arbitrary */
+ pdf_add_dict (descriptor,
+ pdf_new_name("CapHeight"),
+ pdf_new_number(PDFUNIT(os2->sTypoAscender))
+ );
+ }
+ /* optional */
+ if (os2->xAvgCharWidth != 0) {
+ pdf_add_dict (descriptor,
+ pdf_new_name ("AvgWidth"),
+ pdf_new_number (PDFUNIT(os2->xAvgCharWidth)));
+ }
+ }
+
+ /* BoundingBox (array) */
+ bbox = pdf_new_array ();
+ pdf_add_array (bbox, pdf_new_number (PDFUNIT(head->xMin)));
+ pdf_add_array (bbox, pdf_new_number (PDFUNIT(head->yMin)));
+ pdf_add_array (bbox, pdf_new_number (PDFUNIT(head->xMax)));
+ pdf_add_array (bbox, pdf_new_number (PDFUNIT(head->yMax)));
+ pdf_add_dict (descriptor, pdf_new_name ("FontBBox"), bbox);
+
+ /* post */
+ pdf_add_dict (descriptor,
+ pdf_new_name ("ItalicAngle"),
+ pdf_new_number(fixed(post->italicAngle)));
+
+ /* Flags */
+ if (os2) {
+ if (os2->fsSelection & (1 << 0))
+ flag |= ITALIC;
+ if (os2->fsSelection & (1 << 5))
+ flag |= FORCEBOLD;
+ if (((os2->sFamilyClass >> 8) & 0xff) != 8)
+ flag |= SERIF;
+ if (((os2->sFamilyClass >> 8) & 0xff) == 10)
+ flag |= SCRIPT;
+ if (post->isFixedPitch)
+ flag |= FIXEDWIDTH;
+ }
+ pdf_add_dict (descriptor,
+ pdf_new_name ("Flags"),
+ pdf_new_number (flag));
+
+ /* insert panose if you want */
+ if (type == 0 && os2) { /* cid-keyed font - add panose */
+ pdf_obj *styledict = NULL;
+ unsigned char panose[12];
+
+ panose[0] = os2->sFamilyClass >> 8;
+ panose[1] = os2->sFamilyClass & 0xff;
+ memcpy(panose+2, os2->panose, 10);
+
+ styledict = pdf_new_dict ();
+ pdf_add_dict (styledict, pdf_new_name ("Panose"),
+ pdf_new_string (panose, 12));
+ pdf_add_dict (descriptor, pdf_new_name ("Style"), styledict);
+ }
+
+ RELEASE(head);
+ if (os2)
+ RELEASE(os2);
+ tt_release_post_table(post);
+
+ return descriptor;
+}
+
diff --git a/Build/source/texk/dvipdf-x/xsrc/tt_aux.h b/Build/source/texk/dvipdf-x/xsrc/tt_aux.h
new file mode 100644
index 00000000000..3b17d3a70aa
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/tt_aux.h
@@ -0,0 +1,39 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _TT_AUX_H_
+#define _TT_AUX_H_
+
+#include "pdfobj.h"
+#include "sfnt.h"
+
+extern int always_embed; /* flag declared in dvipdfmx.c */
+
+extern void tt_aux_set_verbose(void);
+
+/* TTC (TrueType Collection) */
+extern ULONG ttc_read_offset (sfnt *sfont, int ttc_idx);
+
+/* FontDescriptor */
+extern pdf_obj *tt_get_fontdesc (sfnt *sfont, int *embed, int stemv, int type, const char* fontname);
+
+#endif /* _TT_AUX_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/tt_cmap.c b/Build/source/texk/dvipdf-x/xsrc/tt_cmap.c
new file mode 100644
index 00000000000..ac8610485fd
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/tt_cmap.c
@@ -0,0 +1,1940 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2007-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+/*
+ * A large part of codes are brought from ttfdump-0.5.5.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+
+#include "sfnt.h"
+
+
+/* Sorry for placing this here.
+ * We need to rewrite TrueType font support code...
+ */
+#include "cmap.h"
+#include "cmap_write.h"
+
+#include "tt_aux.h"
+#include "tt_gsub.h"
+
+#include "unicode.h"
+#include "agl.h"
+#include "pdfparse.h"
+#include "pdfresource.h"
+#include "otl_conf.h"
+
+#include "dpxfile.h"
+
+/* Hash */
+#include "dpxutil.h"
+
+#include "tt_cmap.h"
+
+#define VERBOSE_LEVEL_MIN 0
+static int verbose = 0;
+void
+otf_cmap_set_verbose (void)
+{
+ otl_gsub_set_verbose();
+ verbose++;
+}
+
+/* format 0: byte encoding table */
+struct cmap0
+{
+ BYTE glyphIndexArray[256];
+};
+
+static struct cmap0 *
+read_cmap0 (sfnt *sfont, ULONG len)
+{
+ struct cmap0 *map;
+ int i;
+
+ if (len < 256)
+ ERROR("invalid cmap subtable");
+
+ map = NEW(1, struct cmap0);
+
+ for (i = 0; i < 256; i++)
+ map->glyphIndexArray[i] = sfnt_get_byte(sfont);
+
+ return map;
+}
+
+static void
+release_cmap0(struct cmap0 *map)
+{
+ if (map)
+ RELEASE(map);
+}
+
+static USHORT
+lookup_cmap0 (struct cmap0 *map, USHORT cc)
+{
+ return ((cc > 255) ? 0 : map->glyphIndexArray[cc]);
+}
+
+/* format 2: high-byte mapping through table */
+struct SubHeader
+{
+ USHORT firstCode;
+ USHORT entryCount;
+ SHORT idDelta;
+ USHORT idRangeOffset;
+};
+
+struct cmap2
+{
+ USHORT subHeaderKeys[256];
+ struct SubHeader *subHeaders;
+ USHORT *glyphIndexArray;
+};
+
+static struct cmap2 *
+read_cmap2 (sfnt *sfont, ULONG len)
+{
+ struct cmap2 *map;
+ USHORT i, n;
+
+ if (len < 512)
+ ERROR("invalid cmap subtable");
+
+ map = NEW(1, struct cmap2);
+
+ for (i = 0; i < 256; i++)
+ map->subHeaderKeys[i] = sfnt_get_ushort(sfont);
+
+ for (n = 0, i = 0; i < 256; i++) {
+ map->subHeaderKeys[i] /= 8;
+ if (n < map->subHeaderKeys[i])
+ n = map->subHeaderKeys[i];
+ }
+ n += 1; /* the number of subHeaders is one plus the max of subHeaderKeys */
+
+ map->subHeaders = NEW(n, struct SubHeader);
+ for (i = 0; i < n; i++) {
+ map->subHeaders[i].firstCode = sfnt_get_ushort(sfont);
+ map->subHeaders[i].entryCount = sfnt_get_ushort(sfont);
+ map->subHeaders[i].idDelta = sfnt_get_short(sfont);
+ map->subHeaders[i].idRangeOffset = sfnt_get_ushort(sfont);
+
+ /* It makes things easier to let the offset starts from
+ * the beginning of glyphIndexArray.
+ */
+ if (map->subHeaders[i].idRangeOffset != 0)
+ map->subHeaders[i].idRangeOffset -= (2 + (n - i - 1) * 8);
+ }
+
+ /* Caculate the length of glyphIndexArray, this is ugly,
+ * there should be a better way to get this information.
+ */
+ n = (USHORT) (len - 518 - n * 8) / 2;
+
+ map->glyphIndexArray = NEW(n, USHORT);
+ for (i = 0; i < n; i++)
+ map->glyphIndexArray[i] = sfnt_get_ushort(sfont);
+
+ return map;
+}
+
+static void
+release_cmap2 (struct cmap2 *map)
+{
+ if (map) {
+ if (map->subHeaders)
+ RELEASE(map->subHeaders);
+ if (map->glyphIndexArray)
+ RELEASE(map->glyphIndexArray);
+ RELEASE(map);
+ }
+}
+
+static USHORT
+lookup_cmap2 (struct cmap2 *map, USHORT cc)
+{
+ USHORT idx = 0;
+ SHORT idDelta;
+ USHORT firstCode, entryCount, idRangeOffset;
+ int hi, lo;
+ USHORT i;
+
+ hi = (cc >> 8) & 0xff;
+ lo = cc & 0xff;
+
+ /* select which subHeader to use */
+ i = map->subHeaderKeys[hi];
+
+ firstCode = map->subHeaders[i].firstCode;
+ entryCount = map->subHeaders[i].entryCount;
+ idDelta = map->subHeaders[i].idDelta;
+ idRangeOffset = map->subHeaders[i].idRangeOffset / 2;
+
+ if (lo >= firstCode &&
+ lo < firstCode + entryCount) {
+ idRangeOffset += lo - firstCode;
+ idx = map->glyphIndexArray[idRangeOffset];
+ if (idx != 0)
+ idx = (idx + idDelta) & 0xffff;
+ }
+
+ return idx;
+}
+
+/*
+ * format 4: segment mapping to delta values
+ * - Microsoft standard character to glyph index mapping table
+ */
+struct cmap4
+{
+ USHORT segCountX2;
+ USHORT searchRange;
+ USHORT entrySelector;
+ USHORT rangeShift;
+ USHORT *endCount;
+ USHORT reservedPad;
+ USHORT *startCount;
+ USHORT *idDelta;
+ USHORT *idRangeOffset;
+ USHORT *glyphIndexArray;
+};
+
+static struct cmap4 *
+read_cmap4(sfnt *sfont, ULONG len)
+{
+ struct cmap4 *map;
+ USHORT i, n, segCount;
+
+ if (len < 8)
+ ERROR("invalid cmap subtable");
+
+ map = NEW(1, struct cmap4);
+
+ map->segCountX2 = segCount = sfnt_get_ushort(sfont);
+ map->searchRange = sfnt_get_ushort(sfont);
+ map->entrySelector = sfnt_get_ushort(sfont);
+ map->rangeShift = sfnt_get_ushort(sfont);
+
+ segCount /= 2;
+
+ map->endCount = NEW(segCount, USHORT);
+ for (i = 0; i < segCount; i++)
+ map->endCount[i] = sfnt_get_ushort(sfont);
+
+ map->reservedPad = sfnt_get_ushort(sfont);
+
+ map->startCount = NEW(segCount, USHORT);
+ for (i = 0; i < segCount; i++)
+ map->startCount[i] = sfnt_get_ushort(sfont);
+
+ map->idDelta = NEW(segCount, USHORT);
+ for (i = 0; i < segCount; i++)
+ map->idDelta[i] = sfnt_get_ushort(sfont);
+
+ map->idRangeOffset = NEW(segCount, USHORT);
+ for (i = 0; i < segCount; i++)
+ map->idRangeOffset[i] = sfnt_get_ushort(sfont);
+
+ n = (len - 16 - 8 * segCount) / 2;
+ if (n == 0)
+ map->glyphIndexArray = NULL;
+ else {
+ map->glyphIndexArray = NEW(n, USHORT);
+ for (i = 0; i < n; i++)
+ map->glyphIndexArray[i] = sfnt_get_ushort(sfont);
+ }
+
+ return map;
+}
+
+static void
+release_cmap4 (struct cmap4 *map)
+{
+ if (map) {
+ if (map->endCount) RELEASE(map->endCount);
+ if (map->startCount) RELEASE(map->startCount);
+ if (map->idDelta) RELEASE(map->idDelta);
+ if (map->idRangeOffset) RELEASE(map->idRangeOffset);
+ if (map->glyphIndexArray) RELEASE(map->glyphIndexArray);
+ RELEASE(map);
+ }
+}
+
+static USHORT
+lookup_cmap4 (struct cmap4 *map, USHORT cc)
+{
+ USHORT gid = 0;
+ USHORT i, j, segCount;
+
+ /*
+ * Segments are sorted in order of increasing endCode values.
+ * Last segment maps 0xffff to gid 0 (?)
+ */
+ i = segCount = map->segCountX2 / 2;
+ while (i-- > 0 && cc <= map->endCount[i]) {
+ if (cc >= map->startCount[i]) {
+ if (map->idRangeOffset[i] == 0) {
+ gid = (cc + map->idDelta[i]) & 0xffff;
+ } else if (cc == 0xffff && map->idRangeOffset[i] == 0xffff) {
+ /* this is for protection against some old broken fonts... */
+ gid = 0;
+ } else {
+ j = map->idRangeOffset[i] - (segCount - i) * 2;
+ j = (cc - map->startCount[i]) + (j / 2);
+ gid = map->glyphIndexArray[j];
+ if (gid != 0)
+ gid = (gid + map->idDelta[i]) & 0xffff;
+ }
+ break;
+ }
+ }
+
+ return gid;
+}
+
+/* format 6: trimmed table mapping */
+struct cmap6
+{
+ USHORT firstCode;
+ USHORT entryCount;
+ USHORT *glyphIndexArray;
+};
+
+static struct cmap6 *
+read_cmap6 (sfnt *sfont, ULONG len)
+{
+ struct cmap6 *map;
+ USHORT i;
+
+ if (len < 4)
+ ERROR("invalid cmap subtable");
+
+ map = NEW(1, struct cmap6);
+ map->firstCode = sfnt_get_ushort(sfont);
+ map->entryCount = sfnt_get_ushort(sfont);
+ map->glyphIndexArray = NEW(map->entryCount, USHORT);
+
+ for (i = 0; i < map->entryCount; i++)
+ map->glyphIndexArray[i] = sfnt_get_ushort(sfont);
+
+ return map;
+}
+
+static void
+release_cmap6 (struct cmap6 *map)
+{
+ if (map) {
+ if (map->glyphIndexArray)
+ RELEASE(map->glyphIndexArray);
+ RELEASE(map);
+ }
+}
+
+static USHORT
+lookup_cmap6 (struct cmap6 *map, USHORT cc)
+{
+ USHORT idx;
+
+ idx = cc - map->firstCode;
+ if (idx < map->entryCount)
+ return map->glyphIndexArray[idx];
+ else
+ return 0;
+
+ return 0;
+}
+
+/* Format 8 and 10 not supported...
+ *
+ * format 8: mixed 16-bit and 32-bit coverage
+ * format 10: trimmed array
+ */
+
+/*
+ * format 12: segmented coverage
+ *
+ * startGlyphID is 32-bit long, however, GlyphID is still 16-bit long !
+ */
+
+struct charGroup
+{
+ ULONG startCharCode;
+ ULONG endCharCode;
+ ULONG startGlyphID;
+};
+
+struct cmap12
+{
+ ULONG nGroups;
+ struct charGroup *groups;
+};
+
+/* ULONG length */
+static struct cmap12 *
+read_cmap12 (sfnt *sfont, ULONG len)
+{
+ struct cmap12 *map;
+ ULONG i;
+
+ if (len < 4)
+ ERROR("invalid cmap subtable");
+
+ map = NEW(1, struct cmap12);
+ map->nGroups = sfnt_get_ulong(sfont);
+ map->groups = NEW(map->nGroups, struct charGroup);
+
+ for (i = 0; i < map->nGroups; i++) {
+ map->groups[i].startCharCode = sfnt_get_ulong(sfont);
+ map->groups[i].endCharCode = sfnt_get_ulong(sfont);
+ map->groups[i].startGlyphID = sfnt_get_ulong(sfont);
+ }
+
+ return map;
+}
+
+static void
+release_cmap12 (struct cmap12 *map)
+{
+ if (map) {
+ if (map->groups)
+ RELEASE(map->groups);
+ RELEASE(map);
+ }
+}
+
+static USHORT
+lookup_cmap12 (struct cmap12 *map, ULONG cccc)
+{
+ USHORT gid = 0;
+ ULONG i;
+
+ i = map->nGroups;
+ while (i-- >= 0 &&
+ cccc <= map->groups[i].endCharCode) {
+ if (cccc >= map->groups[i].startCharCode) {
+ gid = (USHORT) ((cccc -
+ map->groups[i].startCharCode +
+ map->groups[i].startGlyphID) & 0xffff);
+ break;
+ }
+ }
+
+ return gid;
+}
+
+/* read cmap */
+tt_cmap *
+tt_cmap_read (sfnt *sfont, USHORT platform, USHORT encoding)
+{
+ tt_cmap *cmap = NULL;
+ ULONG offset, length = 0;
+ USHORT p_id, e_id;
+ USHORT i, n_subtabs;
+
+ ASSERT(sfont);
+
+ offset = sfnt_locate_table(sfont, "cmap");
+ (void) sfnt_get_ushort(sfont);
+ n_subtabs = sfnt_get_ushort(sfont);
+
+ for (i = 0; i < n_subtabs; i++) {
+ p_id = sfnt_get_ushort(sfont);
+ e_id = sfnt_get_ushort(sfont);
+ if (p_id != platform || e_id != encoding)
+ sfnt_get_ulong(sfont);
+ else {
+ offset += sfnt_get_ulong(sfont);
+ break;
+ }
+ }
+
+ if (i == n_subtabs)
+ return NULL;
+
+ cmap = NEW(1, tt_cmap);
+ cmap->map = NULL;
+ cmap->platform = platform;
+ cmap->encoding = encoding;
+
+ sfnt_seek_set(sfont, offset);
+ cmap->format = sfnt_get_ushort(sfont);
+ /* Length and version (language) is ULONG for
+ * format 8, 10, 12 !
+ */
+ if (cmap->format <= 6) {
+ length = sfnt_get_ushort(sfont);
+ cmap->language = sfnt_get_ushort(sfont); /* language (Mac) */
+ } else {
+ if (sfnt_get_ushort(sfont) != 0) { /* reverved - 0 */
+ WARN("Unrecognized cmap subtable format.");
+ tt_cmap_release(cmap);
+ return NULL;
+ } else {
+ length = sfnt_get_ulong(sfont);
+ cmap->language = sfnt_get_ulong(sfont);
+ }
+ }
+
+ switch(cmap->format) {
+ case 0:
+ cmap->map = read_cmap0(sfont, length);
+ break;
+ case 2:
+ cmap->map = read_cmap2(sfont, length);
+ break;
+ case 4:
+ cmap->map = read_cmap4(sfont, length);
+ break;
+ case 6:
+ cmap->map = read_cmap6(sfont, length);
+ break;
+ case 12:
+ /*WARN("UCS-4 TrueType cmap table...");*/
+ cmap->map = read_cmap12(sfont, length);
+ break;
+ default:
+ WARN("Unrecognized OpenType/TrueType cmap format.");
+ tt_cmap_release(cmap);
+ return NULL;
+ }
+
+ if (!cmap->map) {
+ tt_cmap_release(cmap);
+ cmap = NULL;
+ }
+
+ return cmap;
+}
+
+void
+tt_cmap_release (tt_cmap *cmap)
+{
+
+ if (cmap) {
+ if (cmap->map) {
+ switch(cmap->format) {
+ case 0:
+ release_cmap0(cmap->map);
+ break;
+ case 2:
+ release_cmap2(cmap->map);
+ break;
+ case 4:
+ release_cmap4(cmap->map);
+ break;
+ case 6:
+ release_cmap6(cmap->map);
+ break;
+ case 12:
+ release_cmap12(cmap->map);
+ break;
+ default:
+ ERROR("Unrecognized OpenType/TrueType cmap format.");
+ }
+ }
+ RELEASE(cmap);
+ }
+
+ return;
+}
+
+
+USHORT
+tt_cmap_lookup (tt_cmap *cmap, long cc)
+{
+ USHORT gid = 0;
+
+ ASSERT(cmap);
+
+ if (cc > 0xffffL && cmap->format < 12) {
+ WARN("Four bytes charcode not supported in OpenType/TrueType cmap format 0...6.");
+ return 0;
+ }
+
+ switch (cmap->format) {
+ case 0:
+ gid = lookup_cmap0(cmap->map, (USHORT) cc);
+ break;
+ case 2:
+ gid = lookup_cmap2(cmap->map, (USHORT) cc);
+ break;
+ case 4:
+ gid = lookup_cmap4(cmap->map, (USHORT) cc);
+ break;
+ case 6:
+ gid = lookup_cmap6(cmap->map, (USHORT) cc);
+ break;
+ case 12:
+ gid = lookup_cmap12(cmap->map, (ULONG) cc);
+ break;
+ default:
+ ERROR("Unrecognized OpenType/TrueType cmap subtable format");
+ break;
+ }
+
+ return gid;
+}
+
+/* Sorry for placing this here.
+ * We need to rewrite TrueType font support code...
+ */
+
+#define WBUF_SIZE 1024
+static unsigned char wbuf[WBUF_SIZE];
+
+static unsigned char srange_min[2] = {0x00, 0x00};
+static unsigned char srange_max[2] = {0xff, 0xff};
+static unsigned char lrange_min[4] = {0x00, 0x00, 0x00, 0x00};
+static unsigned char lrange_max[4] = {0x7f, 0xff, 0xff, 0xff};
+
+static void
+load_cmap4 (struct cmap4 *map,
+ unsigned char *GIDToCIDMap, CMap *cmap)
+{
+ USHORT c0, c1, gid, cid;
+ USHORT j, d, segCount;
+ USHORT ch;
+ long i;
+
+ segCount = map->segCountX2 / 2;
+ for (i = segCount - 1; i >= 0 ; i--) {
+ c0 = map->startCount[i];
+ c1 = map->endCount[i];
+ d = map->idRangeOffset[i] / 2 - (segCount - i);
+ for (j = 0; j <= c1 - c0; j++) {
+ ch = c0 + j;
+ if (map->idRangeOffset[i] == 0) {
+ gid = (ch + map->idDelta[i]) & 0xffff;
+ } else if (c0 == 0xffff && c1 == 0xffff && map->idRangeOffset[i] == 0xffff) {
+ /* this is for protection against some old broken fonts... */
+ gid = 0;
+ } else {
+ gid = (map->glyphIndexArray[j+d] +
+ map->idDelta[i]) & 0xffff;
+ }
+ if (gid != 0 && gid != 0xffff) {
+ if (GIDToCIDMap) {
+ cid = ((GIDToCIDMap[2*gid] << 8)|GIDToCIDMap[2*gid+1]);
+ if (cid == 0)
+ WARN("GID %u does not have corresponding CID %u.",
+ gid, cid);
+ } else {
+ cid = gid;
+ }
+ wbuf[0] = 0;
+ wbuf[1] = 0;
+ wbuf[2] = (ch >> 8) & 0xff;
+ wbuf[3] = ch & 0xff;
+ CMap_add_cidchar(cmap, wbuf, 4, cid);
+ }
+ }
+ }
+
+ return;
+}
+
+static void
+load_cmap12 (struct cmap12 *map,
+ unsigned char *GIDToCIDMap, CMap *cmap)
+{
+ ULONG i, ch; /* LONG ? */
+ USHORT gid, cid;
+
+ for (i = 0; i < map->nGroups; i++) {
+ for (ch = map->groups[i].startCharCode;
+ ch <= map->groups[i].endCharCode;
+ ch++) {
+ long d = ch - map->groups[i].startCharCode;
+ gid = (USHORT) ((map->groups[i].startGlyphID + d) & 0xffff);
+ if (GIDToCIDMap) {
+ cid = ((GIDToCIDMap[2*gid] << 8)|GIDToCIDMap[2*gid+1]);
+ if (cid == 0)
+ WARN("GID %u does not have corresponding CID %u.", gid, cid);
+ } else {
+ cid = gid;
+ }
+ wbuf[0] = (ch >> 24) & 0xff;
+ wbuf[1] = (ch >> 16) & 0xff;
+ wbuf[2] = (ch >> 8) & 0xff;
+ wbuf[3] = ch & 0xff;
+ CMap_add_cidchar(cmap, wbuf, 4, cid);
+ }
+ }
+
+ return;
+}
+
+/* OpenType CIDFont:
+ *
+ * We don't use GID for them. OpenType cmap table is for
+ * charcode to GID mapping rather than to-CID mapping.
+ */
+#include "cid.h"
+
+#include "tt_table.h"
+#include "cff_types.h"
+#include "cff_dict.h"
+#include "cff.h"
+
+static int
+handle_CIDFont (sfnt *sfont,
+ unsigned char **GIDToCIDMap, CIDSysInfo *csi)
+{
+ cff_font *cffont;
+ long offset, i;
+ card16 num_glyphs, gid;
+ cff_charsets *charset;
+ unsigned char *map;
+ struct tt_maxp_table *maxp;
+
+ ASSERT(csi);
+
+ offset = sfnt_find_table_pos(sfont, "CFF ");
+ if (offset == 0) {
+ csi->registry = NULL;
+ csi->ordering = NULL;
+ *GIDToCIDMap = NULL;
+ return 0;
+ }
+
+ maxp = tt_read_maxp_table(sfont);
+ num_glyphs = (card16) maxp->numGlyphs;
+ RELEASE(maxp);
+ if (num_glyphs < 1)
+ ERROR("No glyph contained in this font...");
+
+ cffont = cff_open(sfont, offset, 0);
+ if (!cffont)
+ ERROR("Could not open CFF font...");
+
+
+ if (!(cffont->flag & FONTTYPE_CIDFONT)) {
+ cff_close(cffont);
+ csi->registry = NULL;
+ csi->ordering = NULL;
+ *GIDToCIDMap = NULL;
+ return 0;
+ }
+
+ if (!cff_dict_known(cffont->topdict, "ROS")) {
+ ERROR("No CIDSystemInfo???");
+ } else {
+ card16 reg, ord;
+
+ reg = (card16) cff_dict_get(cffont->topdict, "ROS", 0);
+ ord = (card16) cff_dict_get(cffont->topdict, "ROS", 1);
+
+ csi->registry = cff_get_string(cffont, reg);
+ csi->ordering = cff_get_string(cffont, ord);
+ csi->supplement = (int) cff_dict_get(cffont->topdict, "ROS", 2);
+ }
+
+ cff_read_charsets(cffont);
+ charset = cffont->charsets;
+ if (!charset) {
+ ERROR("No CFF charset data???");
+ }
+
+ map = NEW(num_glyphs * 2, unsigned char);
+ memset(map, 0, num_glyphs * 2);
+ switch (charset->format) {
+ case 0:
+ {
+ s_SID *cids; /* CID... */
+
+ cids = charset->data.glyphs;
+ for (gid = 1, i = 0;
+ i < charset->num_entries; i++) {
+ map[2*gid ] = (cids[i] >> 8) & 0xff;
+ map[2*gid+1] = cids[i] & 0xff;
+ gid++;
+ }
+ }
+ break;
+ case 1:
+ {
+ cff_range1 *ranges;
+ card16 cid, count;
+
+ ranges = charset->data.range1;
+ for (gid = 1, i = 0;
+ i < charset->num_entries; i++) {
+ cid = ranges[i].first;
+ count = ranges[i].n_left + 1; /* card8 */
+ while (count-- > 0 &&
+ gid <= num_glyphs) {
+ map[2*gid ] = (cid >> 8) & 0xff;
+ map[2*gid + 1] = cid & 0xff;
+ gid++;
+ }
+ }
+ }
+ break;
+ case 2:
+ {
+ cff_range2 *ranges;
+ card16 cid, count;
+
+ ranges = charset->data.range2;
+ if (charset->num_entries == 1 &&
+ ranges[0].first == 1) {
+ /* "Complete" CIDFont */
+ RELEASE(map); map = NULL;
+ } else {
+ /* Not trivial mapping */
+ for (gid = 1, i = 0;
+ i < charset->num_entries; i++) {
+ cid = ranges[i].first;
+ count = ranges[i].n_left + 1;
+ while (count-- > 0 &&
+ gid <= num_glyphs) {
+ map[gid] = (cid >> 8) & 0xff;
+ map[gid] = cid & 0xff;
+ gid++;
+ }
+ }
+
+ }
+ }
+ break;
+ default:
+ RELEASE(map); map = NULL;
+ ERROR("Unknown CFF charset format...: %d", charset->format);
+ break;
+ }
+ cff_close(cffont);
+
+ *GIDToCIDMap = map;
+ return 1;
+}
+
+/*
+ * Substituted glyphs:
+ *
+ * Mapping information stored in cmap_add.
+ */
+#ifndef is_used_char2
+#define is_used_char2(b,c) (((b)[(c)/8]) & (1 << (7-((c)%8))))
+#endif
+
+static USHORT
+handle_subst_glyphs (CMap *cmap,
+ CMap *cmap_add, const char *used_glyphs,
+ sfnt *sfont)
+{
+ USHORT count;
+ USHORT i, gid;
+
+ for (count = 0, i = 0; i < 8192; i++) {
+ int j;
+ long len, inbytesleft, outbytesleft;
+ const unsigned char *inbuf;
+ unsigned char *outbuf;
+
+ if (used_glyphs[i] == 0)
+ continue;
+
+ for (j = 0; j < 8; j++) {
+ gid = 8 * i + j;
+
+ if (!is_used_char2(used_glyphs, gid))
+ continue;
+
+ if (!cmap_add) {
+#if XETEX
+ if (FT_HAS_GLYPH_NAMES(sfont->ft_face)) {
+ /* JK: try to look up Unicode values from the glyph name... */
+#define MAX_UNICODES 16
+#define MAX_NAME 256
+ static char name[MAX_NAME] = "(none)";
+ long unicodes[MAX_UNICODES];
+ int unicode_count = -1;
+ FT_Error err = FT_Get_Glyph_Name(sfont->ft_face, gid, name, MAX_NAME);
+ if (!err) {
+ unicode_count = agl_get_unicodes(name, unicodes, MAX_UNICODES);
+ }
+#undef MAX_UNICODES
+#undef MAX_NAME
+ if (unicode_count == -1) {
+ MESG("No Unicode mapping available: GID=%u, name=%s\n", gid, name);
+ } else {
+ /* the Unicode characters go into wbuf[2] and following, in UTF16BE */
+ /* we rely on WBUF_SIZE being more than adequate for MAX_UNICODES */
+ unsigned char* p = wbuf + 2;
+ int k;
+ len = 0;
+ for (k = 0; k < unicode_count; ++k) {
+ len += UC_sput_UTF16BE(unicodes[k], &p, wbuf+WBUF_SIZE);
+ }
+ wbuf[0] = (gid >> 8) & 0xff;
+ wbuf[1] = gid & 0xff;
+ CMap_add_bfchar(cmap, wbuf, 2, wbuf + 2, len);
+ }
+ }
+#else
+ WARN("No Unicode mapping available: GID=%u", gid);
+#endif
+ } else {
+ wbuf[0] = (gid >> 8) & 0xff;
+ wbuf[1] = gid & 0xff;
+ inbuf = wbuf;
+ inbytesleft = 2;
+ outbuf = wbuf + 2;
+ outbytesleft = WBUF_SIZE - 2;
+ CMap_decode(cmap_add,
+ &inbuf , &inbytesleft,
+ &outbuf, &outbytesleft);
+ if (inbytesleft != 0) {
+ WARN("CMap conversion failed...");
+ } else {
+ len = WBUF_SIZE - 2 - outbytesleft;
+ CMap_add_bfchar(cmap, wbuf, 2, wbuf + 2, len);
+ count++;
+
+ if (verbose > VERBOSE_LEVEL_MIN) {
+ long _i;
+
+ MESG("otf_cmap>> Additional ToUnicode mapping: <%04X> <", gid);
+ for (_i = 0; _i < len; _i++) {
+ MESG("%02X", wbuf[2 + _i]);
+ }
+ MESG(">\n");
+ }
+
+ }
+ }
+
+ }
+ }
+
+ return count;
+}
+
+static pdf_obj *
+create_ToUnicode_cmap4 (struct cmap4 *map,
+ const char *cmap_name, CMap *cmap_add,
+ const char *used_glyphs,
+ sfnt *sfont)
+{
+ pdf_obj *stream = NULL;
+ CMap *cmap;
+ USHORT c0, c1, gid, count, ch;
+ USHORT i, j, d, segCount;
+ char used_glyphs_copy[8192];
+
+ cmap = CMap_new();
+ CMap_set_name (cmap, cmap_name);
+ CMap_set_wmode(cmap, 0);
+ CMap_set_type (cmap, CMAP_TYPE_TO_UNICODE);
+ CMap_set_CIDSysInfo(cmap, &CSI_UNICODE);
+ CMap_add_codespacerange(cmap, srange_min, srange_max, 2);
+
+ memcpy(used_glyphs_copy, used_glyphs, 8192);
+
+ segCount = map->segCountX2 / 2;
+ for (count = 0, i = 0; i < segCount; i++) {
+ c0 = map->startCount[i];
+ c1 = map->endCount[i];
+ d = map->idRangeOffset[i] / 2 - (segCount - i);
+ for (j = 0; j <= c1 - c0; j++) {
+ ch = c0 + j;
+ if (map->idRangeOffset[i] == 0) {
+ gid = (ch + map->idDelta[i]) & 0xffff;
+ } else if (c0 == 0xffff && c1 == 0xffff && map->idRangeOffset[i] == 0xffff) {
+ /* this is for protection against some old broken fonts... */
+ gid = 0;
+ } else {
+ gid = (map->glyphIndexArray[j+d] +
+ map->idDelta[i]) & 0xffff;
+ }
+ if (is_used_char2(used_glyphs_copy, gid)) {
+ count++;
+
+ wbuf[0] = (gid >> 8) & 0xff;
+ wbuf[1] = (gid & 0xff);
+
+ wbuf[2] = (ch >> 8) & 0xff;
+ wbuf[3] = ch & 0xff;
+
+ CMap_add_bfchar(cmap, wbuf, 2, wbuf+2, 2);
+
+ /* Avoid duplicate entry
+ * There are problem when two Unicode code is mapped to
+ * single glyph...
+ */
+ used_glyphs_copy[gid/8] &= ~(1 << (7 - (gid % 8)));
+ count++;
+ }
+ }
+ }
+
+ count += handle_subst_glyphs(cmap, cmap_add, used_glyphs_copy, sfont);
+
+ if (count < 1)
+ stream = NULL;
+ else {
+ stream = CMap_create_stream(cmap, 0);
+ }
+ CMap_release(cmap);
+
+ return stream;
+}
+
+
+static pdf_obj *
+create_ToUnicode_cmap12 (struct cmap12 *map,
+ const char *cmap_name, CMap *cmap_add,
+ const char *used_glyphs,
+ sfnt *sfont)
+{
+ pdf_obj *stream = NULL;
+ CMap *cmap;
+ ULONG i, ch;
+ USHORT gid, count;
+ char used_glyphs_copy[8192];
+
+ cmap = CMap_new();
+ CMap_set_name (cmap, cmap_name);
+ CMap_set_wmode(cmap, 0);
+ CMap_set_type (cmap, CMAP_TYPE_TO_UNICODE);
+ CMap_set_CIDSysInfo(cmap, &CSI_UNICODE);
+ CMap_add_codespacerange(cmap, srange_min, srange_max, 2);
+
+ memcpy(used_glyphs_copy, used_glyphs, 8192);
+ for (count = 0, i = 0; i < map->nGroups; i++) {
+ for (ch = map->groups[i].startCharCode;
+ ch <= map->groups[i].endCharCode; ch++) {
+ unsigned char *p;
+ int len;
+ long d;
+
+ p = wbuf + 2;
+ d = ch - map->groups[i].startCharCode;
+ gid = (USHORT) ((map->groups[i].startGlyphID + d) & 0xffff);
+ if (is_used_char2(used_glyphs_copy, gid)) {
+ count++;
+ wbuf[0] = (gid >> 8) & 0xff;
+ wbuf[1] = (gid & 0xff);
+ len = UC_sput_UTF16BE((long)ch, &p, wbuf+WBUF_SIZE);
+
+ used_glyphs_copy[gid/8] &= ~(1 << (7 - (gid % 8)));
+ CMap_add_bfchar(cmap, wbuf, 2, wbuf+2, len);
+ }
+ }
+ }
+
+ count += handle_subst_glyphs(cmap, cmap_add, used_glyphs_copy, sfont);
+
+ if (count < 1)
+ stream = NULL;
+ else {
+ stream = CMap_create_stream(cmap, 0);
+ }
+ CMap_release(cmap);
+
+ return stream;
+}
+
+typedef struct {
+ short platform;
+ short encoding;
+} cmap_plat_enc_rec;
+
+static cmap_plat_enc_rec cmap_plat_encs[] = {
+ { 3, 10 },
+ { 0, 3 },
+ { 0, 0 },
+ { 3, 1 },
+ { 0, 1 }
+};
+
+pdf_obj *
+otf_create_ToUnicode_stream (const char *font_name,
+ int ttc_index, /* 0 for non-TTC */
+ FT_Face face,
+ const char *used_glyphs)
+{
+ pdf_obj *cmap_ref = NULL;
+ long res_id;
+ pdf_obj *cmap_obj = NULL;
+ CMap *cmap_add;
+ int cmap_add_id;
+ tt_cmap *ttcmap;
+ char *normalized_font_name;
+ char *cmap_name;
+ FILE *fp = NULL;
+ sfnt *sfont;
+ long offset = 0;
+ int i;
+
+ /* replace slash in map name with dash to make the output cmap name valid,
+ * happens when XeTeX embeds full font path
+ * https://sourceforge.net/p/xetex/bugs/52/
+ */
+ normalized_font_name = NEW(strlen(font_name)+1, char);
+ strcpy(normalized_font_name, font_name);
+ for (i = 0; i < strlen(font_name); ++i) {
+ if (normalized_font_name[i] == '/')
+ normalized_font_name[i] = '-';
+ }
+
+ cmap_name = NEW(strlen(font_name)+strlen("-UTF16")+5, char);
+ sprintf(cmap_name, "%s,%03d-UTF16", normalized_font_name, ttc_index);
+
+ res_id = pdf_findresource("CMap", cmap_name);
+ if (res_id >= 0) {
+ RELEASE(cmap_name);
+ cmap_ref = pdf_get_resource_reference(res_id);
+ return cmap_ref;
+ }
+
+ if (verbose > VERBOSE_LEVEL_MIN) {
+ MESG("\n");
+ MESG("otf_cmap>> Creating ToUnicode CMap for \"%s\"...\n", font_name);
+ }
+
+#ifdef XETEX
+ sfont = sfnt_open(face, -1);
+#else
+ fp = DPXFOPEN(font_name, DPX_RES_TYPE_TTFONT);
+ if (!fp) {
+ fp = DPXFOPEN(font_name, DPX_RES_TYPE_OTFONT);
+ }
+
+ if (!fp) {
+ RELEASE(cmap_name);
+ return NULL;
+ }
+
+ sfont = sfnt_open(fp);
+#endif
+
+ if (!sfont) {
+ ERROR("Could not open OpenType/TrueType font file \"%s\"", font_name);
+ }
+
+ switch (sfont->type) {
+ case SFNT_TYPE_TTC:
+ offset = ttc_read_offset(sfont, ttc_index);
+ if (offset == 0) {
+ ERROR("Invalid TTC index");
+ }
+ break;
+ default:
+ offset = 0;
+ break;
+ }
+
+ if (sfnt_read_table_directory(sfont, offset) < 0) {
+ ERROR("Could not read OpenType/TrueType table directory.");
+ }
+
+ cmap_add_id = CMap_cache_find(cmap_name);
+ if (cmap_add_id < 0) {
+ cmap_add = NULL;
+ } else {
+ cmap_add = CMap_cache_get(cmap_add_id);
+ }
+
+ CMap_set_silent(1); /* many warnings without this... */
+ for (i = 0; i < sizeof(cmap_plat_encs) / sizeof(cmap_plat_enc_rec); ++i) {
+ ttcmap = tt_cmap_read(sfont, cmap_plat_encs[i].platform, cmap_plat_encs[i].encoding);
+ if (!ttcmap)
+ continue;
+ if (ttcmap->format == 4) {
+ cmap_obj = create_ToUnicode_cmap4(ttcmap->map,
+ cmap_name, cmap_add, used_glyphs, sfont);
+ break;
+ }
+ if (ttcmap->format == 12) {
+ cmap_obj = create_ToUnicode_cmap12(ttcmap->map,
+ cmap_name, cmap_add, used_glyphs, sfont);
+ break;
+ }
+ }
+ if (cmap_obj == NULL)
+ WARN("Unable to read OpenType/TrueType Unicode cmap table.");
+ tt_cmap_release(ttcmap);
+ CMap_set_silent(0);
+
+ if (cmap_obj) {
+ res_id = pdf_defineresource("CMap", cmap_name,
+ cmap_obj, PDF_RES_FLUSH_IMMEDIATE);
+ cmap_ref = pdf_get_resource_reference(res_id);
+ } else {
+ cmap_ref = NULL;
+ }
+ RELEASE(cmap_name);
+
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+
+ return cmap_ref;
+}
+
+/* Must be smaller than (WBUF_SIZE-2)/8 */
+#define MAX_UNICODES 16
+
+struct gent
+{
+ USHORT gid;
+ long ucv; /* assigned PUA unicode */
+
+ int num_unicodes;
+ long unicodes[MAX_UNICODES];
+};
+
+static void
+create_cmaps (CMap *cmap, CMap *tounicode,
+ struct ht_table *unencoded, unsigned char *GIDToCIDMap)
+{
+ struct ht_iter iter;
+
+ ASSERT(cmap && unencoded);
+
+ if (ht_set_iter(unencoded, &iter) < 0)
+ return;
+
+ CMap_set_silent(1); /* many warnings without this... */
+
+ do {
+ struct gent *glyph;
+ unsigned char *ucv;
+ int i, len;
+ unsigned char *p, *endptr;
+ CID cid;
+
+ glyph = (struct gent *) ht_iter_getval(&iter);
+ ucv = (unsigned char *) ht_iter_getkey(&iter, &len);
+
+ if (GIDToCIDMap) {
+ cid = ((GIDToCIDMap[2 * glyph->gid] << 8)|GIDToCIDMap[2 * glyph->gid + 1]);
+ if (cid == 0)
+ WARN("Glyph gid=%u does not have corresponding CID.", glyph->gid);
+ } else {
+ cid = glyph->gid;
+ }
+
+ CMap_add_cidchar(cmap, ucv, 4, cid);
+
+ if (tounicode) {
+ wbuf[0] = (cid >> 8) & 0xff;
+ wbuf[1] = cid & 0xff;
+ p = wbuf + 2;
+ endptr = wbuf + WBUF_SIZE;
+ len = 0;
+ for (i = 0; i < glyph->num_unicodes; i++) {
+ len += UC_sput_UTF16BE(glyph->unicodes[i], &p, endptr);
+ }
+ CMap_add_bfchar(tounicode, wbuf, 2, wbuf + 2, len);
+ }
+ } while (ht_iter_next(&iter) >= 0);
+
+ CMap_set_silent(0);
+
+ ht_clear_iter(&iter);
+}
+
+static void
+add_glyph (struct ht_table *unencoded,
+ USHORT gid, long ucv, int num_unicodes, long *unicodes)
+{
+ struct gent *glyph;
+ int i;
+
+ ASSERT(unencoded);
+
+ if (gid == 0 || num_unicodes < 1) {
+ return;
+ }
+
+ wbuf[0] = (ucv >> 24) & 0xff;
+ wbuf[1] = (ucv >> 16) & 0xff;
+ wbuf[2] = (ucv >> 8) & 0xff;
+ wbuf[3] = ucv & 0xff;
+
+ glyph = NEW(1, struct gent);
+ glyph->gid = gid;
+ glyph->num_unicodes = num_unicodes;
+ for (i = 0;
+ i < num_unicodes && i < MAX_UNICODES; i++) {
+ glyph->unicodes[i] = unicodes[i];
+ }
+
+ ht_append_table(unencoded, wbuf, 4, glyph);
+}
+
+/* This seriously affects speed... */
+static struct gent *
+find_glyph (struct ht_table *unencoded, long ucv)
+{
+ ASSERT(unencoded);
+
+ wbuf[0] = (ucv >> 24) & 0xff;
+ wbuf[1] = (ucv >> 16) & 0xff;
+ wbuf[2] = (ucv >> 8) & 0xff;
+ wbuf[3] = ucv & 0xff;
+
+ return (struct gent *) ht_lookup_table(unencoded, wbuf, 4);
+}
+
+static void
+handle_subst (pdf_obj *dst_obj, pdf_obj *src_obj, int flag,
+ otl_gsub *gsub_list, tt_cmap *ttcmap,
+ struct ht_table *unencoded)
+{
+ pdf_obj *tmp;
+ long i, j, src_size, dst_size;
+ long src, dst;
+ long src_start, src_end, dst_start, dst_end;
+
+ src_size = pdf_array_length(src_obj);
+ dst_size = pdf_array_length(dst_obj);
+
+ dst_start = dst_end = -1; dst = 0;
+ src_start = src_end = -1; src = 0;
+ for (i = 0, j = 0;
+ i < src_size && j < dst_size; i++) {
+ USHORT gid;
+ int rv;
+ struct gent *glyph;
+
+ tmp = pdf_get_array(src_obj, i);
+ if (PDF_OBJ_ARRAYTYPE(tmp)) {
+ src_start = (long) pdf_number_value(pdf_get_array(tmp, 0));
+ src_end = (long) pdf_number_value(pdf_get_array(tmp, 1));
+ } else {
+ src_start = src_end = (long) pdf_number_value(tmp);
+ }
+ for (src = src_start; src <= src_end; src++) {
+ glyph = find_glyph(unencoded, src);
+ if (glyph)
+ gid = glyph->gid;
+ else {
+ gid = tt_cmap_lookup(ttcmap, src);
+ }
+ dst++;
+ if (dst > dst_end) {
+ tmp = pdf_get_array(dst_obj, j++);
+ if (PDF_OBJ_ARRAYTYPE(tmp)) {
+ dst_start = (long) pdf_number_value(pdf_get_array(tmp, 0));
+ dst_end = (long) pdf_number_value(pdf_get_array(tmp, 1));
+ } else {
+ dst_start = dst_end = (long) pdf_number_value(tmp);
+ }
+ dst = dst_start;
+ }
+ if (gid == 0) {
+ if (flag == 'r' || flag == 'p') {
+ if (src < 0x10000) {
+ WARN("Font does not have glyph for U+%04X.", src);
+ } else {
+ WARN("Font does not have glyph for U+%06X.", src);
+ }
+ }
+ if (flag == 'r') {
+ ERROR("Missing glyph found...");
+ }
+ continue;
+ }
+ rv = otl_gsub_apply(gsub_list, &gid);
+ if (rv < 0) {
+ if (flag == 'p' || flag == 'r') {
+ if (src < 0x10000) {
+ WARN("No substituted glyph for U+%04X.", src);
+ } else {
+ WARN("No substituted glyph for U+%06X.", src);
+ }
+ }
+ if (flag == 'r') {
+ ERROR("Missing glyph found...");
+ }
+ continue;
+ }
+
+ if (glyph) {
+ glyph->gid = gid;
+ } else {
+ add_glyph(unencoded, gid, dst, 1, &src);
+ }
+
+ if (verbose > VERBOSE_LEVEL_MIN) {
+ if (dst < 0x10000) {
+ MESG("otf_cmap>> Substituted glyph gid=%u assigned to U+%04X\n",
+ gid, dst);
+ } else {
+ MESG("otf_cmap>> Substituted glyph gid=%u assigned to U+%06X\n",
+ gid, dst);
+ }
+ }
+
+ }
+ }
+
+ if (dst < dst_end || src < src_end ||
+ i < src_size || j < dst_size) {
+ WARN("Number of glyphs in left-side and right-side not equal...");
+ WARN("Please check .otl file...");
+ }
+}
+
+static void
+handle_assign (pdf_obj *dst, pdf_obj *src, int flag,
+ otl_gsub *gsub_list, tt_cmap *ttcmap,
+ struct ht_table *unencoded)
+{
+ long unicodes[MAX_UNICODES], ucv;
+ int i, n_unicodes, rv;
+ USHORT gid_in[MAX_UNICODES], lig;
+
+ n_unicodes = pdf_array_length(src); /* FIXME */
+ ucv = (long) pdf_number_value(pdf_get_array(dst, 0)); /* FIXME */
+ if (!UC_is_valid(ucv)) {
+ if (flag == 'r' || flag == 'p') {
+ if (ucv < 0x10000) {
+ WARN("Invalid Unicode in: %04X", ucv);
+ } else {
+ WARN("Invalid Unicode in: %06X", ucv);
+ }
+ }
+ if (flag == 'r') {
+ ERROR("Invalid Unicode code specified.", ucv);
+ }
+ return;
+ }
+
+ if (verbose > VERBOSE_LEVEL_MIN) {
+ MESG("otf_cmap>> Ligature component:");
+ }
+
+ for (i = 0; i < n_unicodes; i++) {
+ unicodes[i] =
+ (long) pdf_number_value(pdf_get_array(src, i));
+ gid_in[i] = tt_cmap_lookup(ttcmap, unicodes[i]);
+
+ if (verbose > VERBOSE_LEVEL_MIN) {
+ if (unicodes[i] < 0x10000) {
+ MESG(" U+%04X (gid=%u)", unicodes[i], gid_in[i]);
+ } else {
+ MESG(" U+%06X (gid=%u)", unicodes[i], gid_in[i]);
+ }
+ }
+
+ if (gid_in[i] == 0) {
+ if (flag == 'r' || flag == 'p') {
+ if (unicodes[i] < 0x10000) {
+ WARN("Unicode char U+%04X not exist in font...", unicodes[i]);
+ } else {
+ WARN("Unicode char U+%06X not exist in font...", unicodes[i]);
+ }
+ }
+ if (flag == 'r') {
+ ERROR("Missing glyph found...");
+ }
+ return;
+ }
+
+ }
+
+ if (verbose > VERBOSE_LEVEL_MIN) {
+ MESG("\n");
+ }
+
+ rv = otl_gsub_apply_lig(gsub_list,
+ gid_in, (USHORT)n_unicodes, &lig);
+ if (rv < 0) {
+ if (flag == 'p')
+ WARN("No ligature found...");
+ else if (flag == 'r')
+ ERROR("No ligature found...");
+ return;
+ }
+
+ add_glyph(unencoded, lig, ucv, n_unicodes, unicodes);
+
+ if (verbose > VERBOSE_LEVEL_MIN) {
+ if (ucv < 0x10000) {
+ MESG("otf_cmap>> Ligature glyph gid=%u assigned to U+%04X\n", lig, ucv);
+ } else {
+ MESG("otf_cmap>> Ligature glyph gid=%u assigned to U+%06X\n", lig, ucv);
+ }
+ }
+
+ return;
+}
+
+static int
+load_base_CMap (const char *cmap_name, int wmode,
+ CIDSysInfo *csi, unsigned char *GIDToCIDMap,
+ tt_cmap *ttcmap)
+{
+ int cmap_id;
+
+ cmap_id = CMap_cache_find(cmap_name);
+ if (cmap_id < 0) {
+ CMap *cmap;
+
+ cmap = CMap_new();
+ CMap_set_name (cmap, cmap_name);
+ CMap_set_type (cmap, CMAP_TYPE_CODE_TO_CID);
+ CMap_set_wmode(cmap, wmode);
+ CMap_add_codespacerange(cmap, lrange_min, lrange_max, 4);
+
+ if (csi) { /* CID */
+ CMap_set_CIDSysInfo(cmap, csi);
+ } else {
+ CMap_set_CIDSysInfo(cmap, &CSI_IDENTITY);
+ }
+
+ if (ttcmap->format == 12) {
+ load_cmap12(ttcmap->map, GIDToCIDMap, cmap);
+ } else if (ttcmap->format == 4) {
+ load_cmap4(ttcmap->map, GIDToCIDMap, cmap);
+ }
+
+ cmap_id = CMap_cache_add(cmap);
+ }
+
+ return cmap_id;
+}
+
+static void
+load_gsub (pdf_obj *conf, otl_gsub *gsub_list, sfnt *sfont)
+{
+ pdf_obj *rule;
+ char *script, *language, *feature;
+ long i, size;
+
+ rule = otl_conf_get_rule(conf);
+ if (!rule)
+ return;
+
+ script = otl_conf_get_script (conf);
+ language = otl_conf_get_language(conf);
+
+ size = pdf_array_length(rule);
+ for (i = 0; i < size; i += 2) {
+ pdf_obj *tmp, *commands;
+ int flag;
+ long j, num_comms;
+
+ tmp = pdf_get_array(rule, i);
+ flag = (int) pdf_number_value(tmp);
+
+ commands = pdf_get_array(rule, i+1);
+ num_comms = pdf_array_length(commands);
+
+ /* (assign|substitute) tag dst src */
+ for (j = 0 ; j < num_comms; j += 4) {
+ tmp = pdf_get_array(commands, 1);
+ if (PDF_OBJ_STRINGTYPE(tmp)) {
+ feature = pdf_string_value(tmp);
+ if (otl_gsub_add_feat(gsub_list,
+ script, language, feature, sfont) < 0) {
+ if (flag == 'p')
+ WARN("No OTL feature matches \"%s.%s.%s\" found.",
+ script, language, feature);
+ else if (flag == 'r')
+ ERROR("No OTL feature matches \"%s.%s.%s\" found.",
+ script, language, feature);
+ }
+ }
+
+ }
+ }
+
+}
+
+static void
+handle_gsub (pdf_obj *conf,
+ tt_cmap *ttcmap, otl_gsub *gsub_list,
+ struct ht_table *unencoded)
+{
+ pdf_obj *rule;
+ char *script, *language, *feature;
+ long i, size;
+
+ if (!conf)
+ return;
+
+ rule = otl_conf_get_rule(conf);
+ if (!rule) {
+ return;
+ }
+
+ if (!PDF_OBJ_ARRAYTYPE(rule)) {
+ WARN("Not arraytype?");
+ return;
+ }
+ script = otl_conf_get_script (conf);
+ language = otl_conf_get_language(conf);
+
+ size = pdf_array_length(rule);
+ for (i = 0; i < size; i += 2) {
+ pdf_obj *tmp, *commands;
+ long j, num_comms;
+ int flag;
+
+ tmp = pdf_get_array(rule, i);
+ flag = (int) pdf_number_value(tmp);
+
+ commands = pdf_get_array (rule, i+1);
+ num_comms = pdf_array_length(commands);
+
+ for (j = 0; j < num_comms; j += 4) {
+ pdf_obj *operator;
+ pdf_obj *src, *dst, *feat;
+ int rv;
+
+ /* (assing|substitute) tag dst src */
+ operator = pdf_get_array(commands, j);
+
+ feat = pdf_get_array(commands, j+1);
+ if (PDF_OBJ_STRINGTYPE(feat))
+ feature = pdf_string_value(feat);
+ else
+ feature = NULL;
+
+ dst = pdf_get_array(commands, j+2);
+ src = pdf_get_array(commands, j+3);
+
+ rv = otl_gsub_select(gsub_list, script, language, feature);
+ if (rv < 0) {
+ if (flag == 'p') {
+ WARN("No GSUB feature %s.%s.%s loaded...",
+ script, language, feature);
+ } else if (flag == 'r') {
+ ERROR("No GSUB feature %s.%s.%s loaded...",
+ script, language, feature);
+ }
+ } else {
+
+ if (verbose > VERBOSE_LEVEL_MIN) {
+ MESG("otf_cmap>> %s:\n", pdf_name_value(operator));
+ }
+
+ if (!strcmp(pdf_name_value(operator), "assign")) {
+ handle_assign(dst, src, flag,
+ gsub_list, ttcmap, unencoded);
+ } else if (!strcmp(pdf_name_value(operator), "substitute")) {
+ handle_subst(dst, src, flag,
+ gsub_list, ttcmap, unencoded);
+ }
+ }
+
+ }
+
+ }
+
+}
+
+static void CDECL
+hval_free (void *hval)
+{
+ RELEASE(hval);
+}
+
+int
+otf_load_Unicode_CMap (const char *map_name, int ttc_index, /* 0 for non-TTC font */
+ const char *otl_tags, int wmode)
+{
+ int cmap_id = -1;
+ int tounicode_id = -1, is_cidfont = 0;
+ sfnt *sfont;
+ unsigned long offset = 0;
+ char *base_name = NULL, *cmap_name = NULL;
+ char *tounicode_name = NULL;
+ FILE *fp = NULL;
+ otl_gsub *gsub_list = NULL;
+ tt_cmap *ttcmap;
+ CMap *cmap, *base, *tounicode = NULL;
+ CIDSysInfo csi = {NULL, NULL, 0};
+ unsigned char *GIDToCIDMap = NULL;
+
+ if (!map_name)
+ return -1;
+
+ if (ttc_index > 999 || ttc_index < 0) {
+ return -1; /* Sorry for this... */
+ }
+
+fprintf(stderr, "otf_load_Unicode_CMap(%s, %d)\n", map_name, ttc_index);
+#ifdef XETEX
+ sfont = NULL; /* FIXME */
+#else
+ fp = DPXFOPEN(map_name, DPX_RES_TYPE_TTFONT);
+ if (!fp) {
+ fp = DPXFOPEN(map_name, DPX_RES_TYPE_OTFONT);
+ }
+ if (!fp) {
+ fp = DPXFOPEN(map_name, DPX_RES_TYPE_DFONT);
+ if (!fp) return -1;
+ sfont = dfont_open(fp, ttc_index);
+ } else {
+ sfont = sfnt_open(fp);
+ }
+#endif
+
+ if (!sfont) {
+ ERROR("Could not open OpenType/TrueType/dfont font file \"%s\"", map_name);
+ }
+ switch (sfont->type) {
+ case SFNT_TYPE_TTC:
+ offset = ttc_read_offset(sfont, ttc_index);
+ if (offset == 0) {
+ ERROR("Invalid TTC index");
+ }
+ break;
+ case SFNT_TYPE_TRUETYPE:
+ case SFNT_TYPE_POSTSCRIPT:
+ offset = 0;
+ break;
+ case SFNT_TYPE_DFONT:
+ offset = sfont->offset;
+ break;
+ default:
+ ERROR("Not a OpenType/TrueType/TTC font?: %s", map_name);
+ break;
+ }
+
+ if (sfnt_read_table_directory(sfont, offset) < 0)
+ ERROR("Could not read OpenType/TrueType table directory.");
+
+ base_name = NEW(strlen(map_name)+strlen("-UCS4-H")+5, char);
+ if (wmode)
+ sprintf(base_name, "%s,%03d-UCS4-V", map_name, ttc_index);
+ else {
+ sprintf(base_name, "%s,%03d-UCS4-H", map_name, ttc_index);
+ }
+
+ if (otl_tags) {
+ cmap_name = NEW(strlen(map_name)+strlen(otl_tags)+strlen("-UCS4-H")+6, char);
+ if (wmode)
+ sprintf(cmap_name, "%s,%03d,%s-UCS4-V", map_name, ttc_index, otl_tags);
+ else
+ sprintf(cmap_name, "%s,%03d,%s-UCS4-H", map_name, ttc_index, otl_tags);
+ } else {
+ cmap_name = NEW(strlen(base_name)+1, char);
+ strcpy(cmap_name, base_name);
+ }
+
+ if (sfont->type == SFNT_TYPE_POSTSCRIPT) {
+ is_cidfont = handle_CIDFont(sfont, &GIDToCIDMap, &csi);
+ } else {
+ is_cidfont = 0;
+ }
+
+ if (is_cidfont) {
+ tounicode_name = NULL;
+ } else {
+ tounicode_name = NEW(strlen(map_name)+strlen("-UTF16")+5, char);
+ sprintf(tounicode_name, "%s,%03d-UTF16", map_name, ttc_index);
+ }
+
+ if (verbose > VERBOSE_LEVEL_MIN) {
+ MESG("\n");
+ MESG("otf_cmap>> Unicode charmap for font=\"%s\" layout=\"%s\"\n",
+ map_name, (otl_tags ? otl_tags : "none"));
+ }
+
+ cmap_id = CMap_cache_find(cmap_name);
+ if (cmap_id >= 0) {
+ RELEASE(cmap_name);
+ RELEASE(base_name);
+ if (GIDToCIDMap)
+ RELEASE(GIDToCIDMap);
+ if (tounicode_name)
+ RELEASE(tounicode_name);
+
+ sfnt_close(sfont);
+ DPXFCLOSE(fp);
+
+ if (verbose > VERBOSE_LEVEL_MIN)
+ MESG("otf_cmap>> Found at cmap_id=%d.\n", cmap_id);
+
+ return cmap_id;
+ }
+
+ ttcmap = tt_cmap_read(sfont, 3, 10); /* Microsoft UCS4 */
+ if (!ttcmap) {
+ ttcmap = tt_cmap_read(sfont, 3, 1); /* Microsoft UCS2 */
+ if (!ttcmap) {
+ ttcmap = tt_cmap_read(sfont, 0, 3); /* Unicode 2.0 or later */
+ if (!ttcmap) {
+ ERROR("Unable to read OpenType/TrueType Unicode cmap table.");
+ }
+ }
+ }
+ cmap_id = load_base_CMap(base_name, wmode,
+ (is_cidfont ? &csi : NULL),
+ GIDToCIDMap, ttcmap);
+ if (cmap_id < 0)
+ ERROR("Failed to read OpenType/TrueType cmap table.");
+
+ if (!otl_tags) {
+ RELEASE(cmap_name);
+ RELEASE(base_name);
+ if (GIDToCIDMap)
+ RELEASE(GIDToCIDMap);
+ if (tounicode_name)
+ RELEASE(tounicode_name);
+ if (is_cidfont) {
+ if (csi.registry)
+ RELEASE(csi.registry);
+ if (csi.ordering)
+ RELEASE(csi.ordering);
+ }
+ tt_cmap_release(ttcmap);
+ sfnt_close(sfont);
+ DPXFCLOSE(fp);
+
+ return cmap_id;
+ }
+
+ base = CMap_cache_get(cmap_id);
+
+ cmap = CMap_new();
+ CMap_set_name (cmap, cmap_name);
+ CMap_set_type (cmap, CMAP_TYPE_CODE_TO_CID);
+ CMap_set_wmode(cmap, wmode);
+ /* CMap_add_codespacerange(cmap, lrange_min, lrange_max, 4); */
+ CMap_set_usecmap(cmap, base);
+ CMap_add_cidchar(cmap, lrange_max, 4, 0); /* FIXME */
+
+ if (is_cidfont) {
+ CMap_set_CIDSysInfo(cmap, &csi);
+ if (csi.registry)
+ RELEASE(csi.registry);
+ if (csi.ordering)
+ RELEASE(csi.ordering);
+ } else {
+ CMap_set_CIDSysInfo(cmap, &CSI_IDENTITY);
+ }
+
+ gsub_list = otl_gsub_new();
+
+ {
+ struct ht_table unencoded;
+ char *conf_name, *opt_tag;
+ pdf_obj *conf, *opt_conf;
+
+ conf_name = NEW(strlen(otl_tags)+1, char);
+ memset (conf_name, 0, strlen(otl_tags)+1);
+ opt_tag = strchr(otl_tags, ':');
+ if (opt_tag) {
+ opt_tag++;
+ strncpy(conf_name, otl_tags,
+ strlen(otl_tags) - strlen(opt_tag) - 1);
+ } else {
+ strcpy(conf_name, otl_tags);
+ }
+
+ if (verbose > VERBOSE_LEVEL_MIN) {
+ MESG("otf_cmap>> Read layout config. \"%s\"\n", conf_name);
+ }
+
+ conf = otl_find_conf(conf_name);
+ if (!conf)
+ ERROR("Layout file \"%s\" not found...", conf_name);
+
+ load_gsub(conf, gsub_list, sfont);
+ if (opt_tag) {
+ if (verbose > VERBOSE_LEVEL_MIN) {
+ MESG("otf_cmap>> Layout option \"%s\" enabled\n", opt_tag);
+ }
+ opt_conf = otl_conf_find_opt(conf, opt_tag);
+ if (!opt_conf)
+ ERROR("There is no option \"%s\" in \"%s\".",
+ opt_tag, conf_name);
+ load_gsub(opt_conf, gsub_list, sfont);
+ }
+
+ ht_init_table(&unencoded, hval_free);
+
+ handle_gsub(conf, ttcmap, gsub_list, &unencoded);
+ if (opt_tag) {
+ opt_conf = otl_conf_find_opt(conf, opt_tag);
+ if (!opt_conf)
+ ERROR("There is no option \"%s\" in \"%s\".",
+ opt_tag, conf_name);
+ handle_gsub(opt_conf, ttcmap, gsub_list, &unencoded);
+ }
+ if (is_cidfont) {
+ tounicode_id = -1;
+ tounicode = NULL;
+ } else {
+ tounicode_id = CMap_cache_find(tounicode_name);
+ if (tounicode_id >= 0)
+ tounicode = CMap_cache_get(tounicode_id);
+ else {
+ tounicode = CMap_new();
+ CMap_set_name (tounicode, tounicode_name);
+ CMap_set_type (tounicode, CMAP_TYPE_TO_UNICODE);
+ CMap_set_wmode(tounicode, 0);
+ CMap_add_codespacerange(tounicode, srange_min, srange_max, 2);
+ CMap_set_CIDSysInfo(tounicode, &CSI_UNICODE);
+ /* FIXME */
+ CMap_add_bfchar(tounicode, srange_min, 2, srange_max, 2);
+ }
+ }
+ create_cmaps(cmap, tounicode, &unencoded, GIDToCIDMap);
+
+ ht_clear_table(&unencoded);
+ RELEASE(conf_name);
+ }
+
+ cmap_id = CMap_cache_add(cmap);
+ if (!is_cidfont && tounicode_id < 0) /* New */
+ CMap_cache_add(tounicode);
+
+ tt_cmap_release(ttcmap);
+ if (gsub_list)
+ otl_gsub_release(gsub_list);
+
+ if (verbose > VERBOSE_LEVEL_MIN) {
+ MESG("otf_cmap>> Overwrite CMap \"%s\" by \"%s\" with usecmap\n",
+ base_name, cmap_name);
+ }
+
+ if (GIDToCIDMap)
+ RELEASE(GIDToCIDMap);
+ if (base_name)
+ RELEASE(base_name);
+ if (cmap_name)
+ RELEASE(cmap_name);
+ if (tounicode_name)
+ RELEASE(tounicode_name);
+
+ sfnt_close(sfont);
+ DPXFCLOSE(fp);
+
+ return cmap_id;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/tt_cmap.h b/Build/source/texk/dvipdf-x/xsrc/tt_cmap.h
new file mode 100644
index 00000000000..30e28950fd4
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/tt_cmap.h
@@ -0,0 +1,80 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _TT_CMAP_H_
+#define _TT_CMAP_H_
+
+#include "sfnt.h"
+
+extern void otf_cmap_set_verbose (void);
+
+/* TrueType cmap table */
+typedef struct
+{
+ USHORT format;
+ USHORT platform;
+ USHORT encoding;
+ ULONG language; /* or version, only for Mac */
+ void *map;
+} tt_cmap;
+
+/* Paltform ID */
+#define TT_MAC 1u
+#define TT_WIN 3u
+
+/* Platform-specific encoding ID */
+
+/* Windows */
+#define TT_WIN_SYMBOL 0u
+#define TT_WIN_UNICODE 1u
+#define TT_WIN_SJIS 2u
+#define TT_WIN_RPC 3u
+#define TT_WIN_BIG5 4u
+#define TT_WIN_WANSUNG 5u
+#define TT_WIN_JOHAB 6u
+#define TT_WIN_UCS4 10u
+
+/* Mac */
+#define TT_MAC_ROMAN 0u
+#define TT_MAC_JAPANESE 1u
+#define TT_MAC_TRADITIONAL_CHINESE 2u
+#define TT_MAC_KOREAN 3u
+#define TT_MAC_SIMPLIFIED_CHINESE 25u
+
+extern tt_cmap *tt_cmap_read (sfnt *sfont, USHORT platform, USHORT encoding);
+
+extern USHORT tt_cmap_lookup (tt_cmap *cmap, long cc);
+extern void tt_cmap_release (tt_cmap *cmap);
+
+#include "pdfobj.h"
+
+/* Indirect reference */
+extern pdf_obj *otf_create_ToUnicode_stream (const char *map_name,
+ int ttc_index,
+ FT_Face face,
+ const char *used_glyphs);
+/* CMap ID */
+extern int otf_load_Unicode_CMap (const char *map_name,
+ int ttc_index,
+ const char *otl_opts, int wmode);
+
+#endif /* _TT_CMAP_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/tt_glyf.c b/Build/source/texk/dvipdf-x/xsrc/tt_glyf.c
new file mode 100644
index 00000000000..5ae56d8d707
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/tt_glyf.c
@@ -0,0 +1,671 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+/*
+ * Subsetting glyf, updating loca, hmtx, ...
+ *
+ */
+
+#include "config.h"
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+#include "dpxutil.h"
+
+#include "sfnt.h"
+#include "tt_table.h"
+#include "tt_glyf.h"
+
+#define NUM_GLYPH_LIMIT 65534
+#define TABLE_DATA_ALLOC_SIZE 40960
+#define GLYPH_ARRAY_ALLOC_SIZE 256
+
+static USHORT
+find_empty_slot (struct tt_glyphs *g)
+{
+ USHORT gid;
+
+ ASSERT(g);
+
+ for (gid = 0; gid < NUM_GLYPH_LIMIT; gid++) {
+ if (!(g->used_slot[gid/8] & (1 << (7 - (gid % 8)))))
+ break;
+ }
+ if (gid == NUM_GLYPH_LIMIT)
+ ERROR("No empty glyph slot available.");
+
+ return gid;
+}
+
+USHORT
+tt_find_glyph (struct tt_glyphs *g, USHORT gid)
+{
+ USHORT idx, new_gid = 0;
+
+ ASSERT(g);
+
+ for (idx = 0; idx < g->num_glyphs; idx++) {
+ if (gid == g->gd[idx].ogid) {
+ new_gid = g->gd[idx].gid;
+ break;
+ }
+ }
+
+ return new_gid;
+}
+
+USHORT
+tt_get_index (struct tt_glyphs *g, USHORT gid)
+{
+ USHORT idx;
+
+ ASSERT(g);
+
+ for (idx = 0; idx < g->num_glyphs; idx++) {
+ if (gid == g->gd[idx].gid)
+ break;
+ }
+ if (idx == g->num_glyphs)
+ idx = 0;
+
+ return idx;
+}
+
+USHORT
+tt_add_glyph (struct tt_glyphs *g, USHORT gid, USHORT new_gid)
+{
+ ASSERT(g);
+
+ if (g->used_slot[new_gid/8] & (1 << (7 - (new_gid % 8)))) {
+ WARN("Slot %u already used.", new_gid);
+ } else {
+ if (g->num_glyphs+1 >= NUM_GLYPH_LIMIT)
+ ERROR("Too many glyphs.");
+
+ if (g->num_glyphs >= g->max_glyphs) {
+ g->max_glyphs += GLYPH_ARRAY_ALLOC_SIZE;
+ g->gd = RENEW(g->gd, g->max_glyphs, struct tt_glyph_desc);
+ }
+ g->gd[g->num_glyphs].gid = new_gid;
+ g->gd[g->num_glyphs].ogid = gid;
+ g->gd[g->num_glyphs].length = 0;
+ g->gd[g->num_glyphs].data = NULL;
+ g->used_slot[new_gid/8] |= (1 << (7 - (new_gid % 8)));
+ g->num_glyphs += 1;
+ }
+
+ if (new_gid > g->last_gid) {
+ g->last_gid = new_gid;
+ }
+
+ return new_gid;
+}
+
+/*
+ * Initialization
+ */
+struct tt_glyphs *
+tt_build_init (void)
+{
+ struct tt_glyphs *g;
+
+ g = NEW(1, struct tt_glyphs);
+
+ g->num_glyphs = 0;
+ g->max_glyphs = 0;
+ g->last_gid = 0;
+ g->emsize = 1;
+ g->default_advh = 0;
+ g->default_tsb = 0;
+ g->gd = NULL;
+ g->used_slot = NEW(8192, unsigned char);
+ memset(g->used_slot, 0, 8192);
+ tt_add_glyph(g, 0, 0);
+
+ return g;
+}
+
+void
+tt_build_finish (struct tt_glyphs *g)
+{
+ if (g) {
+ if (g->gd) {
+ USHORT idx;
+ for (idx = 0; idx < g->num_glyphs; idx++) {
+ if (g->gd[idx].data)
+ RELEASE(g->gd[idx].data);
+ }
+ RELEASE(g->gd);
+ }
+ if (g->used_slot)
+ RELEASE(g->used_slot);
+ RELEASE(g);
+ }
+}
+
+static int CDECL
+glyf_cmp (const void *v1, const void *v2)
+{
+ int cmp = 0;
+ const struct tt_glyph_desc *sv1, *sv2;
+
+ sv1 = (const struct tt_glyph_desc *) v1;
+ sv2 = (const struct tt_glyph_desc *) v2;
+
+ if (sv1->gid == sv2->gid)
+ cmp = 0;
+ else if (sv1->gid < sv2->gid)
+ cmp = -1;
+ else
+ cmp = 1;
+
+ return cmp;
+}
+
+/*
+ * TrueType outline data.
+ */
+#define ARG_1_AND_2_ARE_WORDS (1 << 0)
+#define ARGS_ARE_XY_VALUES (1 << 1)
+#define ROUND_XY_TO_GRID (1 << 2)
+#define WE_HAVE_A_SCALE (1 << 3)
+#define RESERVED (1 << 4)
+#define MORE_COMPONENT (1 << 5)
+#define WE_HAVE_AN_X_AND_Y_SCALE (1 << 6)
+#define WE_HAVE_A_TWO_BY_TWO (1 << 7)
+#define WE_HAVE_INSTRUCTIONS (1 << 8)
+#define USE_MY_METRICS (1 << 9)
+
+int
+tt_build_tables (sfnt *sfont, struct tt_glyphs *g)
+{
+ char *hmtx_table_data = NULL, *loca_table_data = NULL;
+ char *glyf_table_data = NULL;
+ ULONG hmtx_table_size, loca_table_size, glyf_table_size;
+ /* some information available from other TrueType table */
+ struct tt_head_table *head = NULL;
+ struct tt_hhea_table *hhea = NULL;
+ struct tt_maxp_table *maxp = NULL;
+ struct tt_longMetrics *hmtx, *vmtx = NULL;
+ struct tt_os2__table *os2;
+ /* temp */
+ ULONG *location, offset;
+ long i;
+ USHORT *w_stat; /* Estimate most frequently appeared width */
+
+ ASSERT(g);
+
+ if (sfont == NULL ||
+#ifdef XETEX
+ sfont->ft_face == NULL
+#else
+ sfont->stream == NULL
+#endif
+ )
+ ERROR("File not opened.");
+
+ if (sfont->type != SFNT_TYPE_TRUETYPE &&
+ sfont->type != SFNT_TYPE_TTC &&
+ sfont->type != SFNT_TYPE_DFONT)
+ ERROR("Invalid font type");
+
+ if (g->num_glyphs > NUM_GLYPH_LIMIT)
+ ERROR("Too many glyphs.");
+
+ /*
+ * Read head, hhea, maxp, loca:
+ *
+ * unitsPerEm --> head
+ * numHMetrics --> hhea
+ * indexToLocFormat --> head
+ * numGlyphs --> maxp
+ */
+ head = tt_read_head_table(sfont);
+ hhea = tt_read_hhea_table(sfont);
+ maxp = tt_read_maxp_table(sfont);
+
+ if (hhea->metricDataFormat != 0)
+ ERROR("Unknown metricDataFormat.");
+
+ g->emsize = head->unitsPerEm;
+
+ sfnt_locate_table(sfont, "hmtx");
+ hmtx = tt_read_longMetrics(sfont, maxp->numGlyphs, hhea->numOfLongHorMetrics, hhea->numOfExSideBearings);
+
+ os2 = tt_read_os2__table(sfont);
+ if (os2) {
+ g->default_advh = os2->sTypoAscender - os2->sTypoDescender;
+ g->default_tsb = g->default_advh - os2->sTypoAscender;
+ }
+
+ if (sfnt_find_table_pos(sfont, "vmtx") > 0) {
+ struct tt_vhea_table *vhea;
+ vhea = tt_read_vhea_table(sfont);
+ sfnt_locate_table(sfont, "vmtx");
+ vmtx = tt_read_longMetrics(sfont, maxp->numGlyphs, vhea->numOfLongVerMetrics, vhea->numOfExSideBearings);
+ RELEASE(vhea);
+ } else {
+ vmtx = NULL;
+ }
+
+ sfnt_locate_table(sfont, "loca");
+ location = NEW(maxp->numGlyphs + 1, ULONG);
+ if (head->indexToLocFormat == 0) {
+ for (i = 0; i <= maxp->numGlyphs; i++)
+ location[i] = 2*((ULONG) sfnt_get_ushort(sfont));
+ } else if (head->indexToLocFormat == 1) {
+ for (i = 0; i <= maxp->numGlyphs; i++)
+ location[i] = sfnt_get_ulong(sfont);
+ } else {
+ ERROR("Unknown IndexToLocFormat.");
+ }
+
+ w_stat = NEW(g->emsize+2, USHORT);
+ memset(w_stat, 0, sizeof(USHORT)*(g->emsize+2));
+ /*
+ * Read glyf table.
+ */
+ offset = sfnt_locate_table(sfont, "glyf");
+ /*
+ * The num_glyphs may grow when composite glyph is found.
+ * A component of glyph refered by a composite glyph is appended
+ * to used_glyphs if it is not already registered in used_glyphs.
+ * Glyph programs of composite glyphs are modified so that it
+ * correctly refer to new gid of their components.
+ */
+ for (i = 0; i < NUM_GLYPH_LIMIT; i++) {
+ USHORT gid; /* old gid */
+ ULONG loc, len;
+ BYTE *p, *endptr;
+ SHORT number_of_contours;
+
+ if (i >= g->num_glyphs) /* finished */
+ break;
+
+ gid = g->gd[i].ogid;
+ if (gid >= maxp->numGlyphs)
+ ERROR("Invalid glyph index (gid %u)", gid);
+
+ loc = location[gid];
+ len = location[gid+1] - loc;
+ g->gd[i].advw = hmtx[gid].advance;
+ g->gd[i].lsb = hmtx[gid].sideBearing;
+ if (vmtx) {
+ g->gd[i].advh = vmtx[gid].advance;
+ g->gd[i].tsb = vmtx[gid].sideBearing;
+ } else {
+ g->gd[i].advh = g->default_advh;
+ g->gd[i].tsb = g->default_tsb;
+ }
+ g->gd[i].length = len;
+ g->gd[i].data = NULL;
+ if (g->gd[i].advw <= g->emsize) {
+ w_stat[g->gd[i].advw] += 1;
+ } else {
+ w_stat[g->emsize+1] += 1; /* larger than em */
+ }
+
+ if (len == 0) { /* Does not contains any data. */
+ continue;
+ } else if (len < 10) {
+ ERROR("Invalid TrueType glyph data (gid %u).", gid);
+ }
+
+ g->gd[i].data = p = NEW(len, BYTE);
+ endptr = p + len;
+
+ sfnt_seek_set(sfont, offset+loc);
+ number_of_contours = sfnt_get_short(sfont);
+ p += sfnt_put_short(p, number_of_contours);
+
+ /* BoundingBox: FWord x 4 */
+ g->gd[i].llx = sfnt_get_short(sfont);
+ g->gd[i].lly = sfnt_get_short(sfont);
+ g->gd[i].urx = sfnt_get_short(sfont);
+ g->gd[i].ury = sfnt_get_short(sfont);
+ /* _FIXME_ */
+#if 1
+ if (!vmtx) /* vertOriginY == sTypeAscender */
+ g->gd[i].tsb = g->default_advh - g->default_tsb - g->gd[i].ury;
+#endif
+ p += sfnt_put_short(p, g->gd[i].llx);
+ p += sfnt_put_short(p, g->gd[i].lly);
+ p += sfnt_put_short(p, g->gd[i].urx);
+ p += sfnt_put_short(p, g->gd[i].ury);
+
+ /* Read evrything else. */
+ sfnt_read(p, len - 10, sfont);
+ /*
+ * Fix GIDs of composite glyphs.
+ */
+ if (number_of_contours < 0) {
+ USHORT flags, cgid, new_gid; /* flag, gid of a component */
+ do {
+ if (p >= endptr)
+ ERROR("Invalid TrueType glyph data (gid %u): %u bytes", gid, len);
+ /*
+ * Flags and gid of component glyph are both USHORT.
+ */
+ flags = ((*p) << 8)| *(p+1);
+ p += 2;
+ cgid = ((*p) << 8)| *(p+1);
+ if (cgid >= maxp->numGlyphs) {
+ ERROR("Invalid gid (%u > %u) in composite glyph %u.", cgid, maxp->numGlyphs, gid);
+ }
+ new_gid = tt_find_glyph(g, cgid);
+ if (new_gid == 0) {
+ new_gid = tt_add_glyph(g, cgid, find_empty_slot(g));
+ }
+ p += sfnt_put_ushort(p, new_gid);
+ /*
+ * Just skip remaining part.
+ */
+ p += (flags & ARG_1_AND_2_ARE_WORDS) ? 4 : 2;
+ if (flags & WE_HAVE_A_SCALE) /* F2Dot14 */
+ p += 2;
+ else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) /* F2Dot14 x 2 */
+ p += 4;
+ else if (flags & WE_HAVE_A_TWO_BY_TWO) /* F2Dot14 x 4 */
+ p += 8;
+ } while (flags & MORE_COMPONENT);
+ /*
+ * TrueType instructions comes here:
+ * length_of_instruction (ushort)
+ * instruction (byte * length_of_instruction)
+ */
+ }
+ }
+ RELEASE(location);
+ RELEASE(hmtx);
+ if (vmtx)
+ RELEASE(vmtx);
+
+ {
+ int max_count = -1;
+
+ g->dw = g->gd[0].advw;
+ for (i = 0; i < g->emsize + 1; i++) {
+ if (w_stat[i] > max_count) {
+ max_count = w_stat[i];
+ g->dw = i;
+ }
+ }
+ }
+ RELEASE(w_stat);
+
+ qsort(g->gd, g->num_glyphs, sizeof(struct tt_glyph_desc), glyf_cmp);
+ {
+ USHORT prev, last_advw;
+ char *p, *q;
+ int padlen, num_hm_known;
+
+ glyf_table_size = 0UL;
+ num_hm_known = 0;
+ last_advw = g->gd[g->num_glyphs - 1].advw;
+ for (i = g->num_glyphs - 1; i >= 0; i--) {
+ padlen = (g->gd[i].length % 4) ? (4 - (g->gd[i].length % 4)) : 0;
+ glyf_table_size += g->gd[i].length + padlen;
+ if (!num_hm_known && last_advw != g->gd[i].advw) {
+ hhea->numOfLongHorMetrics = g->gd[i].gid + 2;
+ num_hm_known = 1;
+ }
+ }
+ /* All advance widths are same. */
+ if (!num_hm_known) {
+ hhea->numOfLongHorMetrics = 1;
+ }
+ hmtx_table_size = hhea->numOfLongHorMetrics * 2 + (g->last_gid + 1) * 2;
+
+ /*
+ * Choosing short format does not always give good result
+ * when compressed. Sometimes increases size.
+ */
+ if (glyf_table_size < 0x20000UL) {
+ head->indexToLocFormat = 0;
+ loca_table_size = (g->last_gid + 2)*2;
+ } else {
+ head->indexToLocFormat = 1;
+ loca_table_size = (g->last_gid + 2)*4;
+ }
+
+ hmtx_table_data = p = NEW(hmtx_table_size, char);
+ loca_table_data = q = NEW(loca_table_size, char);
+ glyf_table_data = NEW(glyf_table_size, char);
+
+ offset = 0UL; prev = 0;
+ for (i = 0; i < g->num_glyphs; i++) {
+ long gap, j;
+ gap = (long) g->gd[i].gid - prev - 1;
+ for (j = 1; j <= gap; j++) {
+ if (prev + j == hhea->numOfLongHorMetrics - 1) {
+ p += sfnt_put_ushort(p, last_advw);
+ } else if (prev + j < hhea->numOfLongHorMetrics) {
+ p += sfnt_put_ushort(p, 0);
+ }
+ p += sfnt_put_short (p, 0);
+ if (head->indexToLocFormat == 0) {
+ q += sfnt_put_ushort(q, (USHORT) (offset/2));
+ } else {
+ q += sfnt_put_ulong(q, offset);
+ }
+ }
+ padlen = (g->gd[i].length % 4) ? (4 - (g->gd[i].length % 4)) : 0;
+ if (g->gd[i].gid < hhea->numOfLongHorMetrics) {
+ p += sfnt_put_ushort(p, g->gd[i].advw);
+ }
+ p += sfnt_put_short (p, g->gd[i].lsb);
+ if (head->indexToLocFormat == 0) {
+ q += sfnt_put_ushort(q, (USHORT) (offset/2));
+ } else {
+ q += sfnt_put_ulong(q, offset);
+ }
+ memset(glyf_table_data + offset, 0, g->gd[i].length + padlen);
+ memcpy(glyf_table_data + offset, g->gd[i].data, g->gd[i].length);
+ offset += g->gd[i].length + padlen;
+ prev = g->gd[i].gid;
+ /* free data here since it consume much memory */
+ RELEASE(g->gd[i].data);
+ g->gd[i].length = 0; g->gd[i].data = NULL;
+ }
+ if (head->indexToLocFormat == 0) {
+ q += sfnt_put_ushort(q, (USHORT) (offset/2));
+ } else {
+ q += sfnt_put_ulong(q, offset);
+ }
+
+ sfnt_set_table(sfont, "hmtx", (char *) hmtx_table_data, hmtx_table_size);
+ sfnt_set_table(sfont, "loca", (char *) loca_table_data, loca_table_size);
+ sfnt_set_table(sfont, "glyf", (char *) glyf_table_data, glyf_table_size);
+ }
+
+ head->checkSumAdjustment = 0;
+ maxp->numGlyphs = g->last_gid + 1;
+
+ /* TODO */
+ sfnt_set_table(sfont, "maxp", tt_pack_maxp_table(maxp), TT_MAXP_TABLE_SIZE);
+ sfnt_set_table(sfont, "hhea", tt_pack_hhea_table(hhea), TT_HHEA_TABLE_SIZE);
+ sfnt_set_table(sfont, "head", tt_pack_head_table(head), TT_HEAD_TABLE_SIZE);
+ RELEASE(maxp);
+ RELEASE(hhea);
+ RELEASE(head);
+ if (os2)
+ RELEASE(os2);
+
+ return 0;
+}
+
+int
+tt_get_metrics (sfnt *sfont, struct tt_glyphs *g)
+{
+ struct tt_head_table *head = NULL;
+ struct tt_hhea_table *hhea = NULL;
+ struct tt_maxp_table *maxp = NULL;
+ struct tt_longMetrics *hmtx, *vmtx = NULL;
+ struct tt_os2__table *os2;
+ /* temp */
+ ULONG *location, offset;
+ long i;
+ USHORT *w_stat;
+
+ ASSERT(g);
+
+ if (sfont == NULL ||
+#ifdef XETEX
+ sfont->ft_face == NULL
+#else
+ sfont->stream == NULL
+#endif
+ )
+ ERROR("File not opened.");
+
+ if (sfont->type != SFNT_TYPE_TRUETYPE &&
+ sfont->type != SFNT_TYPE_TTC &&
+ sfont->type != SFNT_TYPE_DFONT)
+ ERROR("Invalid font type");
+
+ /*
+ * Read head, hhea, maxp, loca:
+ *
+ * unitsPerEm --> head
+ * numHMetrics --> hhea
+ * indexToLocFormat --> head
+ * numGlyphs --> maxp
+ */
+ head = tt_read_head_table(sfont);
+ hhea = tt_read_hhea_table(sfont);
+ maxp = tt_read_maxp_table(sfont);
+
+ if (hhea->metricDataFormat != 0)
+ ERROR("Unknown metricDataFormat.");
+
+ g->emsize = head->unitsPerEm;
+
+ sfnt_locate_table(sfont, "hmtx");
+ hmtx = tt_read_longMetrics(sfont, maxp->numGlyphs, hhea->numOfLongHorMetrics, hhea->numOfExSideBearings);
+
+ os2 = tt_read_os2__table(sfont);
+ g->default_advh = os2->sTypoAscender - os2->sTypoDescender;
+ g->default_tsb = g->default_advh - os2->sTypoAscender;
+
+ if (sfnt_find_table_pos(sfont, "vmtx") > 0) {
+ struct tt_vhea_table *vhea;
+ vhea = tt_read_vhea_table(sfont);
+ sfnt_locate_table(sfont, "vmtx");
+ vmtx = tt_read_longMetrics(sfont, maxp->numGlyphs, vhea->numOfLongVerMetrics, vhea->numOfExSideBearings);
+ RELEASE(vhea);
+ } else {
+ vmtx = NULL;
+ }
+
+ sfnt_locate_table(sfont, "loca");
+ location = NEW(maxp->numGlyphs + 1, ULONG);
+ if (head->indexToLocFormat == 0) {
+ for (i = 0; i <= maxp->numGlyphs; i++)
+ location[i] = 2*((ULONG) sfnt_get_ushort(sfont));
+ } else if (head->indexToLocFormat == 1) {
+ for (i = 0; i <= maxp->numGlyphs; i++)
+ location[i] = sfnt_get_ulong(sfont);
+ } else {
+ ERROR("Unknown IndexToLocFormat.");
+ }
+
+ w_stat = NEW(g->emsize+2, USHORT);
+ memset(w_stat, 0, sizeof(USHORT)*(g->emsize+2));
+ /*
+ * Read glyf table.
+ */
+ offset = sfnt_locate_table(sfont, "glyf");
+ for (i = 0; i < g->num_glyphs; i++) {
+ USHORT gid; /* old gid */
+ ULONG loc, len;
+
+ gid = g->gd[i].ogid;
+ if (gid >= maxp->numGlyphs)
+ ERROR("Invalid glyph index (gid %u)", gid);
+
+ loc = location[gid];
+ len = location[gid+1] - loc;
+ g->gd[i].advw = hmtx[gid].advance;
+ g->gd[i].lsb = hmtx[gid].sideBearing;
+ if (vmtx) {
+ g->gd[i].advh = vmtx[gid].advance;
+ g->gd[i].tsb = vmtx[gid].sideBearing;
+ } else {
+ g->gd[i].advh = g->default_advh;
+ g->gd[i].tsb = g->default_tsb;
+ }
+ g->gd[i].length = len;
+ g->gd[i].data = NULL;
+
+ if (g->gd[i].advw <= g->emsize) {
+ w_stat[g->gd[i].advw] += 1;
+ } else {
+ w_stat[g->emsize+1] += 1; /* larger than em */
+ }
+
+ if (len == 0) { /* Does not contains any data. */
+ continue;
+ } else if (len < 10) {
+ ERROR("Invalid TrueType glyph data (gid %u).", gid);
+ }
+
+ sfnt_seek_set(sfont, offset+loc);
+ (void) sfnt_get_short(sfont);
+
+ /* BoundingBox: FWord x 4 */
+ g->gd[i].llx = sfnt_get_short(sfont);
+ g->gd[i].lly = sfnt_get_short(sfont);
+ g->gd[i].urx = sfnt_get_short(sfont);
+ g->gd[i].ury = sfnt_get_short(sfont);
+ /* _FIXME_ */
+#if 1
+ if (!vmtx) /* vertOriginY == sTypeAscender */
+ g->gd[i].tsb = g->default_advh - g->default_tsb - g->gd[i].ury;
+#endif
+ }
+ RELEASE(location);
+ RELEASE(hmtx);
+ RELEASE(maxp);
+ RELEASE(hhea);
+ RELEASE(head);
+ RELEASE(os2);
+
+ if (vmtx)
+ RELEASE(vmtx);
+
+ {
+ int max_count = -1;
+
+ g->dw = g->gd[0].advw;
+ for (i = 0; i < g->emsize + 1; i++) {
+ if (w_stat[i] > max_count) {
+ max_count = w_stat[i];
+ g->dw = i;
+ }
+ }
+ }
+ RELEASE(w_stat);
+
+
+ return 0;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/tt_post.c b/Build/source/texk/dvipdf-x/xsrc/tt_post.c
new file mode 100644
index 00000000000..0deb3ab8b23
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/tt_post.c
@@ -0,0 +1,276 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#include "system.h"
+#include "error.h"
+#include "mem.h"
+
+#include "dpxfile.h"
+
+#include "sfnt.h"
+
+#include "tt_post.h"
+
+static const char *macglyphorder[258];
+
+/* offset from begenning of the post table */
+#define NAME_STR_OFFSET 32
+
+static int
+read_v2_post_names (struct tt_post_table *post, sfnt *sfont)
+{
+ USHORT i, idx, *indices, maxidx;
+ int len;
+
+ post->numberOfGlyphs = sfnt_get_ushort(sfont);
+
+ indices = NEW(post->numberOfGlyphs, USHORT);
+ maxidx = 257;
+ for (i = 0;
+ i < post->numberOfGlyphs; i++) {
+ idx = sfnt_get_ushort(sfont);
+ if (idx >= 258) {
+ if (idx > maxidx)
+ maxidx = idx;
+ if (idx > 32767) {
+ /* Although this is strictly speaking out of spec, it seems to work
+ and there are real-life fonts that use it.
+ We show a warning only once, instead of thousands of times */
+ static char warning_issued = 0;
+ if (!warning_issued) {
+ WARN("TrueType post table name index %u > 32767", idx);
+ warning_issued = 1;
+ }
+ /* In a real-life large font, (x)dvipdfmx crashes if we use
+ nonvanishing idx in the case of idx > 32767.
+ If we set idx = 0, (x)dvipdfmx works fine for the font and
+ created pdf seems fine. The post table may not be important
+ in such a case */
+ idx = 0;
+ }
+ }
+ indices[i] = idx;
+ }
+
+ post->count = maxidx - 257;
+ if (post->count < 1) {
+ post->names = NULL;
+ } else {
+ post->names = NEW(post->count, char *);
+ for (i = 0; i < post->count; i++) { /* read Pascal strings */
+ len = sfnt_get_byte(sfont);
+ if (len > 0) {
+ post->names[i] = NEW(len + 1, char);
+ sfnt_read((unsigned char*)(post->names[i]), len, sfont);
+ post->names[i][len] = 0;
+ } else {
+ post->names[i] = NULL;
+ }
+ }
+ }
+
+ post->glyphNamePtr = NEW(post->numberOfGlyphs, const char *);
+ for (i = 0; i < post->numberOfGlyphs; i++) {
+ idx = indices[i];
+ if (idx < 258) {
+ post->glyphNamePtr[i] = macglyphorder[idx];
+ } else if (idx - 258 < post->count) {
+ post->glyphNamePtr[i] = post->names[idx - 258];
+ } else {
+ WARN("Invalid glyph name index number: %u (>= %u)",
+ idx, post->count + 258);
+ RELEASE(indices);
+ return -1;
+ }
+ }
+ RELEASE(indices);
+
+ return 0;
+}
+
+struct tt_post_table *
+tt_read_post_table (sfnt *sfont)
+{
+ struct tt_post_table *post;
+
+ /* offset = */ sfnt_locate_table(sfont, "post");
+
+ post = NEW(1, struct tt_post_table);
+
+ post->Version = sfnt_get_ulong(sfont); /* Fixed */
+ post->italicAngle = sfnt_get_ulong(sfont); /* Fixed */
+ post->underlinePosition = sfnt_get_short(sfont); /* FWord */
+ post->underlineThickness = sfnt_get_short(sfont); /* FWord */
+ post->isFixedPitch = sfnt_get_ulong(sfont);
+ post->minMemType42 = sfnt_get_ulong(sfont);
+ post->maxMemType42 = sfnt_get_ulong(sfont);
+ post->minMemType1 = sfnt_get_ulong(sfont);
+ post->maxMemType1 = sfnt_get_ulong(sfont);
+
+ post->numberOfGlyphs = 0;
+ post->glyphNamePtr = NULL;
+ post->count = 0;
+ post->names = NULL;
+
+ if (post->Version == 0x00010000UL) {
+ post->numberOfGlyphs = 258; /* wrong */
+ post->glyphNamePtr = macglyphorder;
+ post->count = 0;
+ post->names = NULL;
+ } else if (post->Version == 0x00025000UL) {
+ WARN("TrueType 'post' version 2.5 found (deprecated)");
+ post->numberOfGlyphs = 0; /* wrong */
+ post->glyphNamePtr = NULL;
+ post->count = 0;
+ post->names = NULL;
+ } else if (post->Version == 0x00020000UL) {
+ if (read_v2_post_names(post, sfont) < 0) {
+ WARN("Invalid version 2.0 'post' table");
+ tt_release_post_table(post);
+ post = NULL;
+ }
+ } else if (post->Version == 0x00030000UL) { /* no glyph names provided */
+ post->numberOfGlyphs = 0; /* wrong */
+ post->glyphNamePtr = NULL;
+ post->count = 0;
+ post->names = NULL;
+ } else if (post->Version == 0x00040000UL) { /* Apple format for printer-based fonts */
+ post->numberOfGlyphs = 0; /* don't bother constructing char names, not sure if they'll ever be needed */
+ post->glyphNamePtr = NULL;
+ post->count = 0;
+ post->names = NULL;
+ } else {
+ WARN("Unknown 'post' version: %08X", post->Version);
+ tt_release_post_table(post);
+ post = NULL;
+ }
+
+ return post;
+}
+
+USHORT
+tt_lookup_post_table (struct tt_post_table *post, const char *glyphname)
+{
+ USHORT gid;
+
+ ASSERT(post && glyphname);
+
+ for (gid = 0; gid < post->count; gid++) {
+ if (post->glyphNamePtr[gid] &&
+ !strcmp(glyphname, post->glyphNamePtr[gid])) {
+ return gid;
+ }
+ }
+
+ return 0;
+}
+
+void
+tt_release_post_table (struct tt_post_table *post)
+{
+ USHORT i;
+
+ ASSERT(post);
+
+ if (post->glyphNamePtr && post->Version != 0x00010000UL)
+ RELEASE((void *)post->glyphNamePtr);
+ if (post->names) {
+ for (i = 0; i < post->count; i++) {
+ if (post->names[i])
+ RELEASE(post->names[i]);
+ }
+ RELEASE(post->names);
+ }
+ post->count = 0;
+ post->glyphNamePtr = NULL;
+ post->names = NULL;
+
+ RELEASE(post);
+
+ return;
+}
+
+/* Macintosh glyph order - from apple's TTRefMan */
+static const char *
+macglyphorder[258] = {
+ /* 0x0000 */
+ ".notdef", ".null", "nonmarkingreturn", "space", "exclam", "quotedbl",
+ "numbersign", "dollar", "percent", "ampersand", "quotesingle",
+ "parenleft", "parenright", "asterisk", "plus", "comma",
+ /* 0x0010 */
+ "hyphen", "period", "slash", "zero", "one", "two", "three", "four",
+ "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less",
+ /* 0x0020 */
+ "equal", "greater", "question", "at", "A", "B", "C", "D",
+ "E", "F", "G", "H", "I", "J", "K", "L",
+ /* 0x0030 */
+ "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
+ "Y", "Z", "bracketleft", "backslash",
+ /* 0x0040 */
+ "bracketright", "asciicircum", "underscore", "grave",
+ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
+ /* 0x0050 */
+ "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
+ "y", "z", "braceleft", "bar",
+ /* 0x0060 */
+ "braceright", "asciitilde", "Adieresis", "Aring", "Ccedilla",
+ "Eacute", "Ntilde", "Odieresis", "Udieresis", "aacute", "agrave",
+ "acircumflex", "adieresis", "atilde", "aring", "ccedilla",
+ /* 0x0070 */
+ "eacute", "egrave", "ecircumflex", "edieresis", "iacute", "igrave",
+ "icircumflex", "idieresis", "ntilde", "oacute", "ograve", "ocircumflex",
+ "odieresis", "otilde", "uacute", "ugrave",
+ /* 0x0080 */
+ "ucircumflex", "udieresis", "dagger", "degree", "cent", "sterling",
+ "section", "bullet", "paragraph", "germandbls", "registered",
+ "copyright", "trademark", "acute", "dieresis", "notequal",
+ /* 0x0090 */
+ "AE", "Oslash", "infinity", "plusminus", "lessequal", "greaterequal",
+ "yen", "mu", "partialdiff", "summation", "product", "pi", "integral",
+ "ordfeminine", "ordmasculine", "Omega",
+ /* 0x00a0 */
+ "ae", "oslash", "questiondown", "exclamdown", "logicalnot", "radical",
+ "florin", "approxequal", "Delta", "guillemotleft", "guillemotright",
+ "ellipsis", "nonbreakingspace", "Agrave", "Atilde", "Otilde",
+ /* 0x00b0 */
+ "OE", "oe", "endash", "emdash", "quotedblleft", "quotedblright",
+ "quoteleft", "quoteright", "divide", "lozenge", "ydieresis",
+ "Ydieresis", "fraction", "currency", "guilsinglleft", "guilsinglright",
+ /* 0x00c0 */
+ "fi", "fl", "daggerdbl", "periodcentered", "quotesinglbase",
+ "quotedblbase", "perthousand", "Acircumflex", "Ecircumflex", "Aacute",
+ "Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis", "Igrave",
+ /* 0x00d0 */
+ "Oacute", "Ocircumflex", "apple", "Ograve", "Uacute", "Ucircumflex",
+ "Ugrave", "dotlessi", "circumflex", "tilde", "macron", "breve",
+ "dotaccent", "ring", "cedilla", "hungarumlaut",
+ /* 0x00e0 */
+ "ogonek", "caron", "Lslash", "lslash", "Scaron", "scaron", "Zcaron",
+ "zcaron", "brokenbar", "Eth", "eth", "Yacute", "yacute", "Thorn",
+ "thorn", "minus",
+ /* 0x00f0 */
+ "multiply", "onesuperior", "twosuperior", "threesuperior", "onehalf",
+ "onequarter", "threequarters", "franc", "Gbreve", "gbreve", "Idotaccent",
+ "Scedilla", "scedilla", "Cacute", "cacute", "Ccaron",
+ /* 0x0100 */
+ "ccaron", "dcroat"
+};
diff --git a/Build/source/texk/dvipdf-x/xsrc/tt_table.c b/Build/source/texk/dvipdf-x/xsrc/tt_table.c
new file mode 100644
index 00000000000..88b3a33c781
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/tt_table.c
@@ -0,0 +1,505 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#include <stdio.h>
+
+#include "system.h"
+#include "error.h"
+#include "mem.h"
+#include "mfileio.h"
+
+#include "sfnt.h"
+#include "tt_table.h"
+
+/*
+ tables contains information refered by other tables
+ maxp->numGlyphs, etc --> loca, etc
+ hhea->numOfLongHorMetrics --> hmtx
+ head->indexToLocFormat --> loca
+ head->glyphDataFormat --> glyf
+*/
+
+char *tt_pack_head_table (struct tt_head_table *table)
+{
+ int i;
+ char *p, *data;
+
+ if (table == NULL)
+ ERROR("passed NULL pointer\n");
+
+ p = data = NEW(TT_HEAD_TABLE_SIZE, char);
+ p += sfnt_put_ulong(p, table->version);
+ p += sfnt_put_ulong(p, table->fontRevision);
+ p += sfnt_put_ulong(p, table->checkSumAdjustment);
+ p += sfnt_put_ulong(p, table->magicNumber);
+ p += sfnt_put_ushort(p, table->flags);
+ p += sfnt_put_ushort(p, table->unitsPerEm);
+ for (i=0; i<8; i++) {
+ *(p++) = (table->created)[i];
+ }
+ for (i=0; i<8; i++) {
+ *(p++) = (table->modified)[i];
+ }
+ p += sfnt_put_short(p, table->xMin);
+ p += sfnt_put_short(p, table->yMin);
+ p += sfnt_put_short(p, table->xMax);
+ p += sfnt_put_short(p, table->yMax);
+ p += sfnt_put_ushort(p, table->macStyle);
+ p += sfnt_put_ushort(p, table->lowestRecPPEM);
+ p += sfnt_put_short(p, table->fontDirectionHint);
+ p += sfnt_put_short(p, table->indexToLocFormat);
+ p += sfnt_put_short(p, table->glyphDataFormat);
+
+ return data;
+}
+
+struct tt_head_table *tt_read_head_table (sfnt *sfont)
+{
+ int i;
+ struct tt_head_table *table = NULL;
+
+ table = NEW(1, struct tt_head_table);
+
+ sfnt_locate_table(sfont, "head");
+
+ table->version = sfnt_get_ulong(sfont);
+ table->fontRevision = sfnt_get_ulong(sfont);
+ table->checkSumAdjustment = sfnt_get_ulong(sfont);
+ table->magicNumber = sfnt_get_ulong(sfont);
+ table->flags = sfnt_get_ushort(sfont);
+ table->unitsPerEm = sfnt_get_ushort(sfont);
+ for (i=0; i<8; i++) {
+ (table->created)[i] = sfnt_get_byte (sfont);
+ }
+ for (i=0; i<8; i++) {
+ (table->modified)[i] = sfnt_get_byte (sfont);
+ }
+ table->xMin = sfnt_get_short(sfont);
+ table->yMin = sfnt_get_short(sfont);
+ table->xMax = sfnt_get_short(sfont);
+ table->yMax = sfnt_get_short(sfont);
+ table->macStyle = sfnt_get_short(sfont);
+ table->lowestRecPPEM = sfnt_get_short(sfont);
+ table->fontDirectionHint = sfnt_get_short(sfont);
+ table->indexToLocFormat = sfnt_get_short(sfont);
+ table->glyphDataFormat = sfnt_get_short(sfont);
+
+ return table;
+}
+
+char *tt_pack_maxp_table (struct tt_maxp_table *table)
+{
+ char *p, *data;
+
+ p = data = NEW(TT_MAXP_TABLE_SIZE, char);
+ p += sfnt_put_ulong(p, table->version);
+ p += sfnt_put_ushort(p, table->numGlyphs);
+ p += sfnt_put_ushort(p, table->maxPoints);
+ p += sfnt_put_ushort(p, table->maxContours);
+ p += sfnt_put_ushort(p, table->maxComponentPoints);
+ p += sfnt_put_ushort(p, table->maxComponentContours);
+ p += sfnt_put_ushort(p, table->maxZones);
+ p += sfnt_put_ushort(p, table->maxTwilightPoints);
+ p += sfnt_put_ushort(p, table->maxStorage);
+ p += sfnt_put_ushort(p, table->maxFunctionDefs);
+ p += sfnt_put_ushort(p, table->maxInstructionDefs);
+ p += sfnt_put_ushort(p, table->maxStackElements);
+ p += sfnt_put_ushort(p, table->maxSizeOfInstructions);
+ p += sfnt_put_ushort(p, table->maxComponentElements);
+ p += sfnt_put_ushort(p, table->maxComponentDepth);
+
+ return data;
+}
+
+struct tt_maxp_table *tt_read_maxp_table (sfnt *sfont)
+{
+ struct tt_maxp_table *table = NULL;
+
+ table = NEW(1, struct tt_maxp_table);
+
+ sfnt_locate_table(sfont, "maxp");
+ table->version = sfnt_get_ulong(sfont);
+ table->numGlyphs = sfnt_get_ushort(sfont);
+ table->maxPoints = sfnt_get_ushort(sfont);
+ table->maxContours = sfnt_get_ushort(sfont);
+ table->maxComponentPoints = sfnt_get_ushort(sfont);
+ table->maxComponentContours = sfnt_get_ushort(sfont);
+ table->maxZones = sfnt_get_ushort(sfont);
+ table->maxTwilightPoints = sfnt_get_ushort(sfont);
+ table->maxStorage = sfnt_get_ushort(sfont);
+ table->maxFunctionDefs = sfnt_get_ushort(sfont);
+ table->maxInstructionDefs = sfnt_get_ushort(sfont);
+ table->maxStackElements = sfnt_get_ushort(sfont);
+ table->maxSizeOfInstructions = sfnt_get_ushort(sfont);
+ table->maxComponentElements = sfnt_get_ushort(sfont);
+ table->maxComponentDepth = sfnt_get_ushort(sfont);
+
+ return table;
+}
+
+char *tt_pack_hhea_table (struct tt_hhea_table *table)
+{
+ int i;
+ char *p, *data;
+
+ p = data = NEW(TT_HHEA_TABLE_SIZE, char);
+ p += sfnt_put_ulong(p, table->version);
+ p += sfnt_put_short(p, table->ascent);
+ p += sfnt_put_short(p, table->descent);
+ p += sfnt_put_short(p, table->lineGap);
+ p += sfnt_put_ushort(p, table->advanceWidthMax);
+ p += sfnt_put_short(p, table->minLeftSideBearing);
+ p += sfnt_put_short(p, table->minRightSideBearing);
+ p += sfnt_put_short(p, table->xMaxExtent);
+ p += sfnt_put_short(p, table->caretSlopeRise);
+ p += sfnt_put_short(p, table->caretSlopeRun);
+ p += sfnt_put_short(p, table->caretOffset);
+ for (i = 0; i < 4; i++) {
+ p += sfnt_put_short(p, table->reserved[i]);
+ }
+ p += sfnt_put_short(p, table->metricDataFormat);
+ p += sfnt_put_ushort(p, table->numOfLongHorMetrics);
+
+ return data;
+}
+
+struct tt_hhea_table *
+tt_read_hhea_table (sfnt *sfont)
+{
+ int i;
+ ULONG len;
+ struct tt_hhea_table *table = NULL;
+
+ sfnt_locate_table(sfont, "hhea");
+
+ table = NEW(1, struct tt_hhea_table);
+ table->version = sfnt_get_ulong(sfont);
+ table->ascent = sfnt_get_short (sfont);
+ table->descent = sfnt_get_short(sfont);
+ table->lineGap = sfnt_get_short(sfont);
+ table->advanceWidthMax = sfnt_get_ushort(sfont);
+ table->minLeftSideBearing = sfnt_get_short(sfont);
+ table->minRightSideBearing = sfnt_get_short(sfont);
+ table->xMaxExtent = sfnt_get_short(sfont);
+ table->caretSlopeRise = sfnt_get_short(sfont);
+ table->caretSlopeRun = sfnt_get_short(sfont);
+ table->caretOffset = sfnt_get_short(sfont);
+ for(i = 0; i < 4; i++) {
+ table->reserved[i] = sfnt_get_short(sfont);
+ }
+ table->metricDataFormat = sfnt_get_short(sfont);
+ if (table->metricDataFormat != 0)
+ ERROR("unknown metricDataFormat");
+ table->numOfLongHorMetrics = sfnt_get_ushort(sfont);
+
+ len = sfnt_find_table_len(sfont, "hmtx");
+ table->numOfExSideBearings = (USHORT)((len - table->numOfLongHorMetrics * 4) / 2);
+
+ return table;
+}
+
+/* vhea */
+#if 0
+char *
+tt_pack_vhea_table (struct tt_vhea_table *table)
+{
+ int i;
+ char *p, *data;
+
+ p = data = NEW(TT_VHEA_TABLE_SIZE, char);
+ p += sfnt_put_ulong(p, table->version);
+ p += sfnt_put_short(p, table->vertTypoAscender);
+ p += sfnt_put_short(p, table->vertTypoDescender);
+ p += sfnt_put_short(p, table->vertTypoLineGap);
+ p += sfnt_put_short(p, table->advanceHeightMax); /* ushort ? */
+ p += sfnt_put_short(p, table->minTopSideBearing);
+ p += sfnt_put_short(p, table->minBottomSideBearing);
+ p += sfnt_put_short(p, table->yMaxExtent);
+ p += sfnt_put_short(p, table->caretSlopeRise);
+ p += sfnt_put_short(p, table->caretSlopeRun);
+ p += sfnt_put_short(p, table->caretOffset);
+ for(i = 0; i < 4; i++) {
+ p += sfnt_put_short(p, table->reserved[i]);
+ }
+ p += sfnt_put_short(p, table->metricDataFormat);
+ p += sfnt_put_ushort(p, table->numOfLongVerMetrics);
+
+ return data;
+}
+#endif
+
+struct tt_vhea_table *tt_read_vhea_table (sfnt *sfont)
+{
+ int i;
+ ULONG len;
+ struct tt_vhea_table *table = NULL;
+
+ table = NEW(1, struct tt_vhea_table);
+
+ sfnt_locate_table(sfont, "vhea");
+ table->version = sfnt_get_ulong(sfont);
+ table->vertTypoAscender = sfnt_get_short (sfont);
+ table->vertTypoDescender = sfnt_get_short(sfont);
+ table->vertTypoLineGap = sfnt_get_short(sfont);
+ table->advanceHeightMax = sfnt_get_short(sfont); /* ushort ? */
+ table->minTopSideBearing = sfnt_get_short(sfont);
+ table->minBottomSideBearing = sfnt_get_short(sfont);
+ table->yMaxExtent = sfnt_get_short(sfont);
+ table->caretSlopeRise = sfnt_get_short(sfont);
+ table->caretSlopeRun = sfnt_get_short(sfont);
+ table->caretOffset = sfnt_get_short(sfont);
+ for(i = 0; i < 4; i++) {
+ (table->reserved)[i] = sfnt_get_short(sfont);
+ }
+ table->metricDataFormat = sfnt_get_short(sfont);
+ table->numOfLongVerMetrics = sfnt_get_ushort(sfont);
+
+ len = sfnt_find_table_len(sfont, "vmtx");
+ table->numOfExSideBearings = (USHORT)((len - table->numOfLongVerMetrics * 4) / 2);
+
+ return table;
+}
+
+
+struct tt_VORG_table *
+tt_read_VORG_table (sfnt *sfont)
+{
+ struct tt_VORG_table *vorg;
+ ULONG offset;
+ USHORT i;
+
+ offset = sfnt_find_table_pos(sfont, "VORG");
+
+ if (offset > 0) {
+ vorg = NEW(1, struct tt_VORG_table);
+
+ sfnt_locate_table(sfont, "VORG");
+ if (sfnt_get_ushort(sfont) != 1 ||
+ sfnt_get_ushort(sfont) != 0)
+ ERROR("Unsupported VORG version.");
+
+ vorg->defaultVertOriginY = sfnt_get_short(sfont);
+ vorg->numVertOriginYMetrics = sfnt_get_ushort(sfont);
+ vorg->vertOriginYMetrics = NEW(vorg->numVertOriginYMetrics,
+ struct tt_vertOriginYMetrics);
+ /*
+ * The vertOriginYMetrics array must be sorted in increasing
+ * glyphIndex order.
+ */
+ for (i = 0;
+ i < vorg->numVertOriginYMetrics; i++) {
+ vorg->vertOriginYMetrics[i].glyphIndex = sfnt_get_ushort(sfont);
+ vorg->vertOriginYMetrics[i].vertOriginY = sfnt_get_short(sfont);
+ }
+ } else {
+ vorg = NULL;
+ }
+
+ return vorg;
+}
+
+/*
+ * hmtx and vmtx
+ *
+ * Reading/writing hmtx and vmtx depend on other tables, maxp and hhea/vhea.
+ */
+
+struct tt_longMetrics *
+tt_read_longMetrics (sfnt *sfont, USHORT numGlyphs, USHORT numLongMetrics, USHORT numExSideBearings)
+{
+ struct tt_longMetrics *m;
+ USHORT gid, last_adv = 0;
+ SHORT last_esb = 0;
+
+ m = NEW(numGlyphs, struct tt_longMetrics);
+ for (gid = 0; gid < numGlyphs; gid++) {
+ if (gid < numLongMetrics)
+ last_adv = sfnt_get_ushort(sfont);
+ if (gid < numLongMetrics + numExSideBearings)
+ last_esb = sfnt_get_short(sfont);
+ m[gid].advance = last_adv;
+ m[gid].sideBearing = last_esb;
+ }
+
+ return m;
+}
+
+/* OS/2 table */
+/* this table may not exist */
+struct tt_os2__table *
+tt_read_os2__table (sfnt *sfont)
+{
+ struct tt_os2__table *table = NULL;
+ int i;
+
+ if (sfnt_find_table_pos(sfont, "OS/2") == 0)
+ return NULL;
+
+ sfnt_locate_table(sfont, "OS/2");
+
+ table = NEW(1, struct tt_os2__table);
+
+ table->version = sfnt_get_ushort(sfont);
+ table->xAvgCharWidth = sfnt_get_short(sfont);
+ table->usWeightClass = sfnt_get_ushort(sfont);
+ table->usWidthClass = sfnt_get_ushort(sfont);
+ table->fsType = sfnt_get_short(sfont);
+ table->ySubscriptXSize = sfnt_get_short(sfont);
+ table->ySubscriptYSize = sfnt_get_short(sfont);
+ table->ySubscriptXOffset = sfnt_get_short(sfont);
+ table->ySubscriptYOffset = sfnt_get_short(sfont);
+ table->ySuperscriptXSize = sfnt_get_short(sfont);
+ table->ySuperscriptYSize = sfnt_get_short(sfont);
+ table->ySuperscriptXOffset = sfnt_get_short(sfont);
+ table->ySuperscriptYOffset = sfnt_get_short(sfont);
+ table->yStrikeoutSize = sfnt_get_short(sfont);
+ table->yStrikeoutPosition = sfnt_get_short(sfont);
+ table->sFamilyClass = sfnt_get_short(sfont);
+ for (i = 0; i < 10; i++) {
+ table->panose[i] = sfnt_get_byte(sfont);
+ }
+ table->ulUnicodeRange1 = sfnt_get_ulong(sfont);
+ table->ulUnicodeRange2 = sfnt_get_ulong(sfont);
+ table->ulUnicodeRange3 = sfnt_get_ulong(sfont);
+ table->ulUnicodeRange4 = sfnt_get_ulong(sfont);
+ for (i = 0; i < 4; i++) {
+ table->achVendID[i] = sfnt_get_char(sfont);
+ }
+ table->fsSelection = sfnt_get_ushort(sfont);
+ table->usFirstCharIndex = sfnt_get_ushort(sfont);
+ table->usLastCharIndex = sfnt_get_ushort(sfont);
+ if (sfnt_find_table_len(sfont, "OS/2") >= 78) {
+ /* these fields are not present in the original Apple spec (68-byte table),
+ but Microsoft's version of "format 0" does include them... grr! */
+ table->sTypoAscender = sfnt_get_short(sfont);
+ table->sTypoDescender = sfnt_get_short(sfont);
+ table->sTypoLineGap = sfnt_get_short(sfont);
+ table->usWinAscent = sfnt_get_ushort(sfont);
+ table->usWinDescent = sfnt_get_ushort(sfont);
+ if (table->version > 0) {
+ /* format 1 adds the following 2 fields */
+ table->ulCodePageRange1 = sfnt_get_ulong(sfont);
+ table->ulCodePageRange2 = sfnt_get_ulong(sfont);
+ if (table->version > 1) {
+ /* and formats 2 and 3 (current) include 5 more.... these share the
+ same fields, only the precise definition of some was changed */
+ table->sxHeight = sfnt_get_short(sfont);
+ table->sCapHeight = sfnt_get_short(sfont);
+ table->usDefaultChar = sfnt_get_ushort(sfont);
+ table->usBreakChar = sfnt_get_ushort(sfont);
+ table->usMaxContext = sfnt_get_ushort(sfont);
+ }
+ }
+ }
+
+ return table;
+}
+
+USHORT
+tt_get_name (sfnt *sfont, char *dest, USHORT destlen,
+ USHORT plat_id, USHORT enco_id,
+ USHORT lang_id, USHORT name_id)
+{
+ USHORT length = 0;
+ USHORT num_names, string_offset;
+ ULONG name_offset;
+ int i;
+
+ name_offset = sfnt_locate_table (sfont, "name");
+
+ if (sfnt_get_ushort(sfont))
+ ERROR ("Expecting zero");
+
+ num_names = sfnt_get_ushort(sfont);
+ string_offset = sfnt_get_ushort(sfont);
+ for (i=0;i<num_names;i++) {
+ USHORT p_id, e_id, n_id, l_id;
+ USHORT offset;
+
+ p_id = sfnt_get_ushort(sfont);
+ e_id = sfnt_get_ushort(sfont);
+ l_id = sfnt_get_ushort(sfont);
+ n_id = sfnt_get_ushort(sfont);
+ length = sfnt_get_ushort(sfont);
+ offset = sfnt_get_ushort(sfont);
+ /* language ID value 0xffffu for `accept any language ID' */
+ if ((p_id == plat_id) && (e_id == enco_id) &&
+ (lang_id == 0xffffu || l_id == lang_id) && (n_id == name_id)) {
+ if (length > destlen - 1) {
+ fprintf(stderr, "\n** Notice: Name string too long. Truncating **\n");
+ length = destlen - 1;
+ }
+ sfnt_seek_set (sfont, name_offset+string_offset+offset);
+ sfnt_read((unsigned char*)dest, length, sfont);
+ dest[length] = '\0';
+ break;
+ }
+ }
+ if (i == num_names) {
+ length = 0;
+ }
+
+ return length;
+}
+
+USHORT
+tt_get_ps_fontname (sfnt *sfont, char *dest, USHORT destlen)
+{
+ USHORT namelen = 0;
+
+#ifdef XETEX
+
+ const char* name = FT_Get_Postscript_Name(sfont->ft_face);
+ namelen = strlen(name);
+ if (namelen > destlen - 1) {
+ strncpy(dest, name, destlen - 1);
+ dest[destlen] = 0;
+ }
+ else
+ strcpy(dest, name);
+
+#else
+
+ /* First try Mac-Roman PS name and then Win-Unicode PS name */
+ if ((namelen = tt_get_name(sfont, dest, destlen, 1, 0, 0, 6)) != 0 ||
+ (namelen = tt_get_name(sfont, dest, destlen, 3, 1, 0x409u, 6)) != 0 ||
+ (namelen = tt_get_name(sfont, dest, destlen, 3, 5, 0x412u, 6)) != 0)
+ return namelen;
+
+ fprintf(stderr, "\n** Warning: No valid PostScript name available **\n");
+ /*
+ Wrokaround for some bad TTfonts:
+ Language ID value 0xffffu for `accept any language ID'
+ */
+ if ((namelen = tt_get_name(sfont, dest, destlen, 1, 0, 0xffffu, 6)) == 0) {
+ /*
+ Finally falling back to Mac Roman name field.
+ Warning: Some bad Japanese TTfonts using SJIS encoded string in the
+ Mac Roman name field.
+ */
+ namelen = tt_get_name(sfont, dest, destlen, 1, 0, 0, 1);
+ }
+
+#endif
+
+ return namelen;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/type0.c b/Build/source/texk/dvipdf-x/xsrc/type0.c
new file mode 100644
index 00000000000..29acb44ea8b
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/type0.c
@@ -0,0 +1,687 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+/*
+ * Type0 font support:
+ *
+ * TODO:
+ *
+ * Composite font (multiple descendants) - not supported in PDF
+ */
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <string.h>
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+#include "dpxfile.h"
+
+#include "pdfobj.h"
+#include "fontmap.h"
+
+#include "cmap.h"
+#include "cid.h"
+
+#include "type0.h"
+
+
+#define TYPE0FONT_DEBUG_STR "Type0"
+#define TYPE0FONT_DEBUG 3
+
+static int __verbose = 0;
+
+static pdf_obj *pdf_read_ToUnicode_file (const char *cmap_name);
+
+void
+Type0Font_set_verbose(void)
+{
+ __verbose++;
+}
+
+/*
+ * used_chars:
+ *
+ * Single bit is used for each CIDs since used_chars can be reused as a
+ * stream content of CIDSet by doing so. See, cid.h for add_to_used() and
+ * is_used().
+ */
+
+static char *
+new_used_chars2(void)
+{
+ char *used_chars;
+
+ used_chars = NEW(8192, char);
+ memset(used_chars, 0, 8192);
+
+ return used_chars;
+}
+
+#define FLAG_NONE 0
+#define FLAG_USED_CHARS_SHARED (1 << 0)
+
+struct Type0Font {
+ char *fontname; /* BaseFont */
+ char *encoding; /* "Identity-H" or "Identity-V" (not ID) */
+ char *used_chars; /* Used chars (CIDs) */
+
+ /*
+ * Type0 only
+ */
+ CIDFont *descendant; /* Only single descendant is allowed. */
+ int flags;
+ int wmode;
+
+ /*
+ * PDF Font Resource
+ */
+ pdf_obj *indirect;
+ pdf_obj *fontdict;
+ pdf_obj *descriptor; /* MUST BE NULL */
+};
+
+static void
+Type0Font_init_font_struct (Type0Font *font)
+{
+ ASSERT(font);
+
+ font->fontname = NULL;
+ font->fontdict = NULL;
+ font->indirect = NULL;
+ font->descriptor = NULL;
+ font->encoding = NULL;
+ font->used_chars = NULL;
+ font->descendant = NULL;
+ font->wmode = -1;
+ font->flags = FLAG_NONE;
+
+ return;
+}
+
+static void
+Type0Font_clean (Type0Font *font)
+{
+ if (font) {
+ if (font->fontdict)
+ ERROR("%s: Object not flushed.", TYPE0FONT_DEBUG_STR);
+ if (font->indirect)
+ ERROR("%s: Object not flushed.", TYPE0FONT_DEBUG_STR);
+ if (font->descriptor)
+ ERROR("%s: FontDescriptor unexpected for Type0 font.", TYPE0FONT_DEBUG_STR);
+ if (!(font->flags & FLAG_USED_CHARS_SHARED) && font->used_chars)
+ RELEASE(font->used_chars);
+ if (font->encoding)
+ RELEASE(font->encoding);
+ if (font->fontname)
+ RELEASE(font->fontname);
+ font->fontdict = NULL;
+ font->indirect = NULL;
+ font->descriptor = NULL;
+ font->used_chars = NULL;
+ font->encoding = NULL;
+ font->fontname = NULL;
+ }
+}
+
+/* PLEASE FIX THIS */
+#include "tt_cmap.h"
+
+static void
+add_ToUnicode (Type0Font *font)
+{
+ pdf_obj *tounicode;
+ CIDFont *cidfont;
+ CIDSysInfo *csi;
+ char *cmap_name, *fontname;
+
+ /*
+ * ToUnicode CMap:
+ *
+ * ToUnicode CMaps are usually not required for standard character
+ * collections such as Adobe-Japan1. Identity-H is used for UCS
+ * ordering CID-keyed fonts. External resource must be loaded for
+ * others.
+ */
+
+ cidfont = font->descendant;
+ if (!cidfont) {
+ ERROR("%s: No descendant CID-keyed font.", TYPE0FONT_DEBUG_STR);
+ return;
+ }
+
+ if (CIDFont_is_ACCFont(cidfont)) {
+ /* No need to embed ToUnicode */
+ return;
+ } else if (CIDFont_is_UCSFont(cidfont)) {
+ /*
+ * Old version of dvipdfmx mistakenly used Adobe-Identity as Unicode.
+ */
+ tounicode = pdf_read_ToUnicode_file("Adobe-Identity-UCS2");
+ if (!tounicode) { /* This should work */
+ tounicode = pdf_new_name("Identity-H");
+ }
+ pdf_add_dict(font->fontdict, pdf_new_name("ToUnicode"), tounicode);
+ return;
+ }
+
+ tounicode = NULL;
+ csi = CIDFont_get_CIDSysInfo(cidfont);
+ fontname = CIDFont_get_fontname(cidfont);
+ if (CIDFont_get_embedding(cidfont)) {
+ fontname += 7; /* FIXME */
+ }
+
+ if (!strcmp(csi->registry, "Adobe") &&
+ !strcmp(csi->ordering, "Identity")) {
+ switch (CIDFont_get_subtype(cidfont)) {
+ case CIDFONT_TYPE2:
+ /* PLEASE FIX THIS */
+ tounicode = otf_create_ToUnicode_stream(CIDFont_get_ident(cidfont),
+ CIDFont_get_opt_index(cidfont),
+ CIDFont_get_ft_face(cidfont),
+ Type0Font_get_usedchars(font));
+ break;
+ default:
+ if (CIDFont_get_flag(cidfont, CIDFONT_FLAG_TYPE1C)) { /* FIXME */
+ tounicode = otf_create_ToUnicode_stream(CIDFont_get_ident(cidfont),
+ CIDFont_get_opt_index(cidfont),
+ CIDFont_get_ft_face(cidfont),
+ Type0Font_get_usedchars(font));
+ } else if (CIDFont_get_flag(cidfont, CIDFONT_FLAG_TYPE1)) { /* FIXME */
+ /* Font loader will create ToUnicode and set. */
+ return;
+ } else {
+ cmap_name = NEW(strlen(fontname) + 7, char);
+ sprintf(cmap_name, "%s-UTF16", fontname);
+ tounicode = pdf_read_ToUnicode_file(cmap_name);
+ if (!tounicode) {
+ sprintf(cmap_name, "%s-UCS2", fontname);
+ tounicode = pdf_read_ToUnicode_file(cmap_name);
+ }
+ RELEASE(cmap_name);
+ }
+ break;
+ }
+ } else {
+ cmap_name = NEW(strlen(csi->registry)+strlen(csi->ordering)+8, char);
+ sprintf(cmap_name, "%s-%s-UTF16", csi->registry, csi->ordering);
+ tounicode = pdf_read_ToUnicode_file(cmap_name);
+ if (!tounicode) {
+ sprintf(cmap_name, "%s-%s-UCS2", csi->registry, csi->ordering);
+ tounicode = pdf_read_ToUnicode_file(cmap_name);
+ }
+ RELEASE(cmap_name);
+ }
+
+ if (tounicode) {
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("ToUnicode"), tounicode);
+ } else {
+ WARN("Failed to load ToUnicode CMap for font \"%s\"", fontname);
+ }
+
+ return;
+}
+
+void
+Type0Font_set_ToUnicode (Type0Font *font, pdf_obj *cmap_ref)
+{
+ ASSERT(font);
+
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("ToUnicode"), cmap_ref);
+}
+
+static void
+Type0Font_dofont (Type0Font *font)
+{
+ if (!font || !font->indirect)
+ return;
+
+ if (!pdf_lookup_dict(font->fontdict, "ToUnicode")) { /* FIXME */
+ add_ToUnicode(font);
+ }
+}
+
+static void
+Type0Font_flush (Type0Font *font)
+{
+ if (font) {
+ if (font->fontdict)
+ pdf_release_obj(font->fontdict);
+ font->fontdict = NULL;
+ if (font->indirect)
+ pdf_release_obj(font->indirect);
+ font->indirect = NULL;
+ if (font->descriptor)
+ ERROR("%s: FontDescriptor unexpected for Type0 font.", TYPE0FONT_DEBUG_STR);
+ font->descriptor = NULL;
+ }
+}
+
+int
+Type0Font_get_wmode (Type0Font *font)
+{
+ ASSERT(font);
+
+ return font->wmode;
+}
+
+#if 0
+char *
+Type0Font_get_encoding (Type0Font *font)
+{
+ ASSERT(font);
+
+ return font->encoding;
+}
+#endif /* 0 */
+
+char *
+Type0Font_get_usedchars (Type0Font *font)
+{
+ ASSERT(font);
+
+ return font->used_chars;
+}
+
+pdf_obj *
+Type0Font_get_resource (Type0Font *font)
+{
+ ASSERT(font);
+
+ /*
+ * This looks somewhat strange.
+ */
+ if (!font->indirect) {
+ pdf_obj *array;
+
+ array = pdf_new_array();
+ pdf_add_array(array, CIDFont_get_resource(font->descendant));
+ pdf_add_dict(font->fontdict, pdf_new_name("DescendantFonts"), array);
+ font->indirect = pdf_ref_obj(font->fontdict);
+ }
+
+ return pdf_link_obj(font->indirect);
+}
+
+/******************************** CACHE ********************************/
+
+#define CHECK_ID(n) do {\
+ if ((n) < 0 || (n) >= __cache.count)\
+ ERROR("%s: Invalid ID %d", TYPE0FONT_DEBUG_STR, (n));\
+} while (0)
+
+#define CACHE_ALLOC_SIZE 16u
+
+static struct font_cache {
+ int count;
+ int capacity;
+ Type0Font *fonts;
+} __cache = {
+ 0, 0, NULL
+};
+
+void
+Type0Font_cache_init (void)
+{
+ if (__cache.fonts)
+ ERROR("%s: Already initialized.", TYPE0FONT_DEBUG_STR);
+ __cache.count = 0;
+ __cache.capacity = 0;
+ __cache.fonts = NULL;
+}
+
+Type0Font *
+Type0Font_cache_get (int id)
+{
+ CHECK_ID(id);
+
+ return &__cache.fonts[id];
+}
+
+#ifdef XETEX
+unsigned short*
+Type0Font_get_ft_to_gid(int id)
+{
+ return CIDFont_get_ft_to_gid(Type0Font_cache_get(id)->descendant);
+}
+#endif
+
+int
+Type0Font_cache_find (const char *map_name, int cmap_id, fontmap_opt *fmap_opt)
+{
+ int font_id = -1;
+ Type0Font *font;
+ CIDFont *cidfont;
+ CMap *cmap;
+ CIDSysInfo *csi;
+ char *fontname = NULL;
+ int cid_id = -1, parent_id = -1, wmode = 0;
+ int pdf_ver;
+
+ pdf_ver = pdf_get_version();
+ if (!map_name || cmap_id < 0 || pdf_ver < 2)
+ return -1;
+
+ /*
+ * Encoding is Identity-H or Identity-V according as thier WMode value.
+ *
+ * We do not use match against the map_name since fonts (TrueType) covers
+ * characters across multiple character collection (eg, Adobe-Japan1 and
+ * Adobe-Japan2) must be splited into multiple CID-keyed fonts.
+ */
+
+ cmap = CMap_cache_get(cmap_id);
+ csi = (CMap_is_Identity(cmap)) ? NULL : CMap_get_CIDSysInfo(cmap) ;
+
+ cid_id = CIDFont_cache_find(map_name, csi, fmap_opt);
+
+ if (cid_id < 0)
+ return -1;
+
+ /*
+ * The descendant CID-keyed font has already been registerd.
+ * If CID-keyed font with ID = cid_id is new font, then create new parent
+ * Type 0 font. Otherwise, there already exists parent Type 0 font and
+ * then we find him and return his ID. We must check against their WMode.
+ */
+
+ cidfont = CIDFont_cache_get(cid_id);
+ wmode = CMap_get_wmode(cmap);
+
+ /* Does CID-keyed font already have parent ? */
+ parent_id = CIDFont_get_parent_id(cidfont, wmode);
+ if (parent_id >= 0)
+ return parent_id; /* If so, we don't need new one. */
+
+ /*
+ * CIDFont does not have parent or his parent's WMode does not matched with
+ * wmode. Create new Type0 font.
+ */
+
+ if (__cache.count >= __cache.capacity) {
+ __cache.capacity += CACHE_ALLOC_SIZE;
+ __cache.fonts = RENEW(__cache.fonts, __cache.capacity, struct Type0Font);
+ }
+ font_id = __cache.count;
+ font = &__cache.fonts[font_id];
+
+ Type0Font_init_font_struct(font);
+
+ /*
+ * All CJK double-byte characters are mapped so that resulting
+ * character codes coincide with CIDs of given character collection.
+ * So, the Encoding is always Identity-H for horizontal fonts or
+ * Identity-V for vertical fonts.
+ */
+ if (wmode) {
+ font->encoding = NEW(strlen("Identity-V")+1, char);
+ strcpy(font->encoding, "Identity-V");
+ } else {
+ font->encoding = NEW(strlen("Identity-H")+1, char);
+ strcpy(font->encoding, "Identity-H");
+ }
+ font->wmode = wmode;
+
+ /*
+ * Now we start font dictionary.
+ */
+ font->fontdict = pdf_new_dict();
+ pdf_add_dict(font->fontdict, pdf_new_name ("Type"), pdf_new_name ("Font"));
+ pdf_add_dict(font->fontdict, pdf_new_name ("Subtype"), pdf_new_name ("Type0"));
+
+ /*
+ * Type0 font does not have FontDescriptor because it is not a simple font.
+ * Instead, DescendantFonts appears here.
+ *
+ * Up to PDF version 1.5, Type0 font must have single descendant font which
+ * is a CID-keyed font. Future PDF spec. will allow multiple desecendant
+ * fonts.
+ */
+ font->descendant = cidfont;
+ CIDFont_attach_parent(cidfont, font_id, wmode);
+
+ /*
+ * PostScript Font name:
+ *
+ * Type0 font's fontname is usually descendant CID-keyed font's font name
+ * appended by -ENCODING.
+ */
+ fontname = CIDFont_get_fontname(cidfont);
+
+ if (__verbose) {
+ if (CIDFont_get_embedding(cidfont) && strlen(fontname) > 7)
+ MESG("(CID:%s)", fontname+7); /* skip XXXXXX+ */
+ else
+ MESG("(CID:%s)", fontname);
+ }
+
+ /*
+ * The difference between CID-keyed font and TrueType font appears here.
+ *
+ * Glyph substitution for vertical writing is done in CMap mapping process
+ * for CID-keyed fonts. But we must rely on OpenType layout table in the
+ * case of TrueType fonts. So, we must use different used_chars for each
+ * horizontal and vertical fonts in that case.
+ *
+ * In most PDF file, encoding name is not appended to fontname for Type0
+ * fonts having CIDFontType 2 font as their descendant.
+ */
+
+ font->used_chars = NULL;
+ font->flags = FLAG_NONE;
+
+ switch (CIDFont_get_subtype(cidfont)) {
+ case CIDFONT_TYPE0:
+ font->fontname = NEW(strlen(fontname)+strlen(font->encoding)+2, char);
+ sprintf(font->fontname, "%s-%s", fontname, font->encoding);
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("BaseFont"), pdf_new_name(font->fontname));
+ /*
+ * Need used_chars to write W, W2.
+ */
+ if ((parent_id = CIDFont_get_parent_id(cidfont, wmode ? 0 : 1)) < 0)
+ font->used_chars = new_used_chars2();
+ else {
+ /* Don't allocate new one. */
+ font->used_chars = Type0Font_get_usedchars(Type0Font_cache_get(parent_id));
+ font->flags |= FLAG_USED_CHARS_SHARED;
+ }
+ break;
+ case CIDFONT_TYPE2:
+ /*
+ * TrueType:
+ *
+ * Use different used_chars for H and V.
+ */
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("BaseFont"), pdf_new_name(fontname));
+ font->used_chars = new_used_chars2();
+ break;
+ default:
+ ERROR("Unrecognized CIDFont Type");
+ break;
+ }
+
+ pdf_add_dict(font->fontdict,
+ pdf_new_name("Encoding"), pdf_new_name(font->encoding));
+
+ __cache.count++;
+
+ return font_id;
+}
+
+void
+Type0Font_cache_close (void)
+{
+ int font_id;
+
+ /*
+ * This need to be fixed.
+ *
+ * CIDFont_cache_close() before Type0Font_release because of used_chars.
+ * ToUnicode support want descendant CIDFont's CSI and fontname.
+ */
+ if (__cache.fonts) {
+ for (font_id = 0; font_id < __cache.count; font_id++)
+ Type0Font_dofont(&__cache.fonts[font_id]);
+ }
+ CIDFont_cache_close();
+ if (__cache.fonts) {
+ for (font_id = 0; font_id < __cache.count; font_id++) {
+ Type0Font_flush(&__cache.fonts[font_id]);
+ Type0Font_clean(&__cache.fonts[font_id]);
+ }
+ RELEASE(__cache.fonts);
+ }
+ __cache.fonts = NULL;
+ __cache.count = 0;
+ __cache.capacity = 0;
+}
+
+
+/************************************************************************/
+
+int
+pdf_font_findfont0 (const char *font_name, int cmap_id, fontmap_opt *fmap_opt)
+{
+ return Type0Font_cache_find(font_name, cmap_id, fmap_opt);
+}
+
+/******************************** COMPAT ********************************/
+
+#ifndef WITHOUT_COMPAT
+
+#include "cmap_read.h"
+#include "cmap_write.h"
+#include "pdfresource.h"
+#include "pdfencoding.h"
+
+static pdf_obj *
+create_dummy_CMap (void)
+{
+ pdf_obj *stream;
+ char buf[32];
+ int i, n;
+
+#define CMAP_PART0 "\
+%!PS-Adobe-3.0 Resource-CMap\n\
+%%DocumentNeededResources: ProcSet (CIDInit)\n\
+%%IncludeResource: ProcSet (CIDInit)\n\
+%%BeginResource: CMap (Adobe-Identity-UCS2)\n\
+%%Title: (Adobe-Identity-UCS2 Adobe UCS2 0)\n\
+%%Version: 1.0\n\
+%%Copyright:\n\
+%% ---\n\
+%%EndComments\n\n\
+"
+#define CMAP_PART1 "\
+/CIDInit /ProcSet findresource begin\n\
+\n\
+12 dict begin\n\nbegincmap\n\n\
+/CIDSystemInfo 3 dict dup begin\n\
+ /Registry (Adobe) def\n\
+ /Ordering (UCS2) def\n\
+ /Supplement 0 def\n\
+end def\n\n\
+/CMapName /Adobe-Identity-UCS2 def\n\
+/CMapVersion 1.0 def\n\
+/CMapType 2 def\n\n\
+2 begincodespacerange\n\
+<0000> <FFFF>\n\
+endcodespacerange\n\
+"
+#define CMAP_PART3 "\
+endcmap\n\n\
+CMapName currentdict /CMap defineresource pop\n\n\
+end\nend\n\n\
+%%EndResource\n\
+%%EOF\n\
+"
+
+ stream = pdf_new_stream(STREAM_COMPRESS);
+ pdf_add_stream(stream, CMAP_PART0, strlen(CMAP_PART0));
+ pdf_add_stream(stream, CMAP_PART1, strlen(CMAP_PART1));
+ pdf_add_stream(stream, "\n100 beginbfrange\n", strlen("\n100 beginbfrange\n"));
+ for (i = 0; i < 0x64; i++) {
+ n = sprintf(buf,
+ "<%02X00> <%02XFF> <%02X00>\n", i, i, i);
+ pdf_add_stream(stream, buf, n);
+ }
+ pdf_add_stream(stream, "endbfrange\n\n", strlen("endbfrange\n\n"));
+
+ pdf_add_stream(stream, "\n100 beginbfrange\n", strlen("\n100 beginbfrange\n"));
+ for (i = 0x64; i < 0xc8; i++) {
+ n = sprintf(buf,
+ "<%02X00> <%02XFF> <%02X00>\n", i, i, i);
+ pdf_add_stream(stream, buf, n);
+ }
+ pdf_add_stream(stream, "endbfrange\n\n", strlen("endbfrange\n\n"));
+
+ pdf_add_stream(stream, "\n48 beginbfrange\n", strlen("\n48 beginbfrange\n"));
+ for (i = 0xc8; i <= 0xd7; i++) {
+ n = sprintf(buf,
+ "<%02X00> <%02XFF> <%02X00>\n", i, i, i);
+ pdf_add_stream(stream, buf, n);
+ }
+ for (i = 0xe0; i <= 0xff; i++) {
+ n = sprintf(buf,
+ "<%02X00> <%02XFF> <%02X00>\n", i, i, i);
+ pdf_add_stream(stream, buf, n);
+ }
+ pdf_add_stream(stream, "endbfrange\n\n", strlen("endbfrange\n\n"));
+
+ pdf_add_stream(stream, CMAP_PART3, strlen(CMAP_PART3));
+
+ return stream;
+}
+
+static pdf_obj *
+pdf_read_ToUnicode_file (const char *cmap_name)
+{
+ pdf_obj *stream;
+ long res_id = -1;
+
+ ASSERT(cmap_name);
+
+ res_id = pdf_findresource("CMap", cmap_name);
+ if (res_id < 0) {
+ if (!strcmp(cmap_name, "Adobe-Identity-UCS2"))
+ stream = create_dummy_CMap();
+ else {
+ stream = pdf_load_ToUnicode_stream(cmap_name);
+ }
+ if (stream) {
+ res_id = pdf_defineresource("CMap",
+ cmap_name,
+ stream, PDF_RES_FLUSH_IMMEDIATE);
+ }
+ }
+
+ return (res_id < 0 ? NULL : pdf_get_resource_reference(res_id));
+}
+#endif /* !WITHOUT_COMPAT */
diff --git a/Build/source/texk/dvipdf-x/xsrc/type0.h b/Build/source/texk/dvipdf-x/xsrc/type0.h
new file mode 100644
index 00000000000..68979decbc6
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/type0.h
@@ -0,0 +1,58 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2002-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _TYPE0_H_
+#define _TYPE0_H_
+
+#include "pdfobj.h"
+
+#define add_to_used_chars2(b,c) {(b)[(c)/8] |= (1 << (7-((c)%8)));}
+#define is_used_char2(b,c) (((b)[(c)/8]) & (1 << (7-((c)%8))))
+
+typedef struct Type0Font Type0Font;
+
+extern void Type0Font_set_verbose (void);
+
+extern int Type0Font_get_wmode (Type0Font *font);
+#if 0
+extern char *Type0Font_get_encoding (Type0Font *font);
+#endif /* 0 */
+extern char *Type0Font_get_usedchars (Type0Font *font);
+
+extern pdf_obj *Type0Font_get_resource (Type0Font *font);
+
+extern void Type0Font_set_ToUnicode (Type0Font *font, pdf_obj *cmap_ref);
+
+#include "fontmap.h"
+extern int pdf_font_findfont0 (const char *font_name,
+ int cmap_id, fontmap_opt *fmap_opt);
+
+extern unsigned short *Type0Font_get_ft_to_gid(int id);
+
+/******************************** CACHE ********************************/
+
+extern void Type0Font_cache_init (void);
+extern Type0Font *Type0Font_cache_get (int id);
+extern int Type0Font_cache_find (const char *map_name, int cmap_id, fontmap_opt *fmap_opt);
+extern void Type0Font_cache_close (void);
+
+#endif /* _TYPE0_H_ */
diff --git a/Build/source/texk/dvipdf-x/xsrc/type1.c b/Build/source/texk/dvipdf-x/xsrc/type1.c
new file mode 100644
index 00000000000..f72b5b9d21a
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/type1.c
@@ -0,0 +1,805 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2008-2012 by Jin-Hwan Cho, Matthias Franz, and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <string.h>
+#include <math.h>
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+
+#include "dpxfile.h"
+
+#include "numbers.h"
+
+#include "pdfobj.h"
+#include "pdffont.h"
+
+#include "pdfencoding.h"
+#include "unicode.h"
+
+#include "dpxutil.h"
+
+#include "pst_obj.h"
+#include "pst.h"
+
+#include "cff_limits.h"
+#include "cff_types.h"
+#include "cff_dict.h"
+#include "cff.h"
+
+#include "t1_load.h"
+#include "t1_char.h"
+
+#include "type1.h"
+
+#include "tfm.h"
+
+#define FONT_FLAG_FIXEDPITCH (1 << 0) /* Fixed-width font */
+#define FONT_FLAG_SERIF (1 << 1) /* Serif font */
+#define FONT_FLAG_SYMBOLIC (1 << 2) /* Symbolic font */
+#define FONT_FLAG_SCRIPT (1 << 3) /* Script font */
+#define FONT_FLAG_STANDARD (1 << 5) /* Adobe Standard Character Set */
+#define FONT_FLAG_ITALIC (1 << 6) /* Italic */
+#define FONT_FLAG_ALLCAP (1 << 16) /* All-cap font */
+#define FONT_FLAG_SMALLCAP (1 << 17) /* Small-cap font */
+#define FONT_FLAG_FORCEBOLD (1 << 18) /* Force bold at small text sizes */
+
+static int
+is_basefont (const char *name)
+{
+ static const char *basefonts[] = {
+ "Courier", "Courier-Bold", "Courier-Oblique",
+ "Courier-BoldOblique", "Helvetica", "Helvetica-Bold",
+ "Helvetica-Oblique", "Helvetica-BoldOblique", "Symbol",
+ "Times-Roman", "Times-Bold", "Times-Italic",
+ "Times-BoldItalic", "ZapfDingbats"
+ };
+ int i;
+
+ for (i = 0; i < 14; i++) {
+ if (!strcmp(name, basefonts[i]))
+ return 1;
+ }
+
+ return 0;
+}
+
+int
+pdf_font_open_type1 (pdf_font *font)
+{
+ char *ident;
+ FILE *fp;
+ char fontname[PDF_NAME_LEN_MAX+1];
+
+ ASSERT(font);
+
+ ident = pdf_font_get_ident(font);
+
+ if (is_basefont(ident)) {
+ pdf_font_set_fontname(font, ident);
+ pdf_font_set_subtype (font, PDF_FONT_FONTTYPE_TYPE1);
+ pdf_font_set_flags (font,
+ (PDF_FONT_FLAG_NOEMBED|PDF_FONT_FLAG_BASEFONT));
+ } else {
+ fp = DPXFOPEN(ident, DPX_RES_TYPE_T1FONT);
+ if (!fp)
+ return -1;
+
+ memset(fontname, 0, PDF_NAME_LEN_MAX+1);
+ if (!is_pfb(fp) || t1_get_fontname(fp, fontname) < 0) {
+ ERROR("Failed to read Type 1 font \"%s\".", ident);
+ }
+ DPXFCLOSE(fp);
+
+ pdf_font_set_fontname(font, fontname);
+ pdf_font_set_subtype (font, PDF_FONT_FONTTYPE_TYPE1);
+ }
+
+ return 0;
+}
+
+static void
+get_font_attr (pdf_font *font, cff_font *cffont)
+{
+ char *fontname;
+ pdf_obj *descriptor;
+ double capheight, ascent, descent;
+ double italicangle, stemv;
+ double defaultwidth, nominalwidth;
+ long flags = 0, gid, i;
+ static const char *L_c[] = {
+ "H", "P", "Pi", "Rho", NULL
+ };
+ static const char *L_d[] = {
+ "p", "q", "mu", "eta", NULL
+ };
+ static const char *L_a[] = {
+ "b", "h", "lambda", NULL
+ };
+ t1_ginfo gm;
+
+ defaultwidth = 500.0;
+ nominalwidth = 0.0;
+
+ /*
+ * CapHeight, Ascent, and Descent is meaningfull only for Latin/Greek/Cyrillic.
+ * The BlueValues and OtherBlues also have those information.
+ */
+ if (cff_dict_known(cffont->topdict, "FontBBox")) {
+ /* Default values */
+ capheight = ascent = cff_dict_get(cffont->topdict, "FontBBox", 3);
+ descent = cff_dict_get(cffont->topdict, "FontBBox", 1);
+ } else {
+ capheight = 680.0;
+ ascent = 690.0;
+ descent = -190.0;
+ }
+ if (cff_dict_known(cffont->private[0], "StdVW")) {
+ stemv = cff_dict_get(cffont->private[0], "StdVW", 0);
+ } else {
+ /*
+ * We may use the following values for StemV:
+ * Thin - ExtraLight: <= 50
+ * Light: 71
+ * Regular(Normal): 88
+ * Medium: 109
+ * SemiBold(DemiBold): 135
+ * Bold - Heavy: >= 166
+ */
+ stemv = 88.0;
+ }
+ if (cff_dict_known(cffont->topdict, "ItalicAngle")) {
+ italicangle = cff_dict_get(cffont->topdict, "ItalicAngle", 0);
+ if (italicangle != 0.0)
+ flags |= FONT_FLAG_ITALIC;
+ } else {
+ italicangle = 0.0;
+ }
+
+ /*
+ * Use "space", "H", "p", and "b" for various values.
+ * Those characters should not "seac". (no accent)
+ */
+ gid = cff_glyph_lookup(cffont, "space");
+ if (gid >= 0 && gid < cffont->cstrings->count) {
+ t1char_get_metrics(cffont->cstrings->data + cffont->cstrings->offset[gid] - 1,
+ cffont->cstrings->offset[gid+1] - cffont->cstrings->offset[gid],
+ cffont->subrs[0], &gm);
+ defaultwidth = gm.wx;
+ }
+
+ for (i = 0; L_c[i] != NULL; i++) {
+ gid = cff_glyph_lookup(cffont, L_c[i]);
+ if (gid >= 0 && gid < cffont->cstrings->count) {
+ t1char_get_metrics(cffont->cstrings->data + cffont->cstrings->offset[gid] - 1,
+ cffont->cstrings->offset[gid+1] - cffont->cstrings->offset[gid],
+ cffont->subrs[0], &gm);
+ capheight = gm.bbox.ury;
+ break;
+ }
+ }
+
+ for (i = 0; L_d[i] != NULL; i++) {
+ gid = cff_glyph_lookup(cffont, L_d[i]);
+ if (gid >= 0 && gid < cffont->cstrings->count) {
+ t1char_get_metrics(cffont->cstrings->data + cffont->cstrings->offset[gid] - 1,
+ cffont->cstrings->offset[gid+1] - cffont->cstrings->offset[gid],
+ cffont->subrs[0], &gm);
+ descent = gm.bbox.lly;
+ break;
+ }
+ }
+
+ for (i = 0; L_a[i] != NULL; i++) {
+ gid = cff_glyph_lookup(cffont, L_a[i]);
+ if (gid >= 0 && gid < cffont->cstrings->count) {
+ t1char_get_metrics(cffont->cstrings->data + cffont->cstrings->offset[gid] - 1,
+ cffont->cstrings->offset[gid+1] - cffont->cstrings->offset[gid],
+ cffont->subrs[0], &gm);
+ ascent = gm.bbox.ury;
+ break;
+ }
+ }
+
+ if (defaultwidth != 0.0) {
+ cff_dict_add(cffont->private[0], "defaultWidthX", 1);
+ cff_dict_set(cffont->private[0], "defaultWidthX", 0, defaultwidth);
+ }
+ if (nominalwidth != 0.0) {
+ cff_dict_add(cffont->private[0], "nominalWidthX", 1);
+ cff_dict_set(cffont->private[0], "nominalWidthX", 0, nominalwidth);
+ }
+ if (cff_dict_known(cffont->private[0], "ForceBold") &&
+ cff_dict_get(cffont->private[0], "ForceBold", 0)) {
+ flags |= FONT_FLAG_FORCEBOLD;
+ }
+ if (cff_dict_known(cffont->private[0], "IsFixedPitch") &&
+ cff_dict_get(cffont->private[0], "IsFixedPitch", 0)) {
+ flags |= FONT_FLAG_FIXEDPITCH;
+ }
+
+ fontname = pdf_font_get_fontname (font);
+ descriptor = pdf_font_get_descriptor(font);
+
+ if (fontname && !strstr(fontname, "Sans")) {
+ flags |= FONT_FLAG_SERIF;
+ }
+ if (fontname && strstr(fontname, "Caps")) {
+ flags |= FONT_FLAG_SMALLCAP;
+ }
+ flags |= FONT_FLAG_SYMBOLIC; /* FIXME */
+
+ pdf_add_dict(descriptor,
+ pdf_new_name("CapHeight"), pdf_new_number(capheight));
+ pdf_add_dict(descriptor,
+ pdf_new_name("Ascent"), pdf_new_number(ascent));
+ pdf_add_dict(descriptor,
+ pdf_new_name("Descent"), pdf_new_number(descent));
+ pdf_add_dict(descriptor,
+ pdf_new_name("ItalicAngle"), pdf_new_number(italicangle));
+ pdf_add_dict(descriptor,
+ pdf_new_name("StemV"), pdf_new_number(stemv));
+ pdf_add_dict(descriptor,
+ pdf_new_name("Flags"), pdf_new_number(flags));
+}
+
+static void
+add_metrics (pdf_font *font, cff_font *cffont, char **enc_vec, double *widths, long num_glyphs)
+{
+ pdf_obj *fontdict, *descriptor;
+ pdf_obj *tmp_array;
+ int code, firstchar, lastchar;
+ double val;
+ int i, tfm_id;
+ char *usedchars;
+ double scaling;
+
+ fontdict = pdf_font_get_resource (font);
+ descriptor = pdf_font_get_descriptor(font);
+ usedchars = pdf_font_get_usedchars (font);
+
+ /*
+ * The original FontBBox of the font is preserved, instead
+ * of replacing it with tight bounding box calculated from
+ * charstrings, to prevent Acrobat 4 from greeking text as
+ * much as possible.
+ */
+ if (!cff_dict_known(cffont->topdict, "FontBBox")) {
+ ERROR("No FontBBox?");
+ }
+
+ /* The widhts array in the font dictionary must be given relative
+ * to the default scaling of 1000:1, not relative to the scaling
+ * given by the font matrix.
+ */
+ if (cff_dict_known(cffont->topdict, "FontMatrix"))
+ scaling = 1000*cff_dict_get(cffont->topdict, "FontMatrix", 0);
+ else
+ scaling = 1;
+
+ tmp_array = pdf_new_array();
+ for (i = 0; i < 4; i++) {
+ val = cff_dict_get(cffont->topdict, "FontBBox", i);
+ pdf_add_array(tmp_array, pdf_new_number(ROUND(val, 1.0)));
+ }
+ pdf_add_dict(descriptor, pdf_new_name("FontBBox"), tmp_array);
+
+ tmp_array = pdf_new_array();
+ if (num_glyphs <= 1) { /* This must be an error. */
+ firstchar = lastchar = 0;
+ pdf_add_array(tmp_array, pdf_new_number(0.0));
+ } else {
+ for (firstchar = 255, lastchar = 0, code = 0; code < 256; code++) {
+ if (usedchars[code]) {
+ if (code < firstchar) firstchar = code;
+ if (code > lastchar) lastchar = code;
+ }
+ }
+ if (firstchar > lastchar) {
+ WARN("No glyphs actually used???");
+ pdf_release_obj(tmp_array);
+ return;
+ }
+ tfm_id = tfm_open(pdf_font_get_mapname(font), 0);
+ for (code = firstchar; code <= lastchar; code++) {
+ if (usedchars[code]) {
+ double width;
+ if (tfm_id < 0) /* tfm is not found */
+ width = scaling * widths[cff_glyph_lookup(cffont, enc_vec[code])];
+ else
+ width = 1000. * tfm_get_width(tfm_id, code);
+ pdf_add_array(tmp_array,
+ pdf_new_number(ROUND(width, 0.1)));
+ } else {
+ pdf_add_array(tmp_array, pdf_new_number(0.0));
+ }
+ }
+ }
+
+ if (pdf_array_length(tmp_array) > 0) {
+ pdf_add_dict(fontdict,
+ pdf_new_name("Widths"), pdf_ref_obj(tmp_array));
+ }
+ pdf_release_obj(tmp_array);
+
+ pdf_add_dict(fontdict,
+ pdf_new_name("FirstChar"), pdf_new_number(firstchar));
+ pdf_add_dict(fontdict,
+ pdf_new_name("LastChar"), pdf_new_number(lastchar));
+
+ return;
+}
+
+
+static long
+write_fontfile (pdf_font *font, cff_font *cffont, long num_glyphs)
+{
+ pdf_obj *descriptor;
+ pdf_obj *fontfile, *stream_dict;
+ cff_index *topdict;
+ long private_size, stream_data_len, charstring_len;
+ long topdict_offset, offset;
+#define WBUF_SIZE 1024
+ card8 *stream_data_ptr, wbuf[WBUF_SIZE];
+
+ descriptor = pdf_font_get_descriptor(font);
+
+ topdict = cff_new_index(1);
+ /*
+ * Force existence of Encoding.
+ */
+ if (!cff_dict_known(cffont->topdict, "CharStrings"))
+ cff_dict_add(cffont->topdict, "CharStrings", 1);
+ if (!cff_dict_known(cffont->topdict, "charset"))
+ cff_dict_add(cffont->topdict, "charset", 1);
+ if (!cff_dict_known(cffont->topdict, "Encoding"))
+ cff_dict_add(cffont->topdict, "Encoding", 1);
+ private_size = cff_dict_pack((cffont->private)[0], wbuf, WBUF_SIZE);
+ if (private_size > 0 && !cff_dict_known(cffont->topdict, "Private"))
+ cff_dict_add(cffont->topdict, "Private", 2);
+ topdict->offset[1] = cff_dict_pack(cffont->topdict, wbuf, WBUF_SIZE) + 1;
+
+ /*
+ * Estimate total size of fontfile.
+ */
+ charstring_len = cff_index_size(cffont->cstrings);
+
+ stream_data_len = 4; /* header size */
+ stream_data_len += cff_index_size(cffont->name);
+ stream_data_len += cff_index_size(topdict);
+ stream_data_len += cff_index_size(cffont->string);
+ stream_data_len += cff_index_size(cffont->gsubr);
+ /* We are using format 1 for Encoding and format 0 for charset.
+ * TODO: Should implement cff_xxx_size().
+ */
+ stream_data_len += 2 + (cffont->encoding->num_entries)*2 + 1 + (cffont->encoding->num_supps)*3;
+ stream_data_len += 1 + (cffont->charsets->num_entries)*2;
+ stream_data_len += charstring_len;
+ stream_data_len += private_size;
+
+ /*
+ * Now we create FontFile data.
+ */
+ stream_data_ptr = NEW(stream_data_len, card8);
+ /*
+ * Data Layout order as described in CFF spec., sec 2 "Data Layout".
+ */
+ offset = 0;
+ /* Header */
+ offset += cff_put_header(cffont,
+ stream_data_ptr + offset, stream_data_len - offset);
+ /* Name */
+ offset += cff_pack_index(cffont->name,
+ stream_data_ptr + offset, stream_data_len - offset);
+ /* Top DICT */
+ topdict_offset = offset;
+ offset += cff_index_size(topdict);
+ /* Strings */
+ offset += cff_pack_index(cffont->string,
+ stream_data_ptr + offset, stream_data_len - offset);
+ /* Global Subrs */
+ offset += cff_pack_index(cffont->gsubr,
+ stream_data_ptr + offset, stream_data_len - offset);
+ /* Encoding */
+ /* TODO: don't write Encoding entry if the font is always used
+ * with PDF Encoding information. Applies to type1c.c as well.
+ */
+ cff_dict_set(cffont->topdict, "Encoding", 0, offset);
+ offset += cff_pack_encoding(cffont,
+ stream_data_ptr + offset, stream_data_len - offset);
+ /* charset */
+ cff_dict_set(cffont->topdict, "charset", 0, offset);
+ offset += cff_pack_charsets(cffont,
+ stream_data_ptr + offset, stream_data_len - offset);
+ /* CharStrings */
+ cff_dict_set(cffont->topdict, "CharStrings", 0, offset);
+ offset += cff_pack_index(cffont->cstrings,
+ stream_data_ptr + offset, charstring_len);
+ /* Private */
+ if ((cffont->private)[0] && private_size > 0) {
+ private_size = cff_dict_pack(cffont->private[0],
+ stream_data_ptr + offset, private_size);
+ cff_dict_set(cffont->topdict, "Private", 1, offset);
+ cff_dict_set(cffont->topdict, "Private", 0, private_size);
+ }
+ offset += private_size;
+
+ /* Finally Top DICT */
+ topdict->data = NEW(topdict->offset[1] - 1, card8);
+ cff_dict_pack (cffont->topdict, topdict->data, topdict->offset[1] - 1);
+ cff_pack_index(topdict,
+ stream_data_ptr + topdict_offset, cff_index_size(topdict));
+ cff_release_index(topdict);
+
+ /* Copyright and Trademark Notice ommited. */
+
+ /* Flush Font File */
+ fontfile = pdf_new_stream(STREAM_COMPRESS);
+ stream_dict = pdf_stream_dict(fontfile);
+ pdf_add_dict(descriptor,
+ pdf_new_name("FontFile3"), pdf_ref_obj (fontfile));
+ pdf_add_dict(stream_dict,
+ pdf_new_name("Subtype"), pdf_new_name("Type1C"));
+ pdf_add_stream (fontfile, (void *) stream_data_ptr, offset);
+ pdf_release_obj(fontfile);
+
+ RELEASE(stream_data_ptr);
+
+ return offset;
+}
+
+
+int
+pdf_font_load_type1 (pdf_font *font)
+{
+ pdf_obj *fontdict;
+ int encoding_id;
+ char *usedchars, *ident;
+ char *fontname, *uniqueTag;
+ char *fullname; /* With pseudo unique tag */
+ cff_font *cffont;
+ cff_charsets *charset;
+ char **enc_vec;
+ double defaultwidth, nominalwidth;
+ double *widths;
+ card16 *GIDMap, num_glyphs = 0;
+ FILE *fp;
+ long offset;
+ int code, verbose;
+
+ ASSERT(font);
+
+ if (!pdf_font_is_in_use(font)) {
+ return 0;
+ }
+
+ verbose = pdf_font_get_verbose();
+
+ encoding_id = pdf_font_get_encoding (font);
+ fontdict = pdf_font_get_resource (font);
+
+ pdf_font_get_descriptor(font);
+ usedchars = pdf_font_get_usedchars (font);
+ ident = pdf_font_get_ident (font);
+ fontname = pdf_font_get_fontname (font);
+ uniqueTag = pdf_font_get_uniqueTag (font);
+ if (!usedchars || !ident || !fontname) {
+ ERROR("Type1: Unexpected error.");
+ }
+
+ fp = DPXFOPEN(ident, DPX_RES_TYPE_T1FONT);
+ if (!fp) {
+ ERROR("Type1: Could not open Type1 font: %s", ident);
+ }
+
+ GIDMap = NULL;
+ num_glyphs = 0;
+
+ if (encoding_id >= 0) {
+ enc_vec = NULL;
+ } else {
+ enc_vec = NEW(256, char *);
+ for (code = 0; code <= 0xff; code++) {
+ enc_vec[code] = NULL;
+ }
+ }
+
+ cffont = t1_load_font(enc_vec, 0, fp);
+ if (!cffont) {
+ ERROR("Could not load Type 1 font: %s", ident);
+ }
+ DPXFCLOSE(fp);
+
+ fullname = NEW(strlen(fontname) + 8, char);
+ sprintf(fullname, "%6s+%s", uniqueTag, fontname);
+
+ /*
+ * Encoding related things.
+ */
+ if (encoding_id >= 0) {
+ enc_vec = pdf_encoding_get_encoding(encoding_id);
+ } else {
+ pdf_obj *tounicode;
+
+ /*
+ * Create enc_vec and ToUnicode CMap for built-in encoding.
+ */
+ if (!pdf_lookup_dict(fontdict, "ToUnicode")) {
+ tounicode = pdf_create_ToUnicode_CMap(fullname,
+ enc_vec, usedchars);
+ if (tounicode) {
+ pdf_add_dict(fontdict,
+ pdf_new_name("ToUnicode"),
+ pdf_ref_obj (tounicode));
+ pdf_release_obj(tounicode);
+ }
+ }
+ }
+
+ cff_set_name(cffont, fullname);
+ RELEASE(fullname);
+
+ /* defaultWidthX, CapHeight, etc. */
+ get_font_attr(font, cffont);
+ if (cff_dict_known(cffont->private[0], "defaultWidthX")) {
+ defaultwidth = cff_dict_get(cffont->private[0], "defaultWidthX", 0);
+ } else {
+ defaultwidth = 0.0;
+ }
+ if (cff_dict_known(cffont->private[0], "nominalWidthX")) {
+ nominalwidth = cff_dict_get(cffont->private[0], "nominalWidthX", 0);
+ } else {
+ nominalwidth = 0.0;
+ }
+
+ /* Create CFF encoding, charset, sort glyphs */
+#define MAX_GLYPHS 1024
+ GIDMap = NEW(MAX_GLYPHS, card16);
+ {
+ int prev, duplicate;
+ long gid;
+ char *glyph;
+ s_SID sid;
+
+ cffont->encoding = NEW(1, cff_encoding);
+ cffont->encoding->format = 1;
+ cffont->encoding->num_entries = 0;
+ cffont->encoding->data.range1 = NEW(256, cff_range1);
+ cffont->encoding->num_supps = 0;
+ cffont->encoding->supp = NEW(256, cff_map);
+
+ charset = NEW(1, cff_charsets);
+ charset->format = 0;
+ charset->num_entries = 0;
+ charset->data.glyphs = NEW(MAX_GLYPHS, s_SID);
+
+ gid = cff_glyph_lookup(cffont, ".notdef");
+ if (gid < 0)
+ ERROR("Type 1 font with no \".notdef\" glyph???");
+ GIDMap[0] = (card16) gid;
+ if (verbose > 2)
+ MESG("[glyphs:/.notdef");
+ num_glyphs = 1;
+ for (prev = -2, code = 0; code <= 0xff; code++) {
+ glyph = enc_vec[code];
+
+ if (!usedchars[code])
+ continue;
+ if (glyph && !strcmp(glyph, ".notdef")) {
+ WARN("Character mapped to .notdef used in font: %s",
+ fontname);
+ usedchars[code] = 0;
+ continue;
+ }
+
+ gid = cff_glyph_lookup(cffont, glyph);
+ if (gid < 1 || gid >= cffont->cstrings->count) {
+ WARN("Glyph \"%s\" missing in font \"%s\".", glyph, fontname);
+ usedchars[code] = 0;
+ continue;
+ }
+
+ for (duplicate = 0; duplicate < code; duplicate++) {
+ if (usedchars[duplicate] &&
+ enc_vec[duplicate] && !strcmp(enc_vec[duplicate], glyph))
+ break;
+ }
+
+ sid = cff_add_string(cffont, glyph, 1); /* FIXME */
+ if (duplicate < code) { /* found duplicates */
+ cffont->encoding->supp[cffont->encoding->num_supps].code = duplicate;
+ cffont->encoding->supp[cffont->encoding->num_supps].glyph = sid;
+ cffont->encoding->num_supps += 1;
+ } else {
+ GIDMap[num_glyphs] = (card16) gid;
+ charset->data.glyphs[charset->num_entries] = sid;
+ charset->num_entries += 1;
+ if (code != prev + 1) {
+ cffont->encoding->num_entries += 1;
+ cffont->encoding->data.range1[cffont->encoding->num_entries-1].first = code;
+ cffont->encoding->data.range1[cffont->encoding->num_entries-1].n_left = 0;
+ } else {
+ cffont->encoding->data.range1[cffont->encoding->num_entries-1].n_left += 1;
+ }
+ prev = code;
+ num_glyphs++;
+
+ if (verbose > 2) {
+ MESG("/%s", glyph);
+ }
+
+ }
+ }
+ if (cffont->encoding->num_supps > 0) {
+ cffont->encoding->format |= 0x80;
+ } else {
+ RELEASE(cffont->encoding->supp); /* FIXME */
+ cffont->encoding->supp = NULL;
+ }
+ }
+
+ widths = NEW(cffont->cstrings->count, double);
+ /*
+ * No more string will be added.
+ * The Type 1 seac operator may add another glyph but the glyph name of
+ * those glyphs are contained in standard string. The String Index will
+ * not be modified after here.
+ * BUT: We cannot update the String Index yet because then we wouldn't be
+ * able to find the GIDs of the base and accent characters (unless they
+ * have been used already).
+ */
+
+ {
+ cff_index *cstring;
+ t1_ginfo gm;
+ card16 gid, gid_orig;
+ long dstlen_max, srclen;
+ card8 *srcptr, *dstptr;
+
+ offset = dstlen_max = 0L;
+ cstring = cff_new_index(cffont->cstrings->count);
+ cstring->data = NULL;
+ cstring->offset[0] = 1;
+
+ /* The num_glyphs increases if "seac" operators are used. */
+ for (gid = 0; gid < num_glyphs; gid++) {
+ if (offset + CS_STR_LEN_MAX >= dstlen_max) {
+ dstlen_max += CS_STR_LEN_MAX * 2;
+ cstring->data = RENEW(cstring->data, dstlen_max, card8);
+ }
+ gid_orig = GIDMap[gid];
+
+ dstptr = cstring->data + cstring->offset[gid] - 1;
+ srcptr = cffont->cstrings->data + cffont->cstrings->offset[gid_orig] - 1;
+ srclen = cffont->cstrings->offset[gid_orig + 1] - cffont->cstrings->offset[gid_orig];
+
+ offset += t1char_convert_charstring(dstptr, CS_STR_LEN_MAX,
+ srcptr, srclen,
+ cffont->subrs[0], defaultwidth, nominalwidth, &gm);
+ cstring->offset[gid + 1] = offset + 1;
+ if (gm.use_seac) {
+ long bchar_gid, achar_gid, i;
+ const char *bchar_name, *achar_name;
+
+ /*
+ * NOTE:
+ * 1. seac.achar and seac.bchar must be contained in the CFF standard string.
+ * 2. Those characters need not to be encoded.
+ * 3. num_glyphs == charsets->num_entries + 1.
+ */
+ achar_name = t1_get_standard_glyph(gm.seac.achar);
+ achar_gid = cff_glyph_lookup(cffont, achar_name);
+ bchar_name = t1_get_standard_glyph(gm.seac.bchar);
+ bchar_gid = cff_glyph_lookup(cffont, bchar_name);
+ if (achar_gid < 0) {
+ WARN("Accent char \"%s\" not found. Invalid use of \"seac\" operator.",
+ achar_name);
+ continue;
+ }
+ if (bchar_gid < 0) {
+ WARN("Base char \"%s\" not found. Invalid use of \"seac\" operator.",
+ bchar_name);
+ continue;
+ }
+
+ for (i = 0; i < num_glyphs; i++) {
+ if (GIDMap[i] == achar_gid)
+ break;
+ }
+ if (i == num_glyphs) {
+ if (verbose > 2)
+ MESG("/%s", achar_name);
+ GIDMap[num_glyphs++] = achar_gid;
+ charset->data.glyphs[charset->num_entries] = cff_get_seac_sid(cffont, achar_name);
+ charset->num_entries += 1;
+ }
+
+ for (i = 0; i < num_glyphs; i++) {
+ if (GIDMap[i] == bchar_gid)
+ break;
+ }
+ if (i == num_glyphs) {
+ if (verbose > 2)
+ MESG("/%s", bchar_name);
+ GIDMap[num_glyphs++] = bchar_gid;
+ charset->data.glyphs[charset->num_entries] = cff_get_seac_sid(cffont, bchar_name);
+ charset->num_entries += 1;
+ }
+ }
+ widths[gid] = gm.wx;
+ }
+ cstring->count = num_glyphs;
+
+ cff_release_index(cffont->subrs[0]);
+ cffont->subrs[0] = NULL;
+ RELEASE(cffont->subrs);
+ cffont->subrs = NULL;
+
+ cff_release_index(cffont->cstrings);
+ cffont->cstrings = cstring;
+
+ cff_release_charsets(cffont->charsets);
+ cffont->charsets = charset;
+ }
+ if (verbose > 2)
+ MESG("]");
+
+ /* Now we can update the String Index */
+ cff_dict_update (cffont->topdict, cffont);
+ cff_dict_update (cffont->private[0], cffont);
+ cff_update_string(cffont);
+
+ add_metrics(font, cffont, enc_vec, widths, num_glyphs);
+
+ offset = write_fontfile(font, cffont, num_glyphs);
+ if (verbose > 1)
+ MESG("[%u glyphs][%ld bytes]", num_glyphs, offset);
+
+ cff_close(cffont);
+
+ /* Cleanup */
+ if (encoding_id < 0 && enc_vec) {
+ for (code = 0; code < 256; code++) {
+ if (enc_vec[code])
+ RELEASE(enc_vec[code]);
+ enc_vec[code] = NULL;
+ }
+ RELEASE(enc_vec);
+ }
+ if (widths)
+ RELEASE(widths);
+ if (GIDMap)
+ RELEASE(GIDMap);
+
+ /*
+ * Maybe writing Charset is recommended for subsetted font.
+ */
+
+ return 0;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/type1c.c b/Build/source/texk/dvipdf-x/xsrc/type1c.c
new file mode 100644
index 00000000000..64c67ecb4d3
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/type1c.c
@@ -0,0 +1,750 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2008-2012 by Jin-Hwan Cho, Matthias Franz, and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+/*
+ * CFF/OpenType Font support:
+ *
+ * Adobe Technical Note #5176, "The Compact Font Format Specfication"
+ *
+ * NOTE:
+ *
+ * Many CFF/OpenType does not have meaningful/correct CFF encoding.
+ * Encoding should be expilicitly supplied in the fontmap.
+ *
+ */
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <string.h>
+
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+
+#include "dpxfile.h"
+
+#include "pdfobj.h"
+#include "pdffont.h"
+
+#include "pdfencoding.h"
+#include "unicode.h"
+
+/* Font info. from OpenType tables */
+#include "sfnt.h"
+#include "tt_aux.h"
+
+#include "cff_types.h"
+#include "cff_limits.h"
+#include "cff.h"
+#include "cff_dict.h"
+#include "cs_type2.h"
+
+#include "type1c.h"
+
+#include "tfm.h"
+
+int
+pdf_font_open_type1c (pdf_font *font)
+{
+ char *fontname;
+ FILE *fp = NULL;
+ sfnt *sfont;
+ cff_font *cffont;
+ pdf_obj *descriptor, *tmp;
+ unsigned long offset = 0;
+ int encoding_id, embedding;
+
+ ASSERT(font);
+
+ pdf_font_get_ident (font);
+ encoding_id = pdf_font_get_encoding(font);
+
+#ifdef XETEX
+ sfont = sfnt_open(pdf_font_get_ft_face(font), SFNT_TYPE_POSTSCRIPT);
+ if (!sfont)
+ return -1;
+#else
+ fp = DPXFOPEN(ident, DPX_RES_TYPE_OTFONT);
+ if (!fp)
+ return -1;
+
+ sfont = sfnt_open(fp);
+#endif
+ if (!sfont ||
+ sfont->type != SFNT_TYPE_POSTSCRIPT ||
+ sfnt_read_table_directory(sfont, 0) < 0) {
+ ERROR("Not a CFF/OpenType font?");
+ }
+
+ offset = sfnt_find_table_pos(sfont, "CFF ");
+ if (offset < 1) {
+ ERROR("No \"CFF \" table found. Not a CFF/OpenType font?");
+ }
+
+ cffont = cff_open(sfont, offset, 0);
+ if (!cffont) {
+ ERROR("Could not read CFF font data");
+ }
+
+ if (cffont->flag & FONTTYPE_CIDFONT) {
+ cff_close (cffont);
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+ return -1;
+ }
+
+ fontname = cff_get_name(cffont);
+ if (!fontname) {
+ ERROR("No valid FontName found in CFF/OpenType font.");
+ }
+ pdf_font_set_fontname(font, fontname);
+ RELEASE(fontname);
+
+ cff_close(cffont);
+
+ /*
+ * Font like AdobePiStd does not have meaningful built-in encoding.
+ * Some software generate CFF/OpenType font with incorrect encoding.
+ */
+ if (encoding_id < 0) {
+ WARN("Built-in encoding used for CFF/OpenType font.");
+ WARN("CFF font in OpenType font sometimes have strange built-in encoding.");
+ WARN("If you find text is not encoded properly in the generated PDF file,");
+ WARN("please specify appropriate \".enc\" file in your fontmap.");
+ }
+ pdf_font_set_subtype (font, PDF_FONT_FONTTYPE_TYPE1C);
+
+ embedding = pdf_font_get_flag(font, PDF_FONT_FLAG_NOEMBED) ? 0 : 1;
+ descriptor = pdf_font_get_descriptor(font);
+ /*
+ * Create font descriptor from OpenType tables.
+ * We can also use CFF TOP DICT/Private DICT for this.
+ */
+ tmp = tt_get_fontdesc(sfont, &embedding, -1, 1, fontname);
+ if (!tmp) {
+ ERROR("Could not obtain neccesary font info from OpenType table.");
+ return -1;
+ }
+ pdf_merge_dict (descriptor, tmp); /* copy */
+ pdf_release_obj(tmp);
+ if (!embedding) { /* tt_get_fontdesc may have changed this */
+ pdf_font_set_flags(font, PDF_FONT_FLAG_NOEMBED);
+ }
+
+ sfnt_close(sfont);
+ if (fp)
+ DPXFCLOSE(fp);
+
+ return 0;
+}
+
+static void
+add_SimpleMetrics (pdf_font *font, cff_font *cffont,
+ double *widths, card16 num_glyphs)
+{
+ pdf_obj *fontdict;
+ int code, firstchar, lastchar, tfm_id;
+ char *usedchars;
+ pdf_obj *tmp_array;
+ double scaling;
+
+ fontdict = pdf_font_get_resource(font);
+ usedchars = pdf_font_get_usedchars(font);
+
+ /* The widhts array in the font dictionary must be given relative
+ * to the default scaling of 1000:1, not relative to the scaling
+ * given by the font matrix.
+ */
+ if (cff_dict_known(cffont->topdict, "FontMatrix"))
+ scaling = 1000*cff_dict_get(cffont->topdict, "FontMatrix", 0);
+ else
+ scaling = 1;
+
+ tmp_array = pdf_new_array();
+ if (num_glyphs <= 1) {
+ /* This should be error. */
+ firstchar = lastchar = 0;
+ pdf_add_array(tmp_array, pdf_new_number(0.0));
+ } else {
+ firstchar = 255; lastchar = 0;
+ for (code = 0; code < 256; code++) {
+ if (usedchars[code]) {
+ if (code < firstchar) firstchar = code;
+ if (code > lastchar) lastchar = code;
+ }
+ }
+ if (firstchar > lastchar) {
+ ERROR("No glyphs used at all!");
+ pdf_release_obj(tmp_array);
+ return;
+ }
+ tfm_id = tfm_open(pdf_font_get_mapname(font), 0);
+ for (code = firstchar; code <= lastchar; code++) {
+ if (usedchars[code]) {
+ double width;
+ if (tfm_id < 0) /* tfm is not found */
+ width = scaling * widths[code];
+ else
+ width = 1000. * tfm_get_width(tfm_id, code);
+ pdf_add_array(tmp_array,
+ pdf_new_number(ROUND(width, 0.1)));
+ } else {
+ pdf_add_array(tmp_array, pdf_new_number(0.0));
+ }
+ }
+ }
+
+ if (pdf_array_length(tmp_array) > 0) {
+ pdf_add_dict(fontdict,
+ pdf_new_name("Widths"), pdf_ref_obj(tmp_array));
+ }
+ pdf_release_obj(tmp_array);
+
+ pdf_add_dict(fontdict,
+ pdf_new_name("FirstChar"), pdf_new_number(firstchar));
+ pdf_add_dict(fontdict,
+ pdf_new_name("LastChar"), pdf_new_number(lastchar));
+
+ return;
+}
+
+int
+pdf_font_load_type1c (pdf_font *font)
+{
+ pdf_obj *fontdict, *descriptor;
+ char *usedchars;
+ char *fontname, *uniqueTag, *ident, *fullname;
+ FILE *fp = NULL;
+ int encoding_id;
+ pdf_obj *fontfile, *stream_dict;
+ char **enc_vec;
+ sfnt *sfont;
+ cff_font *cffont;
+ cff_index *charstrings, *topdict, *cs_idx;
+ cff_charsets *charset = NULL;
+ cff_encoding *encoding = NULL;
+ long topdict_offset, private_size;
+ long charstring_len, max_len;
+ long size, offset = 0;
+ long stream_data_len = 0;
+ card8 *stream_data_ptr, *data;
+ card16 num_glyphs, cs_count, code;
+ cs_ginfo ginfo;
+ double nominal_width, default_width, notdef_width;
+ double widths[256];
+ int verbose;
+
+ ASSERT(font);
+
+ verbose = pdf_font_get_verbose();
+
+ if (!pdf_font_is_in_use(font)) {
+ return 0;
+ }
+
+ if (pdf_font_get_flag(font, PDF_FONT_FLAG_NOEMBED)) {
+ ERROR("Only embedded font supported for CFF/OpenType font.");
+ }
+
+ usedchars = pdf_font_get_usedchars (font);
+ fontname = pdf_font_get_fontname (font);
+ ident = pdf_font_get_ident (font);
+ uniqueTag = pdf_font_get_uniqueTag (font);
+ if (!usedchars ||
+ !fontname || !ident) {
+ ERROR("Unexpected error....");
+ }
+
+ fontdict = pdf_font_get_resource (font);
+ descriptor = pdf_font_get_descriptor(font);
+ encoding_id = pdf_font_get_encoding (font);
+
+#ifdef XETEX
+ sfont = sfnt_open(pdf_font_get_ft_face(font), SFNT_TYPE_POSTSCRIPT);
+#else
+ fp = DPXFOPEN(ident, DPX_RES_TYPE_OTFONT);
+ if (!fp) {
+ ERROR("Could not open OpenType font: %s", ident);
+ }
+
+ sfont = sfnt_open(fp);
+#endif
+ if (!sfont) {
+ ERROR("Could not open OpenType font: %s", ident);
+ }
+ if (sfnt_read_table_directory(sfont, 0) < 0) {
+ ERROR("Could not read OpenType table directory: %s", ident);
+ }
+ if (sfont->type != SFNT_TYPE_POSTSCRIPT ||
+ (offset = sfnt_find_table_pos(sfont, "CFF ")) == 0) {
+ ERROR("Not a CFF/OpenType font ?");
+ }
+
+ cffont = cff_open(sfont, offset, 0);
+ if (!cffont) {
+ ERROR("Could not open CFF font.");
+ }
+ if (cffont->flag & FONTTYPE_CIDFONT) {
+ ERROR("This is CIDFont...");
+ }
+
+ fullname = NEW(strlen(fontname) + 8, char);
+ sprintf(fullname, "%6s+%s", uniqueTag, fontname);
+
+ /* Offsets from DICTs */
+ cff_read_charsets(cffont);
+ if (encoding_id < 0)
+ cff_read_encoding(cffont);
+ cff_read_private(cffont);
+ cff_read_subrs (cffont);
+
+ /* FIXME */
+ cffont->_string = cff_new_index(0);
+
+ /* New Charsets data */
+ charset = NEW(1, cff_charsets);
+ charset->format = 0;
+ charset->num_entries = 0;
+ charset->data.glyphs = NEW(256, s_SID);
+
+ /*
+ * Encoding related things.
+ */
+ enc_vec = NULL;
+ if (encoding_id >= 0) {
+ enc_vec = pdf_encoding_get_encoding(encoding_id);
+ } else {
+ pdf_obj *tounicode;
+
+ /*
+ * Create enc_vec and ToUnicode CMap for built-in encoding.
+ */
+ enc_vec = NEW(256, char *);
+ for (code = 0; code < 256; code++) {
+ if (usedchars[code]) {
+ card16 gid;
+
+ gid = cff_encoding_lookup(cffont, code);
+ enc_vec[code] = cff_get_string(cffont,
+ cff_charsets_lookup_inverse(cffont, gid));
+ } else {
+ enc_vec[code] = NULL;
+ }
+ }
+ if (!pdf_lookup_dict(fontdict, "ToUnicode")) {
+ tounicode = pdf_create_ToUnicode_CMap(fullname,
+ enc_vec, usedchars);
+ if (tounicode) {
+ pdf_add_dict(fontdict,
+ pdf_new_name("ToUnicode"),
+ pdf_ref_obj (tounicode));
+ pdf_release_obj(tounicode);
+ }
+ }
+ }
+
+ /*
+ * New Encoding data:
+ *
+ * We should not use format 0 here.
+ * The number of encoded glyphs (num_entries) is limited to 255 in format 0,
+ * and hence it causes problem for encodings that uses full 256 code-points.
+ * As we always sort glyphs by encoding, we can avoid this problem simply
+ * by using format 1; Using full range result in a single range, 0 255.
+ *
+ * Creating actual encoding date is delayed to eliminate character codes to
+ * be mapped to .notdef and to handle multiply-encoded glyphs.
+ */
+ encoding = NEW(1, cff_encoding);
+ encoding->format = 1;
+ encoding->num_entries = 0;
+ encoding->data.range1 = NEW(255, cff_range1);
+ encoding->num_supps = 0;
+ encoding->supp = NEW(255, cff_map);
+
+ /*
+ * Charastrings.
+ */
+ offset = (long) cff_dict_get(cffont->topdict, "CharStrings", 0);
+ cff_seek_set(cffont, offset);
+ cs_idx = cff_get_index_header(cffont);
+
+ /* Offset is now absolute offset ... fixme */
+ offset = cffont->sfont->loc;
+ cs_count = cs_idx->count;
+ if (cs_count < 2) {
+ ERROR("No valid charstring data found.");
+ }
+
+ /* New CharStrings INDEX */
+ charstrings = cff_new_index(257); /* 256 + 1 for ".notdef" glyph */
+ max_len = 2 * CS_STR_LEN_MAX;
+ charstrings->data = NEW(max_len, card8);
+ charstring_len = 0;
+
+ /*
+ * Information from OpenType table is rough estimate. Replace with accurate value.
+ */
+ if (cffont->private[0] &&
+ cff_dict_known(cffont->private[0], "StdVW")) {
+ double stemv;
+
+ stemv = cff_dict_get(cffont->private[0], "StdVW", 0);
+ pdf_add_dict(descriptor,
+ pdf_new_name("StemV"), pdf_new_number(stemv));
+ }
+
+ /*
+ * Widths
+ */
+ if (cffont->private[0] &&
+ cff_dict_known(cffont->private[0], "defaultWidthX")) {
+ default_width = (double) cff_dict_get(cffont->private[0], "defaultWidthX", 0);
+ } else {
+ default_width = CFF_DEFAULTWIDTHX_DEFAULT;
+ }
+ if (cffont->private[0] &&
+ cff_dict_known(cffont->private[0], "nominalWidthX")) {
+ nominal_width = (double) cff_dict_get(cffont->private[0], "nominalWidthX", 0);
+ } else {
+ nominal_width = CFF_NOMINALWIDTHX_DEFAULT;
+ }
+
+ data = NEW(CS_STR_LEN_MAX, card8);
+
+ /* First we add .notdef glyph.
+ * All Type 1 font requires .notdef glyph to be present.
+ */
+ if (verbose > 2) {
+ MESG("[glyphs:/.notdef");
+ }
+ size = cs_idx->offset[1] - cs_idx->offset[0];
+ if (size > CS_STR_LEN_MAX) {
+ ERROR("Charstring too long: gid=%u, %ld bytes", 0, size);
+ }
+ charstrings->offset[0] = charstring_len + 1;
+ sfnt_seek_set(cffont->sfont, offset + cs_idx->offset[0] - 1);
+ sfnt_read(data, size, cffont->sfont);
+ charstring_len += cs_copy_charstring(charstrings->data + charstring_len,
+ max_len - charstring_len,
+ data, size,
+ cffont->gsubr, cffont->subrs[0],
+ default_width, nominal_width, &ginfo);
+ notdef_width = ginfo.wx;
+
+ /*
+ * Subset font
+ */
+ num_glyphs = 1;
+ for (code = 0; code < 256; code++) {
+ card16 gid, j;
+ s_SID sid_orig, sid;
+
+ widths[code] = notdef_width;
+
+ if (!usedchars[code] || !enc_vec[code] ||
+ !strcmp(enc_vec[code], ".notdef"))
+ continue;
+
+ /*
+ * FIXME:
+ * cff_get_sid() obtain SID from original String INDEX.
+ * It should be cff_string_get_sid(string, ...).
+ * cff_add_string(cff, ...) -> cff_string_add(string, ...).
+ */
+ sid_orig = cff_get_sid (cffont, enc_vec[code]);
+ sid = sid_orig < CFF_STDSTR_MAX ?
+ sid_orig : cff_add_string(cffont, enc_vec[code], 0);
+ /*
+ * We use "unique = 0" because duplicate strings are impossible
+ * at this stage unless the original font already had duplicates.
+ */
+
+ /*
+ * Check if multiply-encoded glyph.
+ */
+ for (j = 0; j < charset->num_entries; j++) {
+ if (sid == charset->data.glyphs[j]) {
+ /* Already have this glyph. */
+ encoding->supp[encoding->num_supps].code = code;
+ encoding->supp[encoding->num_supps].glyph = sid;
+ usedchars[code] = 0; /* Used but multiply-encoded. */
+ encoding->num_supps += 1;
+ break;
+ }
+ }
+ if (j < charset->num_entries) {
+ continue; /* Prevent duplication. */
+ }
+
+ /* This is new encoding entry. */
+ gid = cff_charsets_lookup(cffont, sid_orig); /* FIXME */
+ if (gid == 0) {
+ WARN("Glyph \"%s\" missing in font \"%s\".", enc_vec[code], fontname);
+ WARN("Maybe incorrect encoding specified.");
+ usedchars[code] = 0; /* Set unused for writing correct encoding */
+ continue;
+ }
+ if (verbose > 2) {
+ MESG("/%s", enc_vec[code]);
+ }
+
+ size = cs_idx->offset[gid+1] - cs_idx->offset[gid];
+ if (size > CS_STR_LEN_MAX) {
+ ERROR("Charstring too long: gid=%u, %ld bytes", gid, size);
+ }
+
+ if (charstring_len + CS_STR_LEN_MAX >= max_len) {
+ max_len = charstring_len + 2 * CS_STR_LEN_MAX;
+ charstrings->data = RENEW(charstrings->data, max_len, card8);
+ }
+ charstrings->offset[num_glyphs] = charstring_len + 1;
+ sfnt_seek_set(cffont->sfont, offset + cs_idx->offset[gid] - 1);
+ sfnt_read(data, size, cffont->sfont);
+ charstring_len += cs_copy_charstring(charstrings->data + charstring_len,
+ max_len - charstring_len,
+ data, size,
+ cffont->gsubr, cffont->subrs[0],
+ default_width, nominal_width, &ginfo);
+ widths[code] = ginfo.wx;
+ charset->data.glyphs[charset->num_entries] = sid;
+ charset->num_entries += 1;
+ num_glyphs++;
+ }
+ if (verbose > 2) {
+ MESG("]");
+ }
+ RELEASE(data);
+
+ /*
+ * Now we create encoding data.
+ */
+ if (encoding->num_supps > 0)
+ encoding->format |= 0x80; /* Have supplemantary data. */
+ else {
+ RELEASE(encoding->supp); /* FIXME */
+ }
+ for (code = 0; code < 256; code++) {
+ if (!usedchars[code] ||
+ !enc_vec[code] || !strcmp(enc_vec[code], ".notdef"))
+ continue;
+ encoding->data.range1[encoding->num_entries].first = code;
+ encoding->data.range1[encoding->num_entries].n_left = 0;
+ code++;
+ while (code < 256 && usedchars[code] &&
+ enc_vec[code] && strcmp(enc_vec[code], ".notdef")) {
+ encoding->data.range1[encoding->num_entries].n_left += 1;
+ code++;
+ }
+ encoding->num_entries += 1;
+ /* The above while() loop stopped at unused char or code == 256. */
+ }
+
+ /* cleanup */
+ if (encoding_id < 0 && enc_vec) {
+ for (code = 0; code < 256; code++) {
+ if (enc_vec[code]) {
+ RELEASE(enc_vec[code]);
+ }
+ }
+ RELEASE(enc_vec);
+ }
+
+ cff_release_index(cs_idx);
+
+ charstrings->offset[num_glyphs] = charstring_len + 1;
+ charstrings->count = num_glyphs;
+ charstring_len = cff_index_size(charstrings);
+ cffont->num_glyphs = num_glyphs;
+
+ /*
+ * Discard old one, set new data.
+ */
+ if (cffont->charsets)
+ cff_release_charsets(cffont->charsets);
+ cffont->charsets = charset;
+ if (cffont->encoding)
+ cff_release_encoding(cffont->encoding);
+ cffont->encoding = encoding;
+ /*
+ * We don't use subroutines at all.
+ */
+ if (cffont->gsubr)
+ cff_release_index(cffont->gsubr);
+ cffont->gsubr = cff_new_index(0);
+ if (cffont->subrs[0])
+ cff_release_index(cffont->subrs[0]);
+ cffont->subrs[0] = NULL;
+
+ /*
+ * Flag must be reset since cff_pack_encoding(charset) does not write
+ * encoding(charset) if HAVE_STANDARD_ENCODING(CHARSET) is set. We are
+ * re-encoding font.
+ */
+ cffont->flag = FONTTYPE_FONT;
+
+ /*
+ * FIXME:
+ * Update String INDEX to delete unused strings.
+ */
+ cff_dict_update(cffont->topdict, cffont);
+ if (cffont->private[0])
+ cff_dict_update(cffont->private[0], cffont);
+ cff_update_string(cffont);
+
+ /*
+ * Calculate sizes of Top DICT and Private DICT.
+ * All offset values in DICT are set to long (32-bit) integer
+ * in cff_dict_pack(), those values are updated later.
+ */
+ topdict = cff_new_index(1);
+
+ cff_dict_remove(cffont->topdict, "UniqueID");
+ cff_dict_remove(cffont->topdict, "XUID");
+
+ /*
+ * Force existence of Encoding.
+ */
+ if (!cff_dict_known(cffont->topdict, "Encoding"))
+ cff_dict_add(cffont->topdict, "Encoding", 1);
+ topdict->offset[1] = cff_dict_pack(cffont->topdict,
+ (card8 *) work_buffer,
+ WORK_BUFFER_SIZE) + 1;
+ private_size = 0;
+ if (cffont->private[0]) {
+ cff_dict_remove(cffont->private[0], "Subrs"); /* no Subrs */
+ private_size = cff_dict_pack(cffont->private[0],
+ (card8 *) work_buffer, WORK_BUFFER_SIZE);
+ }
+
+ /*
+ * Estimate total size of fontfile.
+ */
+ stream_data_len = 4; /* header size */
+
+ stream_data_len += cff_set_name(cffont, fullname);
+ RELEASE(fullname);
+
+ stream_data_len += cff_index_size(topdict);
+ stream_data_len += cff_index_size(cffont->string);
+ stream_data_len += cff_index_size(cffont->gsubr);
+
+ /* We are using format 1 for Encoding and format 0 for charset.
+ * TODO: Should implement cff_xxx_size().
+ */
+ stream_data_len += 2 + (encoding->num_entries)*2 + 1 + (encoding->num_supps)*3;
+ stream_data_len += 1 + (charset->num_entries)*2;
+ stream_data_len += charstring_len;
+ stream_data_len += private_size;
+
+ /*
+ * Now we create FontFile data.
+ */
+ stream_data_ptr = NEW(stream_data_len, card8);
+
+ /*
+ * Data Layout order as described in CFF spec., sec 2 "Data Layout".
+ */
+ offset = 0;
+ /* Header */
+ offset += cff_put_header(cffont, stream_data_ptr + offset, stream_data_len - offset);
+ /* Name */
+ offset += cff_pack_index(cffont->name, stream_data_ptr + offset, stream_data_len - offset);
+ /* Top DICT */
+ topdict_offset = offset;
+ offset += cff_index_size(topdict);
+ /* Strings */
+ offset += cff_pack_index(cffont->string,
+ stream_data_ptr + offset, stream_data_len - offset);
+ /* Global Subrs */
+ offset += cff_pack_index(cffont->gsubr,
+ stream_data_ptr + offset, stream_data_len - offset);
+ /* Encoding */
+ cff_dict_set(cffont->topdict, "Encoding", 0, offset);
+ offset += cff_pack_encoding(cffont,
+ stream_data_ptr + offset, stream_data_len - offset);
+ /* charset */
+ cff_dict_set(cffont->topdict, "charset", 0, offset);
+ offset += cff_pack_charsets(cffont,
+ stream_data_ptr + offset, stream_data_len - offset);
+ /* CharStrings */
+ cff_dict_set(cffont->topdict, "CharStrings", 0, offset);
+ offset += cff_pack_index(charstrings,
+ stream_data_ptr + offset, charstring_len);
+ cff_release_index(charstrings);
+ /* Private */
+ cff_dict_set(cffont->topdict, "Private", 1, offset);
+ if (cffont->private[0] && private_size > 0)
+ private_size = cff_dict_pack(cffont->private[0],
+ stream_data_ptr + offset, private_size);
+ cff_dict_set(cffont->topdict, "Private", 0, private_size);
+ offset += private_size;
+
+ /* Finally Top DICT */
+ topdict->data = NEW(topdict->offset[1] - 1, card8);
+ cff_dict_pack (cffont->topdict, topdict->data, topdict->offset[1] - 1);
+ cff_pack_index(topdict,
+ stream_data_ptr + topdict_offset, cff_index_size(topdict));
+ cff_release_index(topdict);
+
+ /* Copyright and Trademark Notice ommited. */
+
+ /* Handle Widths in fontdict. */
+ add_SimpleMetrics(font, cffont, widths, num_glyphs);
+
+ /* Close font */
+ cff_close (cffont);
+ sfnt_close(sfont);
+
+ if (fp)
+ DPXFCLOSE(fp);
+
+ if (verbose > 1) {
+ MESG("[%u/%u glyphs][%ld bytes]", num_glyphs, cs_count, offset);
+ }
+
+ /*
+ * CharSet might be recommended for subsetted font, but it is meaningful
+ * only for Type 1 font...
+ */
+
+ /*
+ * Write PDF FontFile data.
+ */
+ fontfile = pdf_new_stream(STREAM_COMPRESS);
+ stream_dict = pdf_stream_dict(fontfile);
+ pdf_add_dict(descriptor,
+ pdf_new_name("FontFile3"), pdf_ref_obj (fontfile));
+ pdf_add_dict(stream_dict,
+ pdf_new_name("Subtype"), pdf_new_name("Type1C"));
+ pdf_add_stream (fontfile, (void *) stream_data_ptr, offset);
+ pdf_release_obj(fontfile);
+
+ RELEASE(stream_data_ptr);
+
+ return 0;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/vf.c b/Build/source/texk/dvipdf-x/xsrc/vf.c
new file mode 100644
index 00000000000..fea4f2739df
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/vf.c
@@ -0,0 +1,1042 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2007-2012 by Jin-Hwan Cho and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#if HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "system.h"
+#include "numbers.h"
+#include "error.h"
+#include "mem.h"
+
+#include "dpxfile.h"
+/* pdfdev... */
+#include "pdfdev.h"
+
+#include "tfm.h"
+#include "dvi.h"
+#include "vf.h"
+
+#include "dvicodes.h"
+
+#define VF_ALLOC_SIZE 16u
+
+#define VF_ID 202
+#define FIX_WORD_BASE 1048576.0
+#define TEXPT2PT (72.0/72.27)
+#define FW2PT (TEXPT2PT/((double)(FIX_WORD_BASE)))
+
+static unsigned char verbose = 0;
+
+void vf_set_verbose(void)
+{
+ if (verbose < 255) verbose++;
+}
+
+struct font_def {
+ signed long font_id /* id used internally in vf file */;
+ unsigned long checksum, size, design_size;
+ char *directory, *name;
+ int tfm_id; /* id returned by TFM module */
+ int dev_id; /* id returned by DEV module */
+};
+
+struct vf
+{
+ char *tex_name;
+ spt_t ptsize;
+ unsigned long design_size; /* A fixword-pts quantity */
+ int num_dev_fonts, max_dev_fonts;
+ struct font_def *dev_fonts;
+ unsigned char **ch_pkt;
+ unsigned long *pkt_len;
+ unsigned num_chars;
+};
+
+struct vf *vf_fonts = NULL;
+int num_vf_fonts = 0, max_vf_fonts = 0;
+
+static int read_header(FILE *vf_file, int thisfont)
+{
+ int i, result = 1, ch;
+
+ /* Check for usual signature */
+ if ((ch = get_unsigned_byte (vf_file)) == PRE &&
+ (ch = get_unsigned_byte (vf_file)) == VF_ID) {
+
+ /* If here, assume it's a legitimate vf file */
+ ch = get_unsigned_byte (vf_file);
+
+ /* skip comment */
+ for (i=0; i<ch; i++)
+ get_unsigned_byte (vf_file);
+
+ /* Skip checksum */
+ get_unsigned_quad(vf_file);
+
+ vf_fonts[thisfont].design_size =
+ get_unsigned_quad(vf_file);
+ } else { /* Try to fail gracefully and return an error to caller */
+ fprintf (stderr, "VF file may be corrupt\n");
+ result = 0;
+ }
+ return result;
+}
+
+
+static void resize_vf_fonts(int size)
+{
+ int i;
+ if (size > max_vf_fonts) {
+ vf_fonts = RENEW (vf_fonts, size, struct vf);
+ for (i=max_vf_fonts; i<size; i++) {
+ vf_fonts[i].num_dev_fonts = 0;
+ vf_fonts[i].max_dev_fonts = 0;
+ vf_fonts[i].dev_fonts = NULL;
+ }
+ max_vf_fonts = size;
+ }
+ return;
+}
+
+static void resize_one_vf_font (struct vf *a_vf, unsigned size)
+{
+ unsigned i;
+ if (size > (a_vf->num_chars)) {
+ size = MAX (size, a_vf->num_chars+256);
+ a_vf->ch_pkt = RENEW (a_vf->ch_pkt, size, unsigned char *);
+ a_vf->pkt_len = RENEW (a_vf->pkt_len, size, unsigned long);
+ for (i=a_vf->num_chars; i<size; i++) {
+ (a_vf->ch_pkt)[i] = NULL;
+ (a_vf->pkt_len)[i] = 0;
+ }
+ a_vf->num_chars = size;
+ }
+}
+
+static void read_a_char_def(FILE *vf_file, int thisfont, unsigned long pkt_len,
+ unsigned ch)
+{
+ unsigned char *pkt;
+#ifdef DEBUG
+ fprintf (stderr, "read_a_char_def: len=%ld, ch=%d\n", pkt_len, ch);
+#endif
+ /* Resize and initialize character arrays if necessary */
+ if (ch >= vf_fonts[thisfont].num_chars) {
+ resize_one_vf_font (vf_fonts+thisfont, ch+1);
+ }
+ if (pkt_len > 0) {
+ pkt = NEW (pkt_len, unsigned char);
+ if (fread (pkt, 1, pkt_len, vf_file) != pkt_len)
+ ERROR ("VF file ended prematurely.");
+ (vf_fonts[thisfont].ch_pkt)[ch] = pkt;
+ }
+ (vf_fonts[thisfont].pkt_len)[ch] = pkt_len;
+ return;
+}
+
+static void read_a_font_def(FILE *vf_file, signed long font_id, int thisfont)
+{
+ struct font_def *dev_font;
+ int dir_length, name_length;
+#ifdef DEBUG
+ fprintf (stderr, "read_a_font_def: font_id = %ld\n", font_id);
+#endif
+ if (vf_fonts[thisfont].num_dev_fonts >=
+ vf_fonts[thisfont].max_dev_fonts) {
+ vf_fonts[thisfont].max_dev_fonts += VF_ALLOC_SIZE;
+ vf_fonts[thisfont].dev_fonts = RENEW
+ (vf_fonts[thisfont].dev_fonts,
+ vf_fonts[thisfont].max_dev_fonts,
+ struct font_def);
+ }
+ dev_font = vf_fonts[thisfont].dev_fonts+
+ vf_fonts[thisfont].num_dev_fonts;
+ dev_font -> font_id = font_id;
+ dev_font -> checksum = get_unsigned_quad (vf_file);
+ dev_font -> size = get_unsigned_quad (vf_file);
+ dev_font -> design_size = get_unsigned_quad (vf_file);
+ dir_length = get_unsigned_byte (vf_file);
+ name_length = get_unsigned_byte (vf_file);
+ dev_font -> directory = NEW (dir_length+1, char);
+ dev_font -> name = NEW (name_length+1, char);
+ fread (dev_font -> directory, 1, dir_length, vf_file);
+ fread (dev_font -> name, 1, name_length, vf_file);
+ (dev_font -> directory)[dir_length] = 0;
+ (dev_font -> name)[name_length] = 0;
+ vf_fonts[thisfont].num_dev_fonts += 1;
+ dev_font->tfm_id = tfm_open (dev_font -> name, 1); /* must exist */
+ dev_font->dev_id =
+ dvi_locate_font (dev_font->name,
+ sqxfw (vf_fonts[thisfont].ptsize,
+ dev_font->size));
+#ifdef DEBUG
+ fprintf (stderr, "[%s/%s]\n", dev_font -> directory, dev_font -> name);
+#endif
+ return;
+}
+
+
+static void process_vf_file (FILE *vf_file, int thisfont)
+{
+ int eof = 0, code;
+ unsigned long font_id;
+ while (!eof) {
+ code = get_unsigned_byte (vf_file);
+ switch (code) {
+ case FNT_DEF1:
+ font_id = get_unsigned_byte (vf_file);
+ read_a_font_def (vf_file, font_id, thisfont);
+ break;
+ case FNT_DEF2:
+ font_id = get_unsigned_pair (vf_file);
+ read_a_font_def (vf_file, font_id, thisfont);
+ break;
+ case FNT_DEF3:
+ font_id = get_unsigned_triple(vf_file);
+ read_a_font_def (vf_file, font_id, thisfont);
+ break;
+ case FNT_DEF4:
+ font_id = get_signed_quad(vf_file);
+ read_a_font_def (vf_file, font_id, thisfont);
+ break;
+ default:
+ if (code < 242) {
+ long ch;
+ /* For a short packet, code is the pkt_len */
+ ch = get_unsigned_byte (vf_file);
+ /* Skip over TFM width since we already know it */
+ get_unsigned_triple (vf_file);
+ read_a_char_def (vf_file, thisfont, code, ch);
+ break;
+ }
+ if (code == 242) {
+ unsigned long pkt_len, ch;
+ pkt_len = get_unsigned_quad(vf_file);
+ ch = get_unsigned_quad (vf_file);
+ /* Skip over TFM width since we already know it */
+ get_unsigned_quad (vf_file);
+ if (ch < 65536L)
+ read_a_char_def (vf_file, thisfont, pkt_len, ch);
+ else {
+ fprintf (stderr, "char=%ld\n", ch);
+ ERROR ("Long character (>16 bits) in VF file.\nI can't handle long characters!\n");
+ }
+ break;
+ }
+ if (code == POST) {
+ eof = 1;
+ break;
+ }
+ fprintf (stderr, "Quitting on code=%d\n", code);
+ eof = 1;
+ break;
+ }
+ }
+ return;
+}
+
+/* Unfortunately, the following code isn't smart enough
+ to load the vf only once for multiple point sizes.
+ You will get a separate copy of each VF in memory (and a separate
+ opening and reading of the file) for
+ each point size. Since VFs are pretty small, I guess
+ this is tolerable for now. In any case,
+ the PDF file will never repeat a physical font name */
+/* Note: This code needs to be able to recurse */
+/* Global variables such as num_vf_fonts require careful attention */
+int vf_locate_font (const char *tex_name, spt_t ptsize)
+{
+ int thisfont = -1, i;
+ char *full_vf_file_name;
+ FILE *vf_file;
+ /* Has this name and ptsize already been loaded as a VF? */
+ for (i=0; i<num_vf_fonts; i++) {
+ if (!strcmp (vf_fonts[i].tex_name, tex_name) &&
+ vf_fonts[i].ptsize == ptsize)
+ break;
+ }
+ if (i != num_vf_fonts) {
+ thisfont = i;
+ } else {
+ /* It's hasn't already been loaded as a VF, so try to load it */
+ full_vf_file_name = kpse_find_file (tex_name,
+ kpse_vf_format,
+ 1);
+ if (!full_vf_file_name) {
+ full_vf_file_name = kpse_find_file (tex_name,
+ kpse_ovf_format,
+ 1);
+ }
+ if (full_vf_file_name &&
+ (vf_file = MFOPEN (full_vf_file_name, FOPEN_RBIN_MODE)) != NULL) {
+ if (verbose == 1)
+ fprintf (stderr, "(VF:%s", tex_name);
+ if (verbose > 1)
+ fprintf (stderr, "(VF:%s", full_vf_file_name);
+ if (num_vf_fonts >= max_vf_fonts) {
+ resize_vf_fonts (max_vf_fonts + VF_ALLOC_SIZE);
+ }
+ thisfont = num_vf_fonts++;
+ { /* Initialize some pointers and such */
+ vf_fonts[thisfont].tex_name = NEW (strlen(tex_name)+1, char);
+ strcpy (vf_fonts[thisfont].tex_name, tex_name);
+ vf_fonts[thisfont].ptsize = ptsize;
+ vf_fonts[thisfont].num_chars = 0;
+ vf_fonts[thisfont].ch_pkt = NULL;
+ vf_fonts[thisfont].pkt_len = NULL;
+ }
+ read_header(vf_file, thisfont);
+ process_vf_file (vf_file, thisfont);
+ if (verbose)
+ fprintf (stderr, ")");
+ MFCLOSE (vf_file);
+ }
+ if (full_vf_file_name)
+ RELEASE(full_vf_file_name);
+ }
+ return thisfont;
+}
+
+#define next_byte() (*((*start)++))
+static UNSIGNED_BYTE unsigned_byte (unsigned char **start, unsigned char *end)
+{
+ UNSIGNED_BYTE byte = 0;
+ if (*start < end)
+ byte = next_byte();
+ else
+ ERROR ("Premature end of DVI byte stream in VF font\n");
+ return byte;
+}
+
+static SIGNED_BYTE signed_byte (unsigned char **start, unsigned char *end)
+{
+ int byte = 0;
+ if (*start < end) {
+ byte = next_byte();
+ if (byte >= 0x80)
+ byte -= 0x100;
+ }
+ else
+ ERROR ("Premature end of DVI byte stream in VF font\n");
+ return (SIGNED_BYTE) byte;
+}
+
+static UNSIGNED_PAIR unsigned_pair (unsigned char **start, unsigned char *end)
+{
+ int i;
+ UNSIGNED_BYTE byte;
+ UNSIGNED_PAIR pair = 0;
+ if (end-*start > 1) {
+ for (i=0; i<2; i++) {
+ byte = next_byte();
+ pair = pair*0x100u + byte;
+ }
+ }
+ else
+ ERROR ("Premature end of DVI byte stream in VF font\n");
+ return pair;
+}
+
+static SIGNED_PAIR signed_pair (unsigned char **start, unsigned char *end)
+{
+ int i;
+ long pair = 0;
+ if (end - *start > 1) {
+ for (i=0; i<2; i++) {
+ pair = pair*0x100 + next_byte();
+ }
+ if (pair >= 0x8000) {
+ pair -= 0x10000l;
+ }
+ } else
+ ERROR ("Premature end of DVI byte stream in VF font\n");
+ return (SIGNED_PAIR) pair;
+}
+
+static UNSIGNED_TRIPLE unsigned_triple(unsigned char **start, unsigned
+ char *end)
+{
+ int i;
+ long triple = 0;
+ if (end-*start > 2) {
+ for (i=0; i<3; i++) {
+ triple = triple*0x100u + next_byte();
+ }
+ } else
+ ERROR ("Premature end of DVI byte stream in VF font\n");
+ return (UNSIGNED_TRIPLE) triple;
+}
+
+static SIGNED_TRIPLE signed_triple(unsigned char **start, unsigned char *end)
+{
+ int i;
+ long triple = 0;
+ if (end-*start > 2) {
+ for (i=0; i<3; i++) {
+ triple = triple*0x100 + next_byte();
+ }
+ if (triple >= 0x800000l)
+ triple -= 0x1000000l;
+ } else
+ ERROR ("Premature end of DVI byte stream in VF font\n");
+ return (SIGNED_TRIPLE) triple;
+}
+
+static SIGNED_QUAD signed_quad(unsigned char **start, unsigned char *end)
+{
+ int byte, i;
+ long quad = 0;
+ /* Check sign on first byte before reading others */
+ if (end-*start > 3) {
+ byte = next_byte();
+ quad = byte;
+ if (quad >= 0x80)
+ quad = byte - 0x100;
+ for (i=0; i<3; i++) {
+ quad = quad*0x100 + next_byte();
+ }
+ } else
+ ERROR ("Premature end of DVI byte stream in VF font\n");
+ return (SIGNED_QUAD) quad;
+}
+
+static UNSIGNED_QUAD unsigned_quad(unsigned char **start, unsigned char *end)
+{
+ int i;
+ unsigned long quad = 0;
+ if (end-*start > 3) {
+ for (i=0; i<4; i++) {
+ quad = quad*0x100u + next_byte();
+ }
+ } else
+ ERROR ("Premature end of DVI byte stream in VF font\n");
+ return (UNSIGNED_QUAD) quad;
+}
+
+static void vf_set (SIGNED_QUAD ch)
+{
+ /* Defer to the dvi_set() defined in dvi.c */
+ dvi_set (ch);
+ return;
+}
+
+static void vf_set1(unsigned char **start, unsigned char *end)
+{
+ vf_set (unsigned_byte(start, end));
+ return;
+}
+
+static void vf_set2(unsigned char **start, unsigned char *end)
+{
+ vf_set (unsigned_pair(start, end));
+ return;
+}
+
+static void vf_putrule(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ SIGNED_QUAD width, height;
+ height = signed_quad (start, end);
+ width = signed_quad (start, end);
+ if (width > 0 && height > 0) {
+ dvi_rule (sqxfw(ptsize,width), sqxfw(ptsize, height));
+ }
+ return;
+}
+
+static void vf_setrule(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ SIGNED_QUAD width, height, s_width;
+ height = signed_quad (start, end);
+ width = signed_quad (start, end);
+ s_width = sqxfw(ptsize, width);
+ if (width > 0 && height > 0) {
+ dvi_rule (s_width, sqxfw(ptsize, height));
+ }
+ dvi_right (s_width);
+ return;
+}
+
+static void vf_put1(unsigned char **start, unsigned char *end)
+{
+ dvi_put (unsigned_byte(start, end));
+ return;
+}
+
+static void vf_put2(unsigned char **start, unsigned char *end)
+{
+ dvi_put (unsigned_pair(start, end));
+ return;
+}
+
+static void vf_push(void)
+{
+ dvi_push();
+ return;
+}
+
+static void vf_pop(void)
+{
+ dvi_pop();
+ return;
+}
+
+static void vf_right (SIGNED_QUAD x, spt_t ptsize)
+{
+ dvi_right ((SIGNED_QUAD) (sqxfw(ptsize, x)));
+ return;
+}
+
+
+static void vf_right1(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_right (signed_byte (start, end), ptsize);
+ return;
+}
+
+static void vf_right2(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_right (signed_pair (start, end), ptsize);
+ return;
+}
+
+static void vf_right3(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_right (signed_triple (start, end), ptsize);
+ return;
+}
+
+static void vf_right4(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_right (signed_quad (start, end), ptsize);
+ return;
+}
+
+static void vf_w0(void)
+{
+ dvi_w0();
+ return;
+}
+
+static void vf_w (SIGNED_QUAD w, spt_t ptsize)
+{
+ dvi_w ((SIGNED_QUAD) (sqxfw(ptsize, w)));
+ return;
+}
+
+static void vf_w1(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_w (signed_byte(start, end), ptsize);
+ return;
+}
+
+static void vf_w2(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_w (signed_pair(start, end), ptsize);
+ return;
+}
+
+static void vf_w3(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_w (signed_triple(start, end), ptsize);
+ return;
+}
+
+static void vf_w4(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_w (signed_quad(start, end), ptsize);
+ return;
+}
+
+static void vf_x0(void)
+{
+ dvi_x0();
+ return;
+}
+
+static void vf_x (SIGNED_QUAD x, spt_t ptsize)
+{
+ dvi_x ((SIGNED_QUAD) (sqxfw(ptsize, x)));
+ return;
+}
+
+static void vf_x1(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_x (signed_byte(start, end), ptsize);
+ return;
+}
+
+static void vf_x2(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_x (signed_pair(start, end), ptsize);
+ return;
+}
+
+static void vf_x3(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_x (signed_triple(start, end), ptsize);
+ return;
+}
+
+static void vf_x4(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_x (signed_quad(start, end), ptsize);
+ return;
+}
+
+static void vf_down (SIGNED_QUAD y, spt_t ptsize)
+{
+ dvi_down ((SIGNED_QUAD) (sqxfw(ptsize, y)));
+ return;
+}
+
+static void vf_down1(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_down (signed_byte(start, end), ptsize);
+ return;
+}
+
+static void vf_down2(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_down (signed_pair(start, end), ptsize);
+ return;
+}
+
+static void vf_down3(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_down (signed_triple(start, end), ptsize);
+ return;
+}
+
+static void vf_down4(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_down (signed_quad(start, end), ptsize);
+ return;
+}
+
+static void vf_y0(void)
+{
+ dvi_y0();
+ return;
+}
+
+static void vf_y (SIGNED_QUAD y, spt_t ptsize)
+{
+ dvi_y ((SIGNED_QUAD) (sqxfw(ptsize, y)));
+ return;
+}
+
+
+static void vf_y1(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_y (signed_byte(start, end), ptsize);
+ return;
+}
+
+static void vf_y2(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_y (signed_pair(start, end), ptsize);
+ return;
+}
+
+static void vf_y3(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_y (signed_triple(start, end), ptsize);
+ return;
+}
+
+static void vf_y4(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_y (signed_quad(start, end), ptsize);
+ return;
+}
+
+static void vf_z0(void)
+{
+ dvi_z0();
+ return;
+}
+
+static void vf_z (SIGNED_QUAD z, spt_t ptsize)
+{
+ dvi_z ((SIGNED_QUAD) (sqxfw(ptsize, z)));
+ return;
+}
+
+static void vf_z1(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_z (signed_byte(start, end), ptsize);
+ return;
+}
+
+static void vf_z2(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_z (signed_pair(start, end), ptsize);
+ return;
+}
+
+static void vf_z3(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_z (signed_triple(start, end), ptsize);
+ return;
+}
+
+static void vf_z4(unsigned char **start, unsigned char *end, spt_t ptsize)
+{
+ vf_z (signed_quad(start, end), ptsize);
+ return;
+}
+
+static void vf_fnt (SIGNED_QUAD font_id, unsigned long vf_font)
+{
+ int i;
+ for (i=0; i<vf_fonts[vf_font].num_dev_fonts; i++) {
+ if (font_id == ((vf_fonts[vf_font].dev_fonts)[i]).font_id) {
+ break;
+ }
+ }
+ if (i < vf_fonts[vf_font].num_dev_fonts) { /* Font was found */
+ dvi_set_font ((vf_fonts[vf_font].dev_fonts[i]).dev_id);
+ } else {
+ fprintf (stderr, "Font_id: %ld not found in VF\n", font_id);
+ }
+ return;
+}
+
+static void vf_fnt1(unsigned char **start, unsigned char *end,
+ unsigned long vf_font)
+{
+ vf_fnt (unsigned_byte(start, end), vf_font);
+ return;
+}
+
+static void vf_fnt2(unsigned char **start, unsigned char *end,
+ unsigned long vf_font)
+{
+ vf_fnt (unsigned_pair(start, end), vf_font);
+ return;
+}
+
+static void vf_fnt3(unsigned char **start, unsigned char *end,
+ unsigned long vf_font)
+{
+ vf_fnt (unsigned_triple(start, end), vf_font);
+ return;
+}
+
+static void vf_fnt4(unsigned char **start, unsigned char *end,
+ unsigned long vf_font)
+{
+ vf_fnt (signed_quad(start, end), vf_font);
+ return;
+}
+
+/* identical to do_xxx in dvi.c */
+static void vf_xxx (SIGNED_QUAD len, unsigned char **start, unsigned char *end)
+{
+ Ubyte *buffer;
+
+ if (*start <= end - len) {
+ buffer = NEW(len+1, Ubyte);
+ memcpy(buffer, *start, len);
+ buffer[len] = '\0';
+ {
+ Ubyte *p = buffer;
+
+ while (p < buffer+len && *p == ' ') p++;
+ /*
+ * Warning message from virtual font.
+ */
+ if (!memcmp((char *)p, "Warning:", 8)) {
+ if (verbose)
+ WARN("VF:%s", p+8);
+ } else {
+ dvi_do_special(buffer, len);
+ }
+ }
+ RELEASE(buffer);
+ } else {
+ ERROR ("Premature end of DVI byte stream in VF font.");
+ }
+
+ *start += len;
+ return;
+}
+
+static void vf_xxx1(unsigned char **start, unsigned char *end)
+{
+ vf_xxx (unsigned_byte(start, end), start, end);
+ return;
+}
+
+static void vf_xxx2(unsigned char **start, unsigned char *end)
+{
+ vf_xxx (unsigned_pair(start, end), start, end);
+ return;
+}
+
+static void vf_xxx3(unsigned char **start, unsigned char *end)
+{
+ vf_xxx (unsigned_triple(start, end), start, end);
+ return;
+}
+
+static void vf_xxx4(unsigned char **start, unsigned char *end)
+{
+ vf_xxx (unsigned_quad(start, end), start, end);
+ return;
+}
+
+static void vf_dir(unsigned char **start, unsigned char *end)
+{
+ dvi_dir (unsigned_byte(start, end));
+ return;
+}
+
+void vf_set_char(SIGNED_QUAD ch, int vf_font)
+{
+ unsigned char opcode;
+ unsigned char *start, *end;
+ spt_t ptsize;
+ int default_font = -1;
+ if (vf_font < num_vf_fonts) {
+ /* Initialize to the first font or -1 if undefined */
+ ptsize = vf_fonts[vf_font].ptsize;
+ if (vf_fonts[vf_font].num_dev_fonts > 0)
+ default_font = ((vf_fonts[vf_font].dev_fonts)[0]).dev_id;
+ dvi_vf_init (default_font);
+ if (ch >= vf_fonts[vf_font].num_chars ||
+ !(start = (vf_fonts[vf_font].ch_pkt)[ch])) {
+ fprintf (stderr, "\nchar=0x%lx(%ld)\n", ch, ch);
+ fprintf (stderr, "Tried to set a nonexistent character in a virtual font");
+ start = end = NULL;
+ } else {
+ end = start + (vf_fonts[vf_font].pkt_len)[ch];
+ }
+ while (start && start < end) {
+ opcode = *(start++);
+#ifdef DEBUG
+ fprintf (stderr, "VF opcode: %d", opcode);
+ if (isprint (opcode)) fprintf (stderr, " (\'%c\')\n", opcode);
+ else fprintf (stderr, "\n");
+#endif
+ switch (opcode)
+ {
+ case SET1:
+ vf_set1(&start, end);
+ break;
+ case SET2:
+ vf_set2(&start, end);
+ break;
+ case SET3:
+ case SET4:
+ ERROR ("Multibyte (>16 bits) character in VF packet.\nI can't handle this!");
+ break;
+ case SET_RULE:
+ vf_setrule(&start, end, ptsize);
+ break;
+ case PUT1:
+ vf_put1(&start, end);
+ break;
+ case PUT2:
+ vf_put2(&start, end);
+ break;
+ case PUT3:
+ case PUT4:
+ ERROR ("Multibyte (>16 bits) character in VF packet.\nI can't handle this!");
+ break;
+ case PUT_RULE:
+ vf_putrule(&start, end, ptsize);
+ break;
+ case NOP:
+ break;
+ case PUSH:
+ vf_push();
+ break;
+ case POP:
+ vf_pop();
+ break;
+ case RIGHT1:
+ vf_right1(&start, end, ptsize);
+ break;
+ case RIGHT2:
+ vf_right2(&start, end, ptsize);
+ break;
+ case RIGHT3:
+ vf_right3(&start, end, ptsize);
+ break;
+ case RIGHT4:
+ vf_right4(&start, end, ptsize);
+ break;
+ case W0:
+ vf_w0();
+ break;
+ case W1:
+ vf_w1(&start, end, ptsize);
+ break;
+ case W2:
+ vf_w2(&start, end, ptsize);
+ break;
+ case W3:
+ vf_w3(&start, end, ptsize);
+ break;
+ case W4:
+ vf_w4(&start, end, ptsize);
+ break;
+ case X0:
+ vf_x0();
+ break;
+ case X1:
+ vf_x1(&start, end, ptsize);
+ break;
+ case X2:
+ vf_x2(&start, end, ptsize);
+ break;
+ case X3:
+ vf_x3(&start, end, ptsize);
+ break;
+ case X4:
+ vf_x4(&start, end, ptsize);
+ break;
+ case DOWN1:
+ vf_down1(&start, end, ptsize);
+ break;
+ case DOWN2:
+ vf_down2(&start, end, ptsize);
+ break;
+ case DOWN3:
+ vf_down3(&start, end, ptsize);
+ break;
+ case DOWN4:
+ vf_down4(&start, end, ptsize);
+ break;
+ case Y0:
+ vf_y0();
+ break;
+ case Y1:
+ vf_y1(&start, end, ptsize);
+ break;
+ case Y2:
+ vf_y2(&start, end, ptsize);
+ break;
+ case Y3:
+ vf_y3(&start, end, ptsize);
+ break;
+ case Y4:
+ vf_y4(&start, end, ptsize);
+ break;
+ case Z0:
+ vf_z0();
+ break;
+ case Z1:
+ vf_z1(&start, end, ptsize);
+ break;
+ case Z2:
+ vf_z2(&start, end, ptsize);
+ break;
+ case Z3:
+ vf_z3(&start, end, ptsize);
+ break;
+ case Z4:
+ vf_z4(&start, end, ptsize);
+ break;
+ case FNT1:
+ vf_fnt1(&start, end, vf_font);
+ break;
+ case FNT2:
+ vf_fnt2(&start, end, vf_font);
+ break;
+ case FNT3:
+ vf_fnt3(&start, end, vf_font);
+ break;
+ case FNT4:
+ vf_fnt4(&start, end, vf_font);
+ break;
+ case XXX1:
+ vf_xxx1(&start, end);
+ break;
+ case XXX2:
+ vf_xxx2(&start, end);
+ break;
+ case XXX3:
+ vf_xxx3(&start, end);
+ break;
+ case XXX4:
+ vf_xxx4(&start, end);
+ break;
+ case PTEXDIR:
+ vf_dir(&start, end);
+ break;
+ default:
+ if (opcode <= SET_CHAR_127) {
+ vf_set (opcode);
+ } else if (opcode >= FNT_NUM_0 && opcode <= FNT_NUM_63) {
+ vf_fnt (opcode - FNT_NUM_0, vf_font);
+ } else {
+ fprintf (stderr, "Unexpected opcode: %d\n", opcode);
+ ERROR ("Unexpected opcode in vf file\n");
+ }
+ }
+ }
+ dvi_vf_finish();
+ } else {
+ fprintf (stderr, "vf_set_char: font: %d", vf_font);
+ ERROR ("Font not loaded\n");
+ }
+ return;
+}
+
+
+void vf_close_all_fonts(void)
+{
+ unsigned long i;
+ int j;
+ struct font_def *one_font;
+ for (i=0; i<num_vf_fonts; i++) {
+ /* Release the packet for each character */
+ if (vf_fonts[i].ch_pkt) {
+ for (j=0; j<vf_fonts[i].num_chars; j++) {
+ if ((vf_fonts[i].ch_pkt)[j] != NULL)
+ RELEASE ((vf_fonts[i].ch_pkt)[j]);
+ }
+ RELEASE (vf_fonts[i].ch_pkt);
+ }
+ if (vf_fonts[i].pkt_len)
+ RELEASE (vf_fonts[i].pkt_len);
+ if (vf_fonts[i].tex_name)
+ RELEASE (vf_fonts[i].tex_name);
+ /* Release each font record */
+ for (j=0; j<vf_fonts[i].num_dev_fonts; j++) {
+ one_font = &(vf_fonts[i].dev_fonts)[j];
+ RELEASE (one_font -> directory);
+ RELEASE (one_font -> name);
+ }
+ if (vf_fonts[i].dev_fonts != NULL)
+ RELEASE (vf_fonts[i].dev_fonts);
+ }
+ if (vf_fonts != NULL)
+ RELEASE (vf_fonts);
+ return;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/xbb.c b/Build/source/texk/dvipdf-x/xsrc/xbb.c
new file mode 100644
index 00000000000..f447d3a0170
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/xbb.c
@@ -0,0 +1,511 @@
+/*
+
+ This is extractbb, a bounding box extraction program.
+
+ Copyright (C) 2008-2012 by Jin-Hwan Cho <chofchof@ktug.or.kr>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+*/
+#include <stdio.h>
+#include <time.h>
+#include <string.h>
+#include "system.h"
+#include "mem.h"
+#include "error.h"
+#include "mfileio.h"
+#include "numbers.h"
+#include "pdfobj.h"
+#include "pdfparse.h"
+
+#include "config.h"
+
+#ifdef HAVE_LIBPNG
+#include <png.h>
+#endif
+
+#include "xbb.h"
+
+#define XBB_PROGRAM "extractbb"
+#define XBB_VERSION "Version 0.2"
+
+static int xbb_output_mode = XBB_OUTPUT;
+
+static void usage(void)
+{
+ fprintf (stderr, "%s, version %s, Copyright (C) 2008 by Jin-Hwan Cho\n",
+ XBB_PROGRAM, XBB_VERSION);
+ fprintf (stderr, "A bounding box extraction utility from PDF, PNG, and JPG.\n");
+ fprintf (stdout, "\nThis is free software; you can redistribute it and/or modify\n");
+ fprintf (stdout, "it under the terms of the GNU General Public License as published by\n");
+ fprintf (stdout, "the Free Software Foundation; either version 2 of the License, or\n");
+ fprintf (stdout, "(at your option) any later version.\n");
+ fprintf (stderr, "\nUsage: %s [-v] [-b] [-m|-x] [files]\n", XBB_PROGRAM);
+ fprintf (stderr, "\t-b\tWrite output file in binary mode\n");
+ if(xbb_output_mode == EBB_OUTPUT) {
+ fprintf (stderr, "\t-m\tOutput .bb file used in DVIPDFM (default)\n");
+ fprintf (stderr, "\t-x\tOutput .xbb file used in DVIPDFMx\n");
+ } else {
+ fprintf (stderr, "\t-m\tOutput .bb file used in DVIPDFM\n");
+ fprintf (stderr, "\t-x\tOutput .xbb file used in DVIPDFMx (default)\n");
+ }
+ fprintf (stderr, "\t-v\tVerbose\n");
+ exit(1);
+}
+
+static char verbose = 0;
+
+static void do_time(FILE *file)
+{
+ time_t current_time;
+ struct tm *bd_time;
+
+ time(&current_time);
+ bd_time = localtime(&current_time);
+ fprintf(file, "%%%%CreationDate: %s\n", asctime(bd_time));
+}
+
+const char *extensions[] = {
+ ".jpeg", ".JPEG", ".jpg", ".JPG", ".pdf", ".PDF", ".png", ".PNG"
+};
+
+static char *make_xbb_filename(const char *name)
+{
+ int i;
+ char *result;
+
+ for (i = 0; i < sizeof(extensions) / sizeof(extensions[0]); i++) {
+ if (strlen(extensions[i]) < strlen(name) &&
+ strncmp(name+strlen(name)-strlen(extensions[i]), extensions[i], strlen(extensions[i])) == 0)
+ break;
+ }
+ if (i == sizeof(extensions) / sizeof(extensions[0])) {
+ fprintf(stderr, "Warning: %s: Filename does not end in a recognizeable extension.\n", name);
+ result = NEW(strlen(name)+3, char);
+ strcpy(result, name);
+ } else { /* Remove extension */
+ result = NEW(strlen(name)+3-strlen(extensions[i])+1, char);
+ strncpy(result, name, strlen(name)-strlen(extensions[i]));
+ result[strlen(name)-strlen(extensions[i])] = 0;
+ }
+ strcat(result, (xbb_output_mode == XBB_OUTPUT ? ".xbb" : ".bb"));
+ return result;
+}
+
+static const char *xbb_file_mode = FOPEN_W_MODE;
+
+static void write_xbb(char *fname, int bbllx, int bblly, int bburx, int bbury)
+{
+ char *outname;
+ FILE *fp;
+
+ outname = make_xbb_filename(fname);
+ if ((fp = MFOPEN(outname, xbb_file_mode)) == NULL) {
+ fprintf(stderr, "Unable to open output file: %s\n", outname);
+ RELEASE(outname);
+ return;
+ }
+ if (verbose) {
+ fprintf(stderr, "Writing to %s: ", outname);
+ fprintf(stderr, "Bounding box: %d %d %d %d\n", bbllx, bblly, bburx, bbury);
+ }
+ fprintf(fp,"%%%%Title: %s\n", fname);
+ fprintf(fp,"%%%%Creator: %s %s\n", XBB_PROGRAM, XBB_VERSION);
+ fprintf(fp,"%%%%BoundingBox: %d %d %d %d\n", bbllx, bblly, bburx, bbury);
+ do_time(fp);
+ RELEASE(outname);
+ MFCLOSE(fp);
+}
+
+typedef enum {
+ JM_SOF0 = 0xc0, JM_SOF1 = 0xc1, JM_SOF2 = 0xc2, JM_SOF3 = 0xc3,
+ JM_SOF5 = 0xc5, JM_DHT = 0xc4, JM_SOF6 = 0xc6, JM_SOF7 = 0xc7,
+ JM_SOF9 = 0xc9, JM_SOF10 = 0xca, JM_SOF11 = 0xcb, JM_DAC = 0xcc,
+ JM_SOF13 = 0xcd, JM_SOF14 = 0xce, JM_SOF15 = 0xcf,
+
+ JM_RST0 = 0xd0, JM_RST1 = 0xd1, JM_RST2 = 0xd2, JM_RST3 = 0xd3,
+ JM_RST4 = 0xd4, JM_RST5 = 0xd5, JM_RST6 = 0xd6, JM_RST7 = 0xd7,
+
+ JM_SOI = 0xd8, JM_EOI = 0xd9, JM_SOS = 0xda, JM_DQT = 0xdb,
+ JM_DNL = 0xdc, JM_DRI = 0xdd, JM_DHP = 0xde, JM_EXP = 0xdf,
+
+ JM_APP0 = 0xe0, JM_APP2 = 0xe2, JM_APP14 = 0xee, JM_APP15 = 0xef,
+
+ JM_COM = 0xfe
+} JPEG_marker;
+
+static JPEG_marker JPEG_get_marker (FILE *fp)
+{
+ int c = fgetc(fp);
+ if (c != 255) return -1;
+ for (;;) {
+ c = fgetc(fp);
+ if (c < 0) return -1;
+ else if (c > 0 && c < 255) return c;
+ }
+ return -1;
+}
+
+static int check_for_jpeg (FILE *fp)
+{
+ unsigned char jpeg_sig[2];
+ rewind(fp);
+ if (fread(jpeg_sig, sizeof(unsigned char), 2, fp) != 2) return 0;
+ else if (jpeg_sig[0] != 0xff || jpeg_sig[1] != JM_SOI) return 0;
+ return 1;
+}
+
+static int jpeg_get_info (FILE *fp, int *width, int *height)
+{
+ JPEG_marker marker;
+ unsigned short length;
+ int count;
+ float xdensity = 1.0, ydensity = 1.0;
+ char app_sig[128];
+
+ if (!check_for_jpeg(fp)) {
+ rewind(fp);
+ return -1;
+ }
+ rewind(fp);
+ count = 0;
+ while ((marker = JPEG_get_marker(fp)) >= 0) {
+ if (marker == JM_SOI || (marker >= JM_RST0 && marker <= JM_RST7)) {
+ count++; continue;
+ }
+ length = get_unsigned_pair(fp) - 2;
+ switch (marker) {
+ case JM_SOF0: case JM_SOF1: case JM_SOF2: case JM_SOF3:
+ case JM_SOF5: case JM_SOF6: case JM_SOF7: case JM_SOF9:
+ case JM_SOF10: case JM_SOF11: case JM_SOF13: case JM_SOF14:
+ case JM_SOF15:
+ get_unsigned_byte(fp);
+ if (xbb_output_mode != XBB_OUTPUT) { /* EBB_OUTPUT */
+ xdensity = ydensity = 72.0 / 100.0;
+ }
+ *height = (int)(get_unsigned_pair(fp) * ydensity + 0.5);
+ *width = (int)(get_unsigned_pair(fp) * xdensity + 0.5);
+ return 0;
+ case JM_APP0:
+ if (length > 5) {
+ if (fread(app_sig, sizeof(char), 5, fp) != 5) return -1;
+ length -= 5;
+ if (!memcmp(app_sig, "JFIF\000", 5)) {
+ int units, xden, yden;
+ get_unsigned_pair(fp);
+ units = (int)get_unsigned_byte(fp);
+ xden = (int)get_unsigned_pair(fp);
+ yden = (int)get_unsigned_pair(fp);
+ switch (units) {
+ case 1: /* pixels per inch */
+ xdensity = 72.0 / xden;
+ ydensity = 72.0 / yden;
+ break;
+ case 2: /* pixels per centimeter */
+ xdensity = 72.0 / 2.54 / xden;
+ ydensity = 72.0 / 2.54 / yden;
+ break;
+ default:
+ break;
+ }
+ length -= 7;
+ }
+ }
+ seek_relative(fp, length);
+ break;
+ default:
+ seek_relative(fp, length);
+ break;
+ }
+ count++;
+ }
+ return -1;
+}
+
+static void do_jpeg (FILE *fp, char *filename)
+{
+ int width, height;
+
+ if (jpeg_get_info(fp, &width, &height) < 0) {
+ fprintf (stderr, "%s does not look like a JPEG file...\n", filename);
+ return;
+ }
+ write_xbb(filename, 0, 0, width, height);
+ return;
+}
+
+#ifdef HAVE_LIBPNG
+static int check_for_png (FILE *png_file)
+{
+ unsigned char sigbytes[4];
+ rewind (png_file);
+ if (fread(sigbytes, 1, sizeof(sigbytes), png_file) != sizeof(sigbytes) ||
+ (png_sig_cmp (sigbytes, 0, sizeof(sigbytes)))) return 0;
+ else return 1;
+}
+
+static int png_get_info(FILE *png_file, int *width, int *height)
+{
+ png_structp png_ptr;
+ png_infop png_info_ptr;
+ png_uint_32 xppm, yppm;
+
+ rewind(png_file);
+
+ png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+ if (png_ptr == NULL || (png_info_ptr = png_create_info_struct(png_ptr)) == NULL) {
+ if (png_ptr) png_destroy_read_struct(&png_ptr, NULL, NULL);
+ return -1;
+ }
+ png_init_io(png_ptr, png_file);
+ png_read_info(png_ptr, png_info_ptr);
+
+ *width = (int)png_get_image_width(png_ptr, png_info_ptr);
+ *height = (int)png_get_image_height(png_ptr, png_info_ptr);
+
+ if (xbb_output_mode == XBB_OUTPUT) {
+ xppm = png_get_x_pixels_per_meter(png_ptr, png_info_ptr);
+ yppm = png_get_y_pixels_per_meter(png_ptr, png_info_ptr);
+ if (xppm > 0)
+ *width = (int)(*width * 72.0 / 0.0254 / xppm + 0.5);
+ if (yppm > 0)
+ *height = (int)(*height * 72.0 / 0.0254 / yppm + 0.5);
+ } else { /* EBB_OUTPUT */
+ *width = (int)(*width * 72.0 / 100.0 + 0.5);
+ *height = (int)(*height * 72.0 / 100.0 + 0.5);
+ }
+ return 0;
+}
+
+static void do_png (FILE *fp, char *filename)
+{
+ int width, height;
+
+ if (png_get_info(fp, &width, &height) < 0) {
+ fprintf (stderr, "%s does not look like a PNG file...\n", filename);
+ return;
+ }
+ write_xbb(filename, 0, 0, width, height);
+ return;
+}
+#endif /* HAVE_LIBPNG */
+
+static int rect_equal (pdf_obj *rect1, pdf_obj *rect2)
+{
+ int i;
+ if (!rect1 || !rect2) return 0;
+ for (i = 0; i < 4; i++) {
+ if (pdf_number_value(pdf_get_array(rect1, i)) != pdf_number_value(pdf_get_array(rect2, i))) return 0;
+ }
+ return 1;
+}
+
+static int pdf_get_info (FILE *image_file, char *filename, int *llx, int *lly, int *urx, int *ury)
+{
+ pdf_obj *page_tree;
+ pdf_obj *bbox;
+ pdf_file *pf;
+
+ page_tree = NULL;
+ {
+ pdf_obj *trailer, *catalog;
+
+ pf = pdf_open(filename, image_file);
+ if (!pf)
+ return -1;
+
+ trailer = pdf_file_get_trailer(pf);
+
+ if (pdf_lookup_dict(trailer, "Encrypt")) {
+ WARN("This PDF document is encrypted.");
+ pdf_release_obj(trailer);
+ pdf_close(pf);
+ return -1;
+ }
+ catalog = pdf_deref_obj(pdf_lookup_dict(trailer, "Root"));
+ if (!catalog) {
+ WARN("Catalog isn't where I expect it.");
+ pdf_close(pf);
+ return -1;
+ }
+ pdf_release_obj(trailer);
+ page_tree = pdf_deref_obj(pdf_lookup_dict(catalog, "Pages"));
+ pdf_release_obj(catalog);
+ }
+ if (!page_tree) {
+ WARN("Page tree not found.");
+ pdf_close(pf);
+ return -1;
+ }
+ {
+ pdf_obj *kids_ref, *kids;
+ pdf_obj *crop_box;
+ pdf_obj *tmp;
+
+ tmp = pdf_lookup_dict(page_tree, "MediaBox");
+ bbox = tmp ? pdf_deref_obj(tmp) : NULL;
+ tmp = pdf_lookup_dict(page_tree, "CropBox");
+ crop_box = tmp ? pdf_deref_obj(tmp) : NULL;
+
+ while ((kids_ref = pdf_lookup_dict(page_tree, "Kids")) != NULL) {
+ kids = pdf_deref_obj(kids_ref);
+ pdf_release_obj(page_tree);
+ page_tree = pdf_deref_obj(pdf_get_array(kids, 0));
+ pdf_release_obj(kids);
+
+ if ((tmp = pdf_deref_obj(pdf_lookup_dict(page_tree, "MediaBox")))) {
+ if (bbox)
+ pdf_release_obj(bbox);
+ bbox = tmp;
+ }
+ if ((tmp = pdf_deref_obj(pdf_lookup_dict(page_tree, "BleedBox")))) {
+ if (!rect_equal(tmp, bbox)) {
+ if (bbox)
+ pdf_release_obj(bbox);
+ bbox = tmp;
+ } else
+ pdf_release_obj(tmp);
+ }
+ if ((tmp = pdf_deref_obj(pdf_lookup_dict(page_tree, "TrimBox")))) {
+ if (!rect_equal(tmp, bbox)) {
+ if (bbox)
+ pdf_release_obj(bbox);
+ bbox = tmp;
+ } else
+ pdf_release_obj(tmp);
+ }
+ if ((tmp = pdf_deref_obj(pdf_lookup_dict(page_tree, "ArtBox")))) {
+ if (!rect_equal(tmp, bbox)) {
+ if (bbox)
+ pdf_release_obj(bbox);
+ bbox = tmp;
+ } else
+ pdf_release_obj(tmp);
+ }
+ if ((tmp = pdf_deref_obj(pdf_lookup_dict(page_tree, "CropBox")))) {
+ if (crop_box)
+ pdf_release_obj(crop_box);
+ crop_box = tmp;
+ }
+ }
+ if (crop_box) {
+ pdf_release_obj(bbox);
+ bbox = crop_box;
+ }
+ }
+ pdf_release_obj(page_tree);
+
+ if (!bbox) {
+ WARN("No BoundingBox information available.");
+ pdf_close(pf);
+ return -1;
+ }
+
+ *llx = (int)pdf_number_value(pdf_get_array(bbox, 0));
+ *lly = (int)pdf_number_value(pdf_get_array(bbox, 1));
+ *urx = (int)pdf_number_value(pdf_get_array(bbox, 2));
+ *ury = (int)pdf_number_value(pdf_get_array(bbox, 3));
+
+ pdf_release_obj(bbox);
+
+ pdf_close(pf);
+ return 0;
+}
+
+static void do_pdf (FILE *fp, char *filename)
+{
+ int llx, lly, urx, ury;
+
+ if (pdf_get_info(fp, filename, &llx, &lly, &urx, &ury) < 0) {
+ fprintf (stderr, "%s does not look like a PDF file...\n", filename);
+ return;
+ }
+ write_xbb(filename, llx, lly, urx, ury);
+ return;
+}
+
+int extractbb (int argc, char *argv[], int mode)
+{
+ xbb_output_mode = mode;
+
+ pdf_files_init();
+
+ pdf_set_version(5);
+
+ kpse_set_program_name(argv[0], NULL);
+
+ argc -= 1; argv += 1;
+ if (argc == 0)
+ usage();
+
+ while (argc > 0 && *argv[0] == '-') {
+ switch (*(argv[0]+1)) {
+ case 'b':
+ xbb_file_mode = FOPEN_WBIN_MODE;
+ argc -= 1; argv += 1;
+ break;
+ case 'm':
+ xbb_output_mode = EBB_OUTPUT;
+ argc -= 1; argv += 1;
+ break;
+ case 'x':
+ xbb_output_mode = XBB_OUTPUT;
+ argc -= 1; argv += 1;
+ break;
+ case 'v':
+ verbose = 1;
+ argc -= 1; argv += 1;
+ break;
+ case 'h':
+ usage();
+ argc -= 1; argv += 1;
+ break;
+ default:
+ usage();
+ }
+ }
+ for (; argc > 0; argc--, argv++) {
+ FILE *infile = NULL;
+ char *kpse_file_name;
+ if (!(kpse_file_name = kpse_find_pict(argv[0])) ||
+ (infile = MFOPEN(kpse_file_name, FOPEN_RBIN_MODE)) == NULL) {
+ fprintf(stderr, "Can't find file (%s)...skipping\n", argv[0]);
+ goto cont;
+ }
+ if (check_for_jpeg(infile)) {
+ do_jpeg(infile, kpse_file_name);
+ goto cont;
+ }
+ if (check_for_pdf(infile)) {
+ do_pdf(infile, kpse_file_name);
+ goto cont;
+ }
+#ifdef HAVE_LIBPNG
+ if (check_for_png(infile)) {
+ do_png(infile, kpse_file_name);
+ goto cont;
+ }
+#endif /* HAVE_LIBPNG */
+ fprintf(stderr, "Can't handle file type for file named %s\n", argv[0]);
+ cont:
+ if (kpse_file_name)
+ RELEASE(kpse_file_name);
+ if (infile)
+ MFCLOSE(infile);
+ }
+
+ pdf_files_close();
+
+ return 0;
+}
diff --git a/Build/source/texk/dvipdf-x/xsrc/xbb.h b/Build/source/texk/dvipdf-x/xsrc/xbb.h
new file mode 100644
index 00000000000..5c8e25c1fd8
--- /dev/null
+++ b/Build/source/texk/dvipdf-x/xsrc/xbb.h
@@ -0,0 +1,31 @@
+/*
+
+ This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks.
+
+ Copyright (C) 2008-2012 by Jin-Hwan Cho, Matthias Franz, and Shunsaku Hirata,
+ the dvipdfmx project team.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+*/
+
+#ifndef _XBB_H_
+#define _XBB_H_
+
+#define EBB_OUTPUT 0
+#define XBB_OUTPUT 1
+
+extern int extractbb(int argc, char *argv[], int mode);
+
+#endif /* _XBB_H_ */