feat: рантайм без fontconfig — глиф-движок GlyphFont (fontbox) вместо java.awt.Font
На OpenJDK/Linux любое обращение к java.awt.Font требует fontconfig-нативки (Fontconfig head is null на хосте без libfontconfig). java.awt.Font убран из всего рантайм-пути: текст chart-движка (DrawMlText) и проверка покрытия глифов (GlyphCoverageNormalizer) переведены на GlyphFont — чистый Java-парсер TTF org.apache.pdfbox:fontbox 3.0.8 (compile; commons-logging исключён, единственный провайдер jcl-over-slf4j). Метрики совпадают с AWT до 4-го знака, кернинг-дрейф 0.0000 (DejaVu Sans, Carlito). AWT остаётся только как геометрия (Graphics2D/Path2D), которая fontconfig не требует. - GlyphFont: of/canDisplay/advance/ascent/descent/leading/draw; TTF читается напрямую из classpath, не зависит от BundledFonts.init(); битый бандл падает IllegalStateException, отсутствующее семейство/начертание -> null - DrawMlText.fontFor: цепочка фолбэка family/variant -> family/regular -> fallback/variant -> fallback/regular (bold у Noto остаётся своим regular) - BundledFonts: awtFont/AWT_FONTS удалены (чистый cutover), CLASSPATH_DIR -> package-private - ChartRenderer.measureLegend: убран неиспользуемый после cutover параметр g (PMD) - GlyphFontTest (6 юнитов) без единого java.awt.Font — обязан проходить на хосте без fontconfig; Containerfile/AGENTS.md: fontconfig рантайму не нужен Проверено: mvn clean verify локально (153 теста, PMD); приёмочный стенд — контейнер без libfontconfig.so и /etc/fonts: mvn verify BUILD SUCCESS и java -jar + конвертация charts-smartart.docx -> PDF 466 КБ с 4 растрами (деградации нет).
This commit is contained in:
@@ -36,6 +36,19 @@
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
</dependency>
|
||||
<!-- Чистый Java-парсер TTF (глиф-движок GlyphFont): метрики и
|
||||
отрисовка глифов без java.awt.Font — рантайму не нужен
|
||||
fontconfig (OpenJDK/Linux требует его при любом обращении
|
||||
к java.awt.Font). -->
|
||||
<dependency>
|
||||
<groupId>org.apache.pdfbox</groupId>
|
||||
<artifactId>fontbox</artifactId>
|
||||
</dependency>
|
||||
<!-- Мост commons-logging -> slf4j для fontbox -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- ============ Тесты ============ -->
|
||||
<dependency>
|
||||
|
||||
@@ -49,8 +49,9 @@ public final class BundledFonts {
|
||||
*/
|
||||
public static final String FALLBACK_FAMILY = "dejavu sans";
|
||||
|
||||
/** Каталог с TTF внутри jar (classpath). */
|
||||
private static final String CLASSPATH_DIR = "fonts";
|
||||
/** Каталог с TTF внутри jar (classpath). Package-private: доступ
|
||||
* для {@link GlyphFont} (читает TTF напрямую из classpath). */
|
||||
static final String CLASSPATH_DIR = "fonts";
|
||||
|
||||
/** Описание одного файла: имя в jar, ключ семейства, начертание.
|
||||
* Package-private: доступ для теста. */
|
||||
@@ -110,9 +111,6 @@ public final class BundledFonts {
|
||||
/** Ключ семейства (lowercase) -> начертание -> зарегистрированный PhysicalFont. */
|
||||
private static final Map<String, Map<String, PhysicalFont>> VARIANTS = new HashMap<>();
|
||||
|
||||
/** Ключ family/variant -> java.awt.Font (кэш, см. {@link #awtFont}). */
|
||||
private static final Map<String, java.awt.Font> AWT_FONTS = new HashMap<>();
|
||||
|
||||
/** Каталог, куда выгружены TTF (после init()). */
|
||||
private static Path extractDir;
|
||||
private static boolean inited = false;
|
||||
@@ -252,30 +250,4 @@ public final class BundledFonts {
|
||||
return font(family, V_BOLD_ITALIC);
|
||||
}
|
||||
|
||||
/**
|
||||
* Тот же TTF, но как {@link java.awt.Font} для Java2D (пре-рендер
|
||||
* диаграмм и SmartArt в растр, см. internal/chart). Шрифт читается
|
||||
* из выгруженного файла один раз и кешируется.
|
||||
*
|
||||
* @return базовый Font размера 1 (далее {@code deriveFont(size)}),
|
||||
* или null, если шрифт не найден / {@link #init()} не вызван
|
||||
*/
|
||||
public static synchronized java.awt.Font awtFont(String family, String variant) {
|
||||
String key = family + "/" + variant;
|
||||
java.awt.Font cached = AWT_FONTS.get(key);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
PhysicalFont pf = font(family, variant);
|
||||
if (pf == null || pf.getEmbeddedURI() == null) {
|
||||
return null;
|
||||
}
|
||||
try (InputStream in = Files.newInputStream(Path.of(pf.getEmbeddedURI()))) {
|
||||
java.awt.Font f = java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, in);
|
||||
AWT_FONTS.put(key, f);
|
||||
return f;
|
||||
} catch (IOException | java.awt.FontFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
package ru.pjandro.wordpdf.fonts;
|
||||
|
||||
import org.apache.fontbox.ttf.CmapLookup;
|
||||
import org.apache.fontbox.ttf.GlyphData;
|
||||
import org.apache.fontbox.ttf.HorizontalHeaderTable;
|
||||
import org.apache.fontbox.ttf.TTFParser;
|
||||
import org.apache.fontbox.ttf.TrueTypeFont;
|
||||
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.geom.AffineTransform;
|
||||
import java.awt.geom.GeneralPath;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Глиф-движок бандл-шрифтов: метрики и отрисовка глифов через чистый
|
||||
* Java-парсер TTF (fontbox), без {@link java.awt.Font}.
|
||||
*
|
||||
* Почему: на OpenJDK/Linux любое обращение к {@code java.awt.Font}
|
||||
* (включая {@code Font.createFont} и {@code TextLayout}) инициализирует
|
||||
* {@code SunFontManager}, которому нужны fontconfig-нативки и хотя бы
|
||||
* один системный шрифт — на хосте без libfontconfig это
|
||||
* {@code RuntimeException: Fontconfig head is null}. Метрики fontbox
|
||||
* совпадают с AWT до 4-го знака (ascent/descent/leading/advance,
|
||||
* кернинг-дрейф 0.0000 — DejaVu Sans, Carlito). Приёмочный стенд —
|
||||
* контейнер без libfontconfig и /etc/fonts (см. GlyphFontTest, там же
|
||||
* регрессия «тест обязан проходить без fontconfig»).
|
||||
*
|
||||
* AWT остаётся только как геометрия (Graphics2D/Path2D/AffineTransform):
|
||||
* она fontconfig не требует. Растеризация глифов — контуры
|
||||
* {@link GlyphData#getPath()} + {@link Graphics2D#fill}.
|
||||
*
|
||||
* Объект безразмерный: размер в pt передаётся в каждый метод явно
|
||||
* (в отличие от AWT, где размер живёт в объекте Font). Шрифт читается
|
||||
* напрямую из classpath ({@code fonts/<file>}), а не из временного
|
||||
* каталога {@link BundledFonts#init()} — поэтому класс не зависит от
|
||||
* порядка шагов конвертации. TTF буферизуется в памяти и живёт до конца
|
||||
* JVM (шрифты бандла конечны, {@link TrueTypeFont} намеренно не закрываем).
|
||||
*/
|
||||
public final class GlyphFont {
|
||||
|
||||
/** Кэш распарсенных шрифтов: ключ — {@code family/variant}. */
|
||||
private static final Map<String, GlyphFont> CACHE = new HashMap<>();
|
||||
|
||||
private final String key;
|
||||
private final TrueTypeFont ttf;
|
||||
private CmapLookup cmap;
|
||||
|
||||
private GlyphFont(String key, TrueTypeFont ttf) {
|
||||
this.key = key;
|
||||
this.ttf = ttf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Шрифт бандла по семейству (lowercase-ключ) и начертанию.
|
||||
*
|
||||
* @return шрифт или {@code null}, если семейства/начертания нет
|
||||
* в бандле (нормальный случай: запрашивающий сделает фолбэк).
|
||||
* {@code null} не кэшируется — повторный вызов дёшев.
|
||||
* @throws IllegalStateException битый бандл: TTF из jar не читается.
|
||||
* Падаем громко, а не «null» — null означал бы «всё непокрыто»
|
||||
* и портил бы разбиение ранов.
|
||||
*/
|
||||
public static synchronized GlyphFont of(String family, String variant) {
|
||||
String key = family + "/" + variant;
|
||||
GlyphFont cached = CACHE.get(key);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
for (BundledFonts.Entry e : BundledFonts.ENTRIES) {
|
||||
if (e.family().equals(family) && e.variant().equals(variant)) {
|
||||
GlyphFont f = load(key, e.file());
|
||||
CACHE.put(key, f);
|
||||
return f;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static GlyphFont load(String key, String file) {
|
||||
String path = BundledFonts.CLASSPATH_DIR + "/" + file;
|
||||
try (InputStream in = GlyphFont.class.getClassLoader().getResourceAsStream(path)) {
|
||||
if (in == null) {
|
||||
throw new IllegalStateException(
|
||||
"Не удалось загрузить шрифт бандла: " + path + " (нет в classpath)");
|
||||
}
|
||||
return new GlyphFont(key, new TTFParser().parseEmbedded(in));
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException(
|
||||
"Не удалось загрузить шрифт бандла: " + path, e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Есть ли глиф для кодовой точки (gid 0 = .notdef → нет). */
|
||||
public boolean canDisplay(int cp) {
|
||||
return cmap().getGlyphId(cp) != 0;
|
||||
}
|
||||
|
||||
/** Ширина строки в pt: сумма ширин глифов по кодовым точкам. */
|
||||
public double advance(String text, double sizePt) {
|
||||
CmapLookup c = cmap();
|
||||
double w = 0;
|
||||
for (int i = 0; i < text.length(); ) {
|
||||
int cp = text.codePointAt(i);
|
||||
w += advanceWidth(c.getGlyphId(cp)) * sizePt / unitsPerEm();
|
||||
i += Character.charCount(cp);
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
/** Высота возвышения над базовой линией в pt (hhea.ascender). */
|
||||
public double ascent(double sizePt) {
|
||||
return hhea().getAscender() * sizePt / unitsPerEm();
|
||||
}
|
||||
|
||||
/** Глубина ниже базовой линии в pt (hhea.descender — число отрицательное). */
|
||||
public double descent(double sizePt) {
|
||||
return -hhea().getDescender() * sizePt / unitsPerEm();
|
||||
}
|
||||
|
||||
/** Межстрочный интервал в pt (hhea.lineGap; у бандла — 0). */
|
||||
public double leading(double sizePt) {
|
||||
return hhea().getLineGap() * sizePt / unitsPerEm();
|
||||
}
|
||||
|
||||
/**
|
||||
* Рисует строку глифами-контурами: базовая линия в {@code baselineY},
|
||||
* цвет/прочие атрибуты — уже установлены в {@code g} вызывающим.
|
||||
* Координаты glyf — Y вверх, база в нуле, поэтому контур
|
||||
* масштабируется с инверсией Y.
|
||||
*/
|
||||
public void draw(Graphics2D g, String text, double x, double baselineY, double sizePt) {
|
||||
CmapLookup c = cmap();
|
||||
double px = x;
|
||||
for (int i = 0; i < text.length(); ) {
|
||||
int cp = text.codePointAt(i);
|
||||
int gid = c.getGlyphId(cp);
|
||||
GlyphData glyph = glyph(gid);
|
||||
GeneralPath p = glyph == null ? null : glyph.getPath();
|
||||
if (p != null) {
|
||||
AffineTransform tr = AffineTransform.getTranslateInstance(px, baselineY);
|
||||
tr.scale(sizePt / unitsPerEm(), -sizePt / unitsPerEm());
|
||||
g.fill(p.createTransformedShape(tr));
|
||||
}
|
||||
px += advanceWidth(gid) * sizePt / unitsPerEm();
|
||||
i += Character.charCount(cp);
|
||||
}
|
||||
}
|
||||
|
||||
private CmapLookup cmap() {
|
||||
CmapLookup c = cmap;
|
||||
if (c == null) {
|
||||
try {
|
||||
c = ttf.getUnicodeCmapLookup();
|
||||
} catch (IOException e) {
|
||||
throw broken(e);
|
||||
}
|
||||
cmap = c;
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
private GlyphData glyph(int gid) {
|
||||
try {
|
||||
return ttf.getGlyph().getGlyph(gid);
|
||||
} catch (IOException e) {
|
||||
throw broken(e);
|
||||
}
|
||||
}
|
||||
|
||||
private double advanceWidth(int gid) {
|
||||
try {
|
||||
return ttf.getAdvanceWidth(gid);
|
||||
} catch (IOException e) {
|
||||
throw broken(e);
|
||||
}
|
||||
}
|
||||
|
||||
private int unitsPerEm() {
|
||||
try {
|
||||
return ttf.getUnitsPerEm();
|
||||
} catch (IOException e) {
|
||||
throw broken(e);
|
||||
}
|
||||
}
|
||||
|
||||
private HorizontalHeaderTable hhea() {
|
||||
try {
|
||||
return ttf.getHorizontalHeader();
|
||||
} catch (IOException e) {
|
||||
throw broken(e);
|
||||
}
|
||||
}
|
||||
|
||||
private IllegalStateException broken(IOException e) {
|
||||
return new IllegalStateException("Битый шрифт бандла: " + key, e);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package ru.pjandro.wordpdf.internal;
|
||||
|
||||
import ru.pjandro.wordpdf.fonts.BundledFontMapper;
|
||||
import ru.pjandro.wordpdf.fonts.BundledFonts;
|
||||
import ru.pjandro.wordpdf.fonts.GlyphFont;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
@@ -296,24 +297,26 @@ public final class GlyphCoverageNormalizer {
|
||||
private static Coverage coverage(String family) {
|
||||
Coverage c = COVERAGE.get(family);
|
||||
if (c == null) {
|
||||
c = new Coverage(BundledFonts.awtFont(family, BundledFonts.V_REGULAR));
|
||||
c = new Coverage(GlyphFont.of(family, BundledFonts.V_REGULAR));
|
||||
COVERAGE.put(family, c);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
/**
|
||||
* Покрытие одного семейства: {@code java.awt.Font.canDisplay} с кэшем
|
||||
* «проверенных» кодов. AWT берётся вместо {@code GlyphCheck}, чтобы не
|
||||
* плодить INFO-лог на каждый отсутствующий глиф.
|
||||
* Покрытие одного семейства: {@link GlyphFont#canDisplay} (fontbox,
|
||||
* cmap) с кэшем «проверенных» кодов. GlyphFont вместо
|
||||
* {@code java.awt.Font}, потому что AWT требует fontconfig на хосте
|
||||
* (OpenJDK/Linux), а docx4j {@code GlyphCheck} плодит INFO-лог на
|
||||
* каждый отсутствующий глиф.
|
||||
*/
|
||||
private static final class Coverage {
|
||||
|
||||
private final java.awt.Font font;
|
||||
private final GlyphFont font;
|
||||
private final java.util.BitSet checked = new java.util.BitSet();
|
||||
private final java.util.BitSet covered = new java.util.BitSet();
|
||||
|
||||
Coverage(java.awt.Font font) {
|
||||
Coverage(GlyphFont font) {
|
||||
this.font = font;
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ final class CartesianPainter {
|
||||
// 1. Поля под подписи осей
|
||||
double catGutter = 0;
|
||||
if (!cats.isEmpty()) {
|
||||
catGutter = DrawMlText.textHeight(catStyle, g.getFontRenderContext());
|
||||
catGutter = DrawMlText.textHeight(catStyle);
|
||||
}
|
||||
catGutter += 6; // auto-layout Word: отступ от подписей до области (Word-эмпирика)
|
||||
|
||||
@@ -54,7 +54,7 @@ final class CartesianPainter {
|
||||
// а не 1 (0…5). Явные c:majorUnit/c:max не трогаем.
|
||||
if (valStyle != null && !valAxis.deleted
|
||||
&& valAxis.majorUnit == null && valAxis.max == null) {
|
||||
double labelH = DrawMlText.textHeight(valStyle, g.getFontRenderContext());
|
||||
double labelH = DrawMlText.textHeight(valStyle);
|
||||
double axisLen = Math.max(10,
|
||||
(horizontal ? box.getWidth() : box.getHeight()) - catGutter);
|
||||
while (hi - lo > unit && axisLen / ((hi - lo) / unit) < 2.5 * labelH) {
|
||||
@@ -70,7 +70,7 @@ final class CartesianPainter {
|
||||
}
|
||||
double valGutter = 0;
|
||||
for (String l : valLabels) {
|
||||
valGutter = Math.max(valGutter, DrawMlText.textWidth(l, valStyle, g.getFontRenderContext()));
|
||||
valGutter = Math.max(valGutter, DrawMlText.textWidth(l, valStyle));
|
||||
}
|
||||
valGutter += 8; // auto-layout Word: отступ от подписей до области (Word-эмпирика)
|
||||
|
||||
@@ -149,7 +149,7 @@ final class CartesianPainter {
|
||||
return;
|
||||
}
|
||||
double n = cats.size();
|
||||
double h = DrawMlText.textHeight(style, g.getFontRenderContext()) + 2;
|
||||
double h = DrawMlText.textHeight(style) + 2;
|
||||
for (int i = 0; i < n; i++) {
|
||||
String label = cats.get(i);
|
||||
if (label.isEmpty()) {
|
||||
@@ -162,7 +162,7 @@ final class CartesianPainter {
|
||||
"r", "ctr", 1.0);
|
||||
} else {
|
||||
double cx = plot.getX() + plot.getWidth() * (i + 0.5) / n;
|
||||
double w = DrawMlText.textWidth(label, style, g.getFontRenderContext());
|
||||
double w = DrawMlText.textWidth(label, style);
|
||||
double slot = plot.getWidth() / n;
|
||||
// Word прячет подписи, которые не помещаются в слот
|
||||
if (w > slot * 1.15) {
|
||||
@@ -182,11 +182,11 @@ final class CartesianPainter {
|
||||
if (style == null) {
|
||||
return;
|
||||
}
|
||||
double h = DrawMlText.textHeight(style, g.getFontRenderContext()) + 2;
|
||||
double h = DrawMlText.textHeight(style) + 2;
|
||||
double span = hi - lo;
|
||||
for (int i = 0; i < labels.size(); i++) {
|
||||
double t = span == 0 ? 0 : i / (double) (labels.size() - 1);
|
||||
double w = DrawMlText.textWidth(labels.get(i), style, g.getFontRenderContext());
|
||||
double w = DrawMlText.textWidth(labels.get(i), style);
|
||||
if (horizontal) {
|
||||
double x = plot.getX() + t * plot.getWidth();
|
||||
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(labels.get(i), style, "ctr")),
|
||||
|
||||
@@ -59,7 +59,7 @@ final class ChartRenderer {
|
||||
box = new Rectangle2D.Double(box.getX(), box.getY() + titleH,
|
||||
box.getWidth(), box.getHeight() - titleH);
|
||||
|
||||
Legend legend = measureLegend(g, spec, palette);
|
||||
Legend legend = measureLegend(spec, palette);
|
||||
double legendH = legend == null ? 0 : legend.height;
|
||||
if (legend != null && "b".equals(spec.legendPos)) {
|
||||
legend.draw(g, box.getX(), box.getY() + box.getHeight() - legendH,
|
||||
@@ -105,8 +105,8 @@ final class ChartRenderer {
|
||||
if (spec.title == null || spec.titleStyle == null) {
|
||||
return 0;
|
||||
}
|
||||
double lineH = DrawMlText.textHeight(spec.titleStyle, g.getFontRenderContext());
|
||||
double width = DrawMlText.textWidth(spec.title, spec.titleStyle, g.getFontRenderContext());
|
||||
double lineH = DrawMlText.textHeight(spec.titleStyle);
|
||||
double width = DrawMlText.textWidth(spec.title, spec.titleStyle);
|
||||
double height = lineH + 4;
|
||||
if (width > box.getWidth()) {
|
||||
DrawMlText.paint(g, List.of(new Paragraph(spec.title, spec.titleStyle, "ctr")),
|
||||
@@ -152,7 +152,7 @@ final class ChartRenderer {
|
||||
g.fill(new Rectangle2D.Double(startX, midY - square / 2.0, square, square));
|
||||
startX += square + 3;
|
||||
}
|
||||
double tw = DrawMlText.textWidth(e.label(), style, g.getFontRenderContext());
|
||||
double tw = DrawMlText.textWidth(e.label(), style);
|
||||
DrawMlText.paint(g, List.of(new Paragraph(e.label(), style, "l")),
|
||||
new Rectangle2D.Double(startX, y, tw, height), "l", "ctr", 1.0);
|
||||
startX += tw + 8;
|
||||
@@ -160,7 +160,7 @@ final class ChartRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
private static Legend measureLegend(Graphics2D g, ChartSpec spec, List<Color> palette) {
|
||||
private static Legend measureLegend(ChartSpec spec, List<Color> palette) {
|
||||
if (spec.legendPos == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -232,11 +232,11 @@ final class ChartRenderer {
|
||||
double width = 0;
|
||||
for (Legend.Entry e : legend.entries) {
|
||||
double marker = e.lineWidth() > 0 ? legend.lineLen : legend.square;
|
||||
width += marker + 3 + DrawMlText.textWidth(e.label(), style, g.getFontRenderContext()) + 8;
|
||||
width += marker + 3 + DrawMlText.textWidth(e.label(), style) + 8;
|
||||
}
|
||||
legend.totalWidth = width;
|
||||
legend.height = Math.max(Math.max(legend.square, legend.lineLen * 0.2),
|
||||
DrawMlText.textHeight(style, g.getFontRenderContext())) + 4;
|
||||
DrawMlText.textHeight(style)) + 4;
|
||||
return legend;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,11 +9,10 @@ import org.docx4j.dml.TextFont;
|
||||
import ru.pjandro.wordpdf.fonts.BundledFontMapper;
|
||||
import ru.pjandro.wordpdf.fonts.BundledFonts;
|
||||
|
||||
import ru.pjandro.wordpdf.fonts.GlyphFont;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.Font;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.font.FontRenderContext;
|
||||
import java.awt.font.TextLayout;
|
||||
import java.awt.geom.Rectangle2D;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -138,18 +137,32 @@ final class DrawMlText {
|
||||
return BundledFontMapper.bundledFamily(name != null ? name : fallbackFam);
|
||||
}
|
||||
|
||||
/** java.awt.Font для стиля; null -> логический SansSerif. */
|
||||
static Font fontFor(Style style) {
|
||||
/**
|
||||
* Шрифт бандла ({@link GlyphFont}, без java.awt.Font — рантайму
|
||||
* не нужен fontconfig) для стиля. Цепочка фолбэка: запрошенное
|
||||
* начертание -> regular того же семейства -> fallback-семейство
|
||||
* (dejavu sans имеет все четыре начертания, поэтому null не
|
||||
* возвращается никогда). Нераспознанное семейство -> sans-фолбэк,
|
||||
* как раньше. Отличие от AWT-варианта: bold/italic у семейства
|
||||
* только с regular (Noto) рисуется своим regular, а не логическим
|
||||
* SansSerif — начертание остаётся в своём семействе.
|
||||
*/
|
||||
static GlyphFont fontFor(Style style) {
|
||||
String variant = style.bold() && style.italic() ? BundledFonts.V_BOLD_ITALIC
|
||||
: style.bold() ? BundledFonts.V_BOLD
|
||||
: style.italic() ? BundledFonts.V_ITALIC
|
||||
: BundledFonts.V_REGULAR;
|
||||
Font base = BundledFonts.awtFont(style.family(), variant);
|
||||
int flags = (style.bold() ? Font.BOLD : 0) | (style.italic() ? Font.ITALIC : 0);
|
||||
if (base == null) {
|
||||
return new Font(Font.SANS_SERIF, flags, 1).deriveFont((float) style.sizePt());
|
||||
GlyphFont f = GlyphFont.of(style.family(), variant);
|
||||
if (f == null) {
|
||||
f = GlyphFont.of(style.family(), BundledFonts.V_REGULAR);
|
||||
}
|
||||
return base.deriveFont((float) style.sizePt());
|
||||
if (f == null) {
|
||||
f = GlyphFont.of(BundledFonts.FALLBACK_FAMILY, variant);
|
||||
}
|
||||
if (f == null) {
|
||||
f = GlyphFont.of(BundledFonts.FALLBACK_FAMILY, BundledFonts.V_REGULAR);
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -162,21 +175,20 @@ final class DrawMlText {
|
||||
if (paragraphs.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
FontRenderContext frc = g.getFontRenderContext();
|
||||
record Line(String text, Style style, String align, double width, double height,
|
||||
double ascent) {
|
||||
}
|
||||
List<Line> lines = new ArrayList<>();
|
||||
double totalHeight = 0;
|
||||
for (Paragraph p : paragraphs) {
|
||||
Font f = fontFor(p.style());
|
||||
TextLayout metrics = new TextLayout("Xg", f, frc);
|
||||
double lineH = (metrics.getAscent() + metrics.getDescent()
|
||||
+ metrics.getLeading()) * lineHeightFactor;
|
||||
for (String line : wrapLines(p.text(), f, frc, box.getWidth())) {
|
||||
double w = new TextLayout(line, f, frc).getAdvance();
|
||||
lines.add(new Line(line, p.style(), p.align(), w, lineH,
|
||||
metrics.getAscent() * lineHeightFactor));
|
||||
GlyphFont f = fontFor(p.style());
|
||||
double sizePt = p.style().sizePt();
|
||||
double lineH = (f.ascent(sizePt) + f.descent(sizePt)
|
||||
+ f.leading(sizePt)) * lineHeightFactor;
|
||||
for (String line : wrapLines(p.text(), f, sizePt, box.getWidth())) {
|
||||
lines.add(new Line(line, p.style(), p.align(),
|
||||
f.advance(line, sizePt), lineH,
|
||||
f.ascent(sizePt) * lineHeightFactor));
|
||||
totalHeight += lineH;
|
||||
}
|
||||
}
|
||||
@@ -188,7 +200,6 @@ final class DrawMlText {
|
||||
}
|
||||
y = Math.max(box.getY(), y);
|
||||
for (Line line : lines) {
|
||||
g.setFont(fontFor(line.style()));
|
||||
g.setColor(line.style().color());
|
||||
double x = box.getX();
|
||||
String align = line.align() != null ? line.align() : defAlign;
|
||||
@@ -197,13 +208,14 @@ final class DrawMlText {
|
||||
} else if ("r".equals(align) || "far".equals(align)) {
|
||||
x += box.getWidth() - line.width();
|
||||
}
|
||||
g.drawString(line.text(), (float) x, (float) (y + line.ascent()));
|
||||
fontFor(line.style()).draw(g, line.text(), x, y + line.ascent(),
|
||||
line.style().sizePt());
|
||||
y += line.height();
|
||||
}
|
||||
}
|
||||
|
||||
/** Жадный перенос по пробелам; длинные слова режутся по символам. */
|
||||
private static List<String> wrapLines(String text, Font f, FontRenderContext frc,
|
||||
private static List<String> wrapLines(String text, GlyphFont f, double sizePt,
|
||||
double maxWidth) {
|
||||
List<String> out = new ArrayList<>();
|
||||
double limit = Math.max(1, maxWidth);
|
||||
@@ -219,7 +231,7 @@ final class DrawMlText {
|
||||
continue;
|
||||
}
|
||||
String candidate = cur.length() == 0 ? word : cur + " " + word;
|
||||
double w = new TextLayout(candidate, f, frc).getAdvance();
|
||||
double w = f.advance(candidate, sizePt);
|
||||
if (w <= limit || cur.length() == 0) {
|
||||
cur.setLength(0);
|
||||
cur.append(candidate);
|
||||
@@ -228,16 +240,15 @@ final class DrawMlText {
|
||||
out.add(cur.toString());
|
||||
cur.setLength(0);
|
||||
cur.append(word);
|
||||
curWidth = new TextLayout(word, f, frc).getAdvance();
|
||||
curWidth = f.advance(word, sizePt);
|
||||
while (curWidth > limit && cur.length() > 1) {
|
||||
int cut = cur.length() - 1;
|
||||
while (cut > 1 && new TextLayout(cur.substring(0, cut), f, frc)
|
||||
.getAdvance() > limit) {
|
||||
while (cut > 1 && f.advance(cur.substring(0, cut), sizePt) > limit) {
|
||||
cut--;
|
||||
}
|
||||
out.add(cur.substring(0, cut));
|
||||
cur.delete(0, cut);
|
||||
curWidth = new TextLayout(cur.toString(), f, frc).getAdvance();
|
||||
curWidth = f.advance(cur.toString(), sizePt);
|
||||
}
|
||||
}
|
||||
if (cur.length() > 0) {
|
||||
@@ -248,14 +259,14 @@ final class DrawMlText {
|
||||
}
|
||||
|
||||
/** Ширина строки в тех же единицах, что и размер шрифта. */
|
||||
static double textWidth(String text, Style style, FontRenderContext frc) {
|
||||
return new TextLayout(text, fontFor(style), frc).getAdvance();
|
||||
static double textWidth(String text, Style style) {
|
||||
return fontFor(style).advance(text, style.sizePt());
|
||||
}
|
||||
|
||||
/** Высота строки (ascent+descent+leading) для стиля. */
|
||||
static double textHeight(Style style, FontRenderContext frc) {
|
||||
Font f = fontFor(style);
|
||||
TextLayout tl = new TextLayout("Xpg", f, frc);
|
||||
return tl.getAscent() + tl.getDescent() + tl.getLeading();
|
||||
static double textHeight(Style style) {
|
||||
GlyphFont f = fontFor(style);
|
||||
return f.ascent(style.sizePt()) + f.descent(style.sizePt())
|
||||
+ f.leading(style.sizePt());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,7 +264,7 @@ final class SmartArtRenderer {
|
||||
for (int attempt = 0; attempt < 4; attempt++) {
|
||||
double needed = 0;
|
||||
for (DrawMlText.Paragraph p : paragraphs) {
|
||||
needed += DrawMlText.textHeight(p.style(), g.getFontRenderContext());
|
||||
needed += DrawMlText.textHeight(p.style());
|
||||
}
|
||||
if (needed <= th || p0(paragraphs) <= 4) {
|
||||
break;
|
||||
|
||||
@@ -439,7 +439,7 @@ final class Surface3dPainter {
|
||||
// Ось значений: левый край дальней стенки
|
||||
DrawMlText.Style vs = valAxis.labelStyle;
|
||||
if (vs != null) {
|
||||
double h = DrawMlText.textHeight(vs, g.getFontRenderContext()) + 2;
|
||||
double h = DrawMlText.textHeight(vs) + 2;
|
||||
int i = 0;
|
||||
for (double v = lo; v <= hi + unit / 2; v += unit) {
|
||||
if (i >= valueAnchors.size()) {
|
||||
@@ -449,7 +449,7 @@ final class Surface3dPainter {
|
||||
double x = n.x() * fit.scaleX() + fit.offX();
|
||||
double y = n.y() * fit.scaleY() + fit.offY();
|
||||
String label = ChartRenderer.formatValue(v, valAxis.numFmt);
|
||||
double w = DrawMlText.textWidth(label, vs, g.getFontRenderContext());
|
||||
double w = DrawMlText.textWidth(label, vs);
|
||||
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, vs, "r")),
|
||||
new Rectangle2D.Double(x - w - 4, y - h / 2, w, h), "r", "ctr", 1.0);
|
||||
}
|
||||
@@ -458,7 +458,7 @@ final class Surface3dPainter {
|
||||
// Категории: переднее нижнее ребро пола
|
||||
DrawMlText.Style cs = catAxis.labelStyle;
|
||||
if (cs != null) {
|
||||
double h = DrawMlText.textHeight(cs, g.getFontRenderContext()) + 2;
|
||||
double h = DrawMlText.textHeight(cs) + 2;
|
||||
for (int c = 0; c < nCat; c++) {
|
||||
String label = c < spec.categories.size() ? spec.categories.get(c) : "";
|
||||
if (label.isEmpty()) {
|
||||
@@ -470,7 +470,7 @@ final class Surface3dPainter {
|
||||
// (замер по эталону word-export.pdf, 300 dpi: центры подписей 669/714/
|
||||
// 764/820 px при линии пола 606/651/700/757 px)
|
||||
double y = n.y() * fit.scaleY() + fit.offY() + 8;
|
||||
double w = DrawMlText.textWidth(label, cs, g.getFontRenderContext());
|
||||
double w = DrawMlText.textWidth(label, cs);
|
||||
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, cs, "ctr")),
|
||||
new Rectangle2D.Double(x - w / 2, y, w, h), "ctr", "t", 1.0);
|
||||
}
|
||||
@@ -479,7 +479,7 @@ final class Surface3dPainter {
|
||||
// Ряды: правое нижнее ребро пола
|
||||
DrawMlText.Style ss = serAxis.labelStyle;
|
||||
if (ss != null) {
|
||||
double h = DrawMlText.textHeight(ss, g.getFontRenderContext()) + 2;
|
||||
double h = DrawMlText.textHeight(ss) + 2;
|
||||
for (int r = 0; r < nSer; r++) {
|
||||
String label = spec.series.get(r).name;
|
||||
if (label == null || label.isEmpty()) {
|
||||
@@ -488,7 +488,7 @@ final class Surface3dPainter {
|
||||
Node n = project(0.5, vOf(r, nSer), floorW, rotX, rotY, depthScale, persp);
|
||||
double x = n.x() * fit.scaleX() + fit.offX() + 4;
|
||||
double y = n.y() * fit.scaleY() + fit.offY();
|
||||
double w = DrawMlText.textWidth(label, ss, g.getFontRenderContext());
|
||||
double w = DrawMlText.textWidth(label, ss);
|
||||
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, ss, "l")),
|
||||
new Rectangle2D.Double(x, y - h / 2, w, h), "l", "ctr", 1.0);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package ru.pjandro.wordpdf.fonts;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.RenderingHints;
|
||||
import java.awt.image.BufferedImage;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Глиф-движок GlyphFont (fontbox). Тест намеренно не использует
|
||||
* {@code java.awt.Font} ни в одной строке: он обязан проходить на хосте
|
||||
* без fontconfig (контейнер без libfontconfig.so и /etc/fonts) — это и
|
||||
* есть приёмочный стенд перехода с AWT-шрифтов на fontbox.
|
||||
*/
|
||||
class GlyphFontTest {
|
||||
|
||||
/** Нет такого семейства в бандле -> null (запрашивающий делает фолбэк). */
|
||||
@Test
|
||||
void of_unknownFamily_returnsNull() {
|
||||
assertNull(GlyphFont.of("comic sans ms", BundledFonts.V_REGULAR));
|
||||
}
|
||||
|
||||
/** Семейство есть, начертания нет (Noto — только regular) -> null. */
|
||||
@Test
|
||||
void of_missingVariant_returnsNull() {
|
||||
assertNull(GlyphFont.of("noto naskh arabic", BundledFonts.V_BOLD));
|
||||
}
|
||||
|
||||
/** Кириллица покрыта; известный остаток эталона U+2188 — нет. */
|
||||
@Test
|
||||
void canDisplay_cyrillicTrue_missingGlyphFalse() {
|
||||
GlyphFont f = GlyphFont.of("dejavu sans", BundledFonts.V_REGULAR);
|
||||
assertNotNull(f);
|
||||
assertTrue(f.canDisplay('а'));
|
||||
assertFalse(f.canDisplay(0x2188));
|
||||
}
|
||||
|
||||
/** Ширина строки — сумма ширин глифов по кодовым точкам. */
|
||||
@Test
|
||||
void advance_sumsCodePoints() {
|
||||
GlyphFont f = GlyphFont.of("carlito", BundledFonts.V_REGULAR);
|
||||
assertNotNull(f);
|
||||
assertEquals(f.advance("A", 12) + f.advance("V", 12),
|
||||
f.advance("AV", 12), 1e-9);
|
||||
assertTrue(f.advance("AV", 12) > 0);
|
||||
}
|
||||
|
||||
/** Растеризация глифов-контуров оставляет чернила (пиксели с alpha). */
|
||||
@Test
|
||||
void draw_leavesInkPixels() {
|
||||
GlyphFont f = GlyphFont.of("dejavu sans", BundledFonts.V_REGULAR);
|
||||
assertNotNull(f);
|
||||
BufferedImage img = new BufferedImage(200, 100, BufferedImage.TYPE_INT_ARGB);
|
||||
Graphics2D g = img.createGraphics();
|
||||
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
|
||||
RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
g.setColor(java.awt.Color.BLACK);
|
||||
f.draw(g, "Тест", 10, 60, 12);
|
||||
g.dispose();
|
||||
int ink = 0;
|
||||
for (int px : img.getRGB(0, 0, img.getWidth(), img.getHeight(),
|
||||
null, 0, img.getWidth())) {
|
||||
if ((px >>> 24) > 0) {
|
||||
ink++;
|
||||
}
|
||||
}
|
||||
assertTrue(ink > 100, "Глифы не оставили пикселей: " + ink);
|
||||
}
|
||||
|
||||
/** Вертикальные метрики: ascent/descent положительные, leading >= 0. */
|
||||
@Test
|
||||
void ascentDescent_positive() {
|
||||
GlyphFont f = GlyphFont.of("carlito", BundledFonts.V_REGULAR);
|
||||
assertNotNull(f);
|
||||
assertTrue(f.ascent(12) > 0);
|
||||
assertTrue(f.descent(12) > 0);
|
||||
assertTrue(f.leading(12) >= 0);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user