SmartArt: ECMA-376 пресет-геометрия вместо калиброванных коэффициентов
PR checks / java (pull_request) Successful in 47s
PR checks / web (pull_request) Successful in 53s
Main: tests, deploy, autotests / web (push) Successful in 43s
Main: tests, deploy, autotests / java (push) Successful in 45s
Main: tests, deploy, autotests / images-web (push) Successful in 29s
Main: tests, deploy, autotests / images-app (push) Successful in 2m26s
Main: tests, deploy, autotests / deploy (push) Successful in 2m56s
Main: tests, deploy, autotests / autotests (push) Successful in 51s
Main: tests, deploy, autotests / rollback (push) Has been skipped

PresetGeometry: avLst/gdLst/pathLst семи пресетов (rect, roundRect, ellipse,
gear6, gear9, circularArrow, leftCircularArrow) дословно из
presetShapeDefinitions.xml + вычислитель префиксных формул ST_GeomGuideFormula.
Кольцевые стрелки: оператор ?: = «if x > 0 then y else z» (ISO/IEC 29500-1),
углы Arc2D со знаком минус (математическая конвенция). PrstGeomShapes удалён.
PresetGeometryTest#tableMatchesEcmaXml пинит синхрон таблицы с копией
стандарта (test-ресурс geom/presetShapeDefinitions.xml).
This commit was merged in pull request #33.
This commit is contained in:
Pjandro
2026-10-23 21:25:15 +00:00
parent 4ab6cf8463
commit 037474cf5b
6 changed files with 21562 additions and 247 deletions
File diff suppressed because it is too large Load Diff
@@ -1,183 +0,0 @@
package ru.pjandro.wordpdf.internal.chart;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
/**
* Пресеты геометрии DrawingML (a:prstGeom) в объёме, который нужен
* SmartArt-схемам: прямоугольники, эллипсы, шестерни и круговые стрелки.
*
* Неизвестный пресет -> прямоугольник (вызывающий логирует подмену):
* для подписанной схемы это заметнее, чем пустое место.
*/
final class PrstGeomShapes {
/** Минимальный заметный дуге размах, градусы. */
private static final double MIN_ARC_SPAN_DEG = 1;
private PrstGeomShapes() {
}
/** Форма с необязательным отверстием (у шестерней — центральная втулка). */
record Shape(Area area, Area hole) {
Area filled() {
if (hole == null) {
return area;
}
Area a = new Area(area);
a.subtract(hole);
return a;
}
}
/**
* @param prst имя пресета из a:prstGeom/@prst
* @param adj целочисленные adjs из a:avLst (в стотысячных долях/градусах*60000)
*/
static Shape build(String prst, int[] adj, double x, double y, double w, double h) {
String p = prst == null ? "rect" : prst;
switch (p) {
case "rect" -> {
return new Shape(new Area(new Rectangle2D.Double(x, y, w, h)), null);
}
case "roundRect" -> {
double arc = Math.min(w, h) * 0.12;
return new Shape(new Area(new RoundRectangle2D.Double(x, y, w, h, arc, arc)), null);
}
case "ellipse", "oval" -> {
return new Shape(new Area(new Ellipse2D.Double(x, y, w, h)), null);
}
case "gear6", "gear9" -> {
int teeth = "gear6".equals(p) ? 6 : 9;
return gear(x, y, w, h, teeth);
}
case "circularArrow", "leftCircularArrow", "rightCircularArrow",
"curvedRightArrow", "curvedLeftArrow" -> {
return circularArrow(x, y, w, h, adj,
"leftCircularArrow".equals(p) || "curvedLeftArrow".equals(p));
}
default -> {
return new Shape(new Area(new Rectangle2D.Double(x, y, w, h)), null);
}
}
}
/**
* Шестерня: зубчатый венец + (опционально) центральное отверстие.
* Внешний радиус немного меньше w/2 (× 0.92), чтобы соседние
* шестерни в drawing1.xml не слипались там, где их ext-ы близко
* (Word использует тот же приём — эффективный радиус ≈ 0.97·ext/2).
* Зуб узкий и короткий, впадины — глубокие.
*/
private static Shape gear(double x, double y, double w, double h, int teeth) {
double cx = x + w / 2.0;
double cy = y + h / 2.0;
double r = Math.min(w, h) / 2.0 * 0.82;
double toothH = r * 0.18;
double body = r - toothH;
Path2D path = new Path2D.Double();
double step = 2 * Math.PI / teeth;
// зуб: основание -> подъём -> вершина (плоская) -> спуск
double toothWidth = step * 0.30;
for (int i = 0; i < teeth; i++) {
double a = i * step;
double a0 = a - toothWidth;
double a1 = a + toothWidth;
double gap1 = a + step - toothWidth;
if (i == 0) {
path.moveTo(cx + body * Math.cos(a0), cy + body * Math.sin(a0));
} else {
path.lineTo(cx + body * Math.cos(a0), cy + body * Math.sin(a0));
}
path.lineTo(cx + r * Math.cos(a0 + toothWidth * 0.5),
cy + r * Math.sin(a0 + toothWidth * 0.5));
path.lineTo(cx + r * Math.cos(a1 - toothWidth * 0.5),
cy + r * Math.sin(a1 - toothWidth * 0.5));
path.lineTo(cx + body * Math.cos(a1), cy + body * Math.sin(a1));
// впадина: плоская дуга по body между зубьями
path.lineTo(cx + body * Math.cos(gap1), cy + body * Math.sin(gap1));
}
path.closePath();
return new Shape(new Area(path), null);
}
/**
* Круговая стрелка: сектор кольца + треугольный наконечник.
* adj2/adj3 — углы начала/конца в 1/60000 градуса (0 = на 3 часа,
* по часовой, т.к. y на экране растёт вниз).
*/
private static Shape circularArrow(double x, double y, double w, double h,
int[] adj, boolean arrowAtStart) {
double cx = x + w / 2.0;
double cy = y + h / 2.0;
double rOuter = Math.min(w, h) / 2.0 * 0.92;
// adj1 у реальных схем даёт невидимую полоску — держим минимум.
double thickness = Math.max(rOuter * pct(adj, 0, 40000), rOuter * 0.07);
double rInner = Math.max(1, rOuter - thickness);
double startDeg = deg(adj, 1, 2700000);
double endDeg = deg(adj, 2, 3600000);
if (Math.abs(endDeg - startDeg) < MIN_ARC_SPAN_DEG) {
endDeg = startDeg + 270;
}
double a0 = Math.toRadians(startDeg);
double a1 = Math.toRadians(endDeg);
if (a1 < a0) {
a1 += 2 * Math.PI;
}
Path2D path = new Path2D.Double();
arcSegment(path, cx, cy, rOuter, a0, a1);
arcSegment(path, cx, cy, rInner, a1, a0);
path.closePath();
Area area = new Area(path);
// Наконечник: размеры берём от толщины кольца — adjs у реальных
// схем (adj4/adj5) дают либо абсурдный угол, либо невидимый «усик».
// headOut ограничен, чтобы он не вылезал сильно за rOuter (иначе
// кольцо цепляется с шестерёнкой, центр которой совпадает со стрелкой).
double rMid = (rOuter + rInner) / 2.0;
double headOut = Math.min(thickness * 1.15, thickness * 2.0);
double tipAngle = arrowAtStart ? a0 - thickness * 1.7 / rMid : a1 + thickness * 1.7 / rMid;
double baseAngle = thickness * 0.9 / rMid;
double base = arrowAtStart ? a0 : a1;
Path2D head = new Path2D.Double();
head.moveTo(cx + (rOuter + headOut * 0.2) * Math.cos(base - Math.copySign(baseAngle, base - tipAngle)),
cy + (rOuter + headOut * 0.2) * Math.sin(base - Math.copySign(baseAngle, base - tipAngle)));
head.lineTo(cx + rMid * Math.cos(tipAngle), cy + rMid * Math.sin(tipAngle));
head.lineTo(cx + Math.max(1, rInner - headOut) * Math.cos(base - Math.copySign(baseAngle, base - tipAngle)),
cy + Math.max(1, rInner - headOut) * Math.sin(base - Math.copySign(baseAngle, base - tipAngle)));
head.closePath();
area.add(new Area(head));
return new Shape(area, null);
}
private static void arcSegment(Path2D path, double cx, double cy, double r,
double a0, double a1) {
int steps = Math.max(2, (int) (Math.abs(a1 - a0) / Math.toRadians(4)));
for (int i = 0; i <= steps; i++) {
double t = a0 + (a1 - a0) * i / steps;
double px = cx + r * Math.cos(t);
double py = cy + r * Math.sin(t);
if (i == 0 && (path.getCurrentPoint() == null
|| Math.abs(path.getCurrentPoint().getX() - px) > 1e-9
|| Math.abs(path.getCurrentPoint().getY() - py) > 1e-9)) {
path.moveTo(px, py);
} else {
path.lineTo(px, py);
}
}
}
private static double pct(int[] adj, int idx, int def) {
int v = adj != null && idx < adj.length ? adj[idx] : def;
return v / 100000.0;
}
private static double deg(int[] adj, int idx, int def) {
int v = adj != null && idx < adj.length ? adj[idx] : def;
return v / 60000.0;
}
}
@@ -1,6 +1,5 @@
package ru.pjandro.wordpdf.internal.chart;
import org.docx4j.dml.CTGeomGuide;
import org.docx4j.dml.CTGradientFillProperties;
import org.docx4j.dml.CTGradientStop;
import org.docx4j.dml.CTPoint2D;
@@ -8,8 +7,11 @@ import org.docx4j.dml.CTPositiveSize2D;
import org.docx4j.dml.CTPresetGeometry2D;
import org.docx4j.dml.CTShapeProperties;
import org.docx4j.dml.CTShapeStyle;
import org.docx4j.dml.CTTextBodyProperties;
import org.docx4j.dml.CTTextNormalAutofit;
import org.docx4j.dml.CTTransform2D;
import org.docx4j.dml.diagram.CTCxn;
import org.docx4j.dml.STTextAnchoringType;
import org.docx4j.dml.diagram.CTDataModel;
import org.docx4j.dml.diagram.STCxnType;
import org.docx4j.dml.diagram.CTPt;
@@ -21,7 +23,6 @@ import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
@@ -45,6 +46,26 @@ final class SmartArtRenderer {
/** Порог «фигура повёрнута», градусы: меньше — поворот незначим. */
private static final double ROTATION_EPSILON_DEG = 0.01;
/** Дефолтные insets bodyPr (ECMA-376 CT_TextBodyProperties), pt. */
private static final double DEFAULT_LR_INS_PT = 7.2;
private static final double DEFAULT_TB_INS_PT = 3.6;
/** EMU в пунктах (insets заданы в EMU). */
private static final double EMU_PER_PT = 12700.0;
/** fontScale/lnSpcReduction: 100000 = «атрибут не задан / 100%». */
private static final int NORM_AUTOFIT_FULL = 100000;
/** Значения выравнивания bodyPr/@anchor, отличные от дефолта. */
private static final String VALIGN_CTR = "ctr";
private static final String VALIGN_BOTTOM = "b";
private static final String ALIGN_LEFT = "l";
private static final String VALIGN_TOP = "t";
/** Минимальный ещё печатаемый размер текстового прямоугольника/кегля, pt. */
private static final double MIN_TEXT_BOX_PT = 0.5;
private static final double MIN_FONT_PT = 4.0;
/** Попыток подбора кегля в autosize. */
private static final int SHRINK_ATTEMPTS = 4;
private SmartArtRenderer() {
}
@@ -99,10 +120,12 @@ final class SmartArtRenderer {
}
double mw = Math.max(1e-6, maxX - minX);
double mh = Math.max(1e-6, maxY - minY);
// 0.80: drawing1.xml хранит ext-ы вплотную (gear6+gear6,
// gear6+circularArrow с почти одним центром), при scale=0.96
// они слипаются. 0.80 даёт зазор ~10% от ext — как в эталоне.
double scale = Math.min(widthPt / mw, heightPt / mh) * 0.80;
// dsp-кэш: координаты EMU в проектном пространстве схемы; фрейм
// wp:extent — EMU. По MS-ODRAWXML «Diagram Layout» трансформа в
// схеме нет; когда кэш свежий, он совпадает с фреймом 1:1. Для
// устаревшего кэша (фрейм ресайзили после раскладки) — равномерный
// fit с центрированием, без коэффициентов.
double scale = Math.min(widthPt / mw, heightPt / mh);
double offX = (widthPt - mw * scale) / 2.0 - minX * scale;
double offY = (heightPt - mh * scale) / 2.0 - minY * scale;
@@ -180,16 +203,9 @@ final class SmartArtRenderer {
if (spPr != null && spPr.getPrstGeom() != null) {
CTPresetGeometry2D pg = spPr.getPrstGeom();
prst = pg.getPrst() == null ? null : pg.getPrst().value();
if (pg.getAvLst() != null) {
List<CTGeomGuide> gd = pg.getAvLst().getGd();
adj = new int[gd.size()];
for (int i = 0; i < gd.size(); i++) {
adj[i] = parseGuide(gd.get(i).getFmla());
}
}
adj = PresetGeometry.adjustValues(pg);
}
PrstGeomShapes.Shape shape = PrstGeomShapes.build(prst, adj, x, y, sw, sh);
Area area = shape.filled();
java.awt.Shape area = PresetGeometry.build(prst, adj, x, y, sw, sh);
Color fill = resolveFill(spPr, colors);
if (fill != null) {
@@ -233,6 +249,20 @@ final class SmartArtRenderer {
tw = txXfrm.getExt().getCx() / 12700.0 * scale;
th = txXfrm.getExt().getCy() / 12700.0 * scale;
}
CTTextBodyProperties bodyPr = sp.getTxBody() == null ? null : sp.getTxBody().getBodyPr();
if (bodyPr != null) {
double insL = inset(bodyPr.getLIns(), DEFAULT_LR_INS_PT) * scale;
double insR = inset(bodyPr.getRIns(), DEFAULT_LR_INS_PT) * scale;
double insT = inset(bodyPr.getTIns(), DEFAULT_TB_INS_PT) * scale;
double insB = inset(bodyPr.getBIns(), DEFAULT_TB_INS_PT) * scale;
tx += insL;
ty += insT;
tw -= insL + insR;
th -= insT + insB;
if (tw <= MIN_TEXT_BOX_PT || th <= MIN_TEXT_BOX_PT) {
return;
}
}
Color textColor = textColor(sp, colors);
List<DrawMlText.Paragraph> paragraphs = new ArrayList<>();
@@ -251,38 +281,68 @@ final class SmartArtRenderer {
if (paragraphs.isEmpty()) {
return;
}
// Шрифт из XML (sz=2600 → 26pt) слишком крупный для маленьких
// шестерёнок SmartArt: "123" лезет поверх зубьев. Ограничиваем
// начальный кегль ~25% меньшей стороны текстового прямоугольника.
double capPt = Math.max(4.0, Math.min(tw, th) * 0.25);
if (p0(paragraphs) > capPt) {
List<DrawMlText.Paragraph> shrunk = new ArrayList<>();
for (DrawMlText.Paragraph p : paragraphs) {
shrunk.add(new DrawMlText.Paragraph(p.text(),
p.style().derive(capPt, null, null, null, null), p.align()));
// autofit по CT_TextBodyProperties: noAutofit — текст по заявленным
// размерам (переполнение не ужимается, как в Word); normAutofit —
// fontScale/lnSpcReduction из XML, затем подбор кегля под прямоугольник.
double lineFactor = 1.0;
boolean noAutofit = bodyPr != null && bodyPr.getNoAutofit() != null;
CTTextNormalAutofit na = bodyPr == null ? null : bodyPr.getNormAutofit();
if (na != null) {
if (na.getFontScale() > 0 && na.getFontScale() != NORM_AUTOFIT_FULL) {
double k = na.getFontScale() / (double) NORM_AUTOFIT_FULL;
List<DrawMlText.Paragraph> scaled = new ArrayList<>();
for (DrawMlText.Paragraph p : paragraphs) {
scaled.add(new DrawMlText.Paragraph(p.text(),
p.style().derive(p.style().sizePt() * k,
null, null, null, null), p.align()));
}
paragraphs = scaled;
}
if (na.getLnSpcReduction() > 0) {
lineFactor = 1.0 - na.getLnSpcReduction() / (double) NORM_AUTOFIT_FULL;
}
paragraphs = shrunk;
}
// autosize: уменьшаем кегль, пока текст не влезет в прямоугольник
for (int attempt = 0; attempt < 4; attempt++) {
double needed = 0;
for (DrawMlText.Paragraph p : paragraphs) {
needed += DrawMlText.textHeight(p.style());
if (!noAutofit) {
// autosize: уменьшаем кегль, пока текст не влезет в прямоугольник
for (int attempt = 0; attempt < SHRINK_ATTEMPTS; attempt++) {
double needed = 0;
for (DrawMlText.Paragraph p : paragraphs) {
needed += DrawMlText.textHeight(p.style());
}
if (needed <= th || p0(paragraphs) <= MIN_FONT_PT) {
break;
}
double factor = th / needed;
List<DrawMlText.Paragraph> shrunk = new ArrayList<>();
for (DrawMlText.Paragraph p : paragraphs) {
shrunk.add(new DrawMlText.Paragraph(p.text(),
p.style().derive(p.style().sizePt() * factor,
null, null, null, null), p.align()));
}
paragraphs = shrunk;
}
if (needed <= th || p0(paragraphs) <= 4) {
break;
}
double factor = th / needed;
List<DrawMlText.Paragraph> shrunk = new ArrayList<>();
for (DrawMlText.Paragraph p : paragraphs) {
shrunk.add(new DrawMlText.Paragraph(p.text(),
p.style().derive(p.style().sizePt() * factor,
null, null, null, null), p.align()));
}
paragraphs = shrunk;
}
DrawMlText.paint(g, paragraphs, new Rectangle2D.Double(tx, ty, tw, th),
"ctr", "ctr", 1.0);
ALIGN_LEFT, vAlignOf(bodyPr), lineFactor);
}
/** Insets bodyPr: значение из XML (EMU) или дефолт ECMA (pt) -> pt. */
private static double inset(Integer emu, double defaultPt) {
return emu == null ? defaultPt : emu / EMU_PER_PT;
}
/** bodyPr/@anchor -> vAlign DrawMlText; дефолт ECMA — верх. */
private static String vAlignOf(CTTextBodyProperties bodyPr) {
if (bodyPr == null || bodyPr.getAnchor() == null) {
return VALIGN_TOP;
}
if (bodyPr.getAnchor() == STTextAnchoringType.CTR) {
return VALIGN_CTR;
}
if (bodyPr.getAnchor() == STTextAnchoringType.B) {
return VALIGN_BOTTOM;
}
return VALIGN_TOP;
}
private static double p0(List<DrawMlText.Paragraph> ps) {
@@ -318,20 +378,4 @@ final class SmartArtRenderer {
}
return new Color(0x59, 0x59, 0x59);
}
/** a:gd/@fmla = "val 4687" -> 4687. */
private static int parseGuide(String fmla) {
if (fmla == null) {
return 0;
}
String s = fmla.trim();
if (s.startsWith("val")) {
s = s.substring(3).trim();
}
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
return 0;
}
}
}
@@ -0,0 +1,275 @@
package ru.pjandro.wordpdf.internal.chart;
import org.docx4j.dml.CTGeomGuide;
import org.docx4j.dml.CTGeomGuideList;
import org.docx4j.dml.CTPresetGeometry2D;
import org.junit.jupiter.api.Test;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import java.awt.Shape;
import java.awt.geom.PathIterator;
import java.awt.geom.Rectangle2D;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Таблица пресетов {@link PresetGeometry} обязана быть дословной копией
* блоков ECMA {@code presetShapeDefinitions.xml} (копия стандарта —
* тестовый ресурс {@code geom/presetShapeDefinitions.xml}); синхрон
* проверяет {@link #tableMatchesEcmaXml()}.
*
* Геометрические зонды — регрессии разборов, на которых движок уже
* спотыкался: оператор {@code ?:} («if x > 0, then y else z», а не
* «x != 0») и знаковая конвенция дуг Arc2D. Ошибка в любом из них
* превращает кольцевую стрелку в залитый «пакман» без отверстия.
*/
class PresetGeometryTest {
private static final double EPS = 1e-6;
private static final String[] SUPPORTED = {
"rect", "roundRect", "ellipse", "gear6", "gear9",
"circularArrow", "leftCircularArrow",
};
/** Глубина блока пресета и его секций в дереве StAX (корень — 1). */
private static final int DEPTH_BLOCK = 2;
private static final int DEPTH_SECTION = 3;
@Test
void tableMatchesEcmaXml() throws Exception {
Map<String, PresetGeometry.Preset> fromXml = parseEcmaXml();
for (String name : SUPPORTED) {
PresetGeometry.Preset expected = fromXml.get(name);
PresetGeometry.Preset actual = PresetGeometry.preset(name);
assertTrue(expected != null && actual != null, name + " отсутствует");
assertArrayEquals(expected.avLst(), actual.avLst(), name + ": avLst");
assertArrayEquals(expected.gdLst(), actual.gdLst(), name + ": gdLst");
assertArrayEquals(expected.pathLst(), actual.pathLst(), name + ": pathLst");
}
}
/** circularArrow: кольцевая полоса сверху (180°→343,76°), отверстие пусто, низ — пасть. */
@Test
void circularArrowIsRingBandNotDisc() {
Shape s = PresetGeometry.build("circularArrow", new int[0], 0, 0, 100, 100);
for (double deg : new double[] {200, 270, 340}) {
assertTrue(onRing(s, deg, 37.5), "полоса на " + deg + "°");
assertFalse(onRing(s, deg, 20), "отверстие на " + deg + "°");
}
assertFalse(onRing(s, 90, 37.5), "низ — пасть, не полоса");
}
/** leftCircularArrow — зеркало: полоса снизу, пасть сверху. */
@Test
void leftCircularArrowMirrorsBand() {
Shape s = PresetGeometry.build("leftCircularArrow", new int[0], 0, 0, 100, 100);
for (double deg : new double[] {20, 90, 160}) {
assertTrue(onRing(s, deg, 37.5), "полоса на " + deg + "°");
assertFalse(onRing(s, deg, 20), "отверстие на " + deg + "°");
}
assertFalse(onRing(s, 270, 37.5), "верх — пасть, не полоса");
}
@Test
void gearsCoverCenterAndFillCell() {
for (String gear : new String[] {"gear6", "gear9"}) {
Shape s = PresetGeometry.build(gear, new int[0], 0, 0, 100, 100);
assertTrue(s.contains(50, 50), gear + ": центр залит");
Rectangle2D b = s.getBounds2D();
assertTrue(b.getWidth() > 85 && b.getHeight() > 90, gear + ": " + b);
}
}
/** avLst-override доходит до движка: толстая шестерня (adj1=20000) отличается от дефолта. */
@Test
void adjustOverrideChangesGear() {
Shape def = PresetGeometry.build("gear6", new int[0], 0, 0, 100, 100);
Shape thick = PresetGeometry.build("gear6", new int[] {20000, 3526}, 0, 0, 100, 100);
assertNotEquals(def.getBounds2D(), thick.getBounds2D());
assertTrue(thick.contains(50, 50));
}
@Test
void roundRectRoundsCorners() {
Shape s = PresetGeometry.build("roundRect", new int[0], 0, 0, 100, 100);
assertFalse(s.contains(1, 1), "угол срезан");
assertTrue(s.contains(1, 50), "середина стороны на месте");
}
@Test
void ellipseFitsCell() {
Shape s = PresetGeometry.build("ellipse", new int[0], 0, 0, 100, 100);
assertTrue(s.contains(50, 50));
assertFalse(s.contains(1, 1), "угол вне эллипса");
}
/** Смещение ячейки (a:xfrm/@off) транслирует построенную форму. */
@Test
void offsetTranslatesBuiltShape() {
Shape s = PresetGeometry.build("ellipse", new int[0], 10, 20, 100, 100);
Rectangle2D b = s.getBounds2D();
assertEquals(10, b.getMinX(), 1e-3);
assertEquals(20, b.getMinY(), 1e-3);
assertEquals(100, b.getWidth(), 1e-3);
assertEquals(100, b.getHeight(), 1e-3);
}
@Test
void unknownPresetFallsBackToCellRect() {
Shape s = PresetGeometry.build("bogusShape", new int[0], 5, 6, 70, 80);
Rectangle2D b = s.getBounds2D();
assertEquals(5, b.getX(), EPS);
assertEquals(6, b.getY(), EPS);
assertEquals(70, b.getWidth(), EPS);
assertEquals(80, b.getHeight(), EPS);
assertTrue(s.contains(5, 6));
}
@Test
void adjustValuesReadsValGuidesByPosition() {
CTPresetGeometry2D pg = new CTPresetGeometry2D();
CTGeomGuideList av = new CTGeomGuideList();
av.getGd().add(guide("adj1", "val 15000"));
av.getGd().add(guide("adj2", "ss 5"));
pg.setAvLst(av);
assertArrayEquals(new int[] {15000, 0}, PresetGeometry.adjustValues(pg));
assertEquals(0, PresetGeometry.adjustValues(new CTPresetGeometry2D()).length);
}
private static CTGeomGuide guide(String name, String fmla) {
CTGeomGuide g = new CTGeomGuide();
g.setName(name);
g.setFmla(fmla);
return g;
}
/** Точка на эллипсе (50±r) под углом deg (единичная конвенция ECMA: y вниз). */
private static boolean onRing(Shape s, double deg, double r) {
double t = Math.toRadians(deg);
return s.contains(50 + r * Math.cos(t), 50 + r * Math.sin(t));
}
/**
* Разбор блоков стандарта: для каждого поддерживаемого пресета —
* строки avLst/gdLst («name fmla») и команды pathLst в формате
* движка («moveTo x y», «arcTo wR hR stAng swAng», «close»).
*/
private static Map<String, PresetGeometry.Preset> parseEcmaXml() throws Exception {
XMLInputFactory f = XMLInputFactory.newFactory();
f.setProperty(XMLInputFactory.SUPPORT_DTD, false);
f.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
Map<String, PresetGeometry.Preset> out = new LinkedHashMap<>();
try (InputStream in = PresetGeometryTest.class.getResourceAsStream(
"/geom/presetShapeDefinitions.xml")) {
assertTrue(in != null, "ресурс geom/presetShapeDefinitions.xml не найден");
XMLStreamReader r = f.createXMLStreamReader(in);
int depth = 0;
String block = null;
String section = null;
List<String> av = new ArrayList<>();
List<String> gd = new ArrayList<>();
List<String> path = new ArrayList<>();
while (r.hasNext()) {
int ev = r.next();
if (ev == XMLStreamConstants.START_ELEMENT) {
depth++;
String ln = r.getLocalName();
if (depth == DEPTH_BLOCK && List.of(SUPPORTED).contains(ln)) {
block = ln;
av = new ArrayList<>();
gd = new ArrayList<>();
path = new ArrayList<>();
} else if (block != null && depth == DEPTH_SECTION) {
section = switch (ln) {
case "avLst", "gdLst", "pathLst" -> ln;
default -> null;
};
} else if (block != null && "gd".equals(ln) && section != null) {
String entry = r.getAttributeValue(null, "name") + " "
+ r.getAttributeValue(null, "fmla");
switch (section) {
case "avLst" -> av.add(entry);
default -> gd.add(entry);
}
} else if (block != null && "pathLst".equals(section)) {
switch (ln) {
case "moveTo", "lnTo" -> {
String[] pt = readPt(r);
path.add(ln + " " + pt[0] + " " + pt[1]);
}
case "arcTo" -> path.add("arcTo " + r.getAttributeValue(null, "wR")
+ " " + r.getAttributeValue(null, "hR")
+ " " + r.getAttributeValue(null, "stAng")
+ " " + r.getAttributeValue(null, "swAng"));
case "close" -> path.add("close");
default -> {
}
}
}
} else if (ev == XMLStreamConstants.END_ELEMENT) {
String ln = r.getLocalName();
if (depth == DEPTH_SECTION) {
section = null;
}
if (depth == DEPTH_BLOCK && ln.equals(block)) {
out.put(block, new PresetGeometry.Preset(
av.toArray(String[]::new),
gd.toArray(String[]::new),
path.toArray(String[]::new)));
block = null;
}
depth--;
}
}
}
return out;
}
/** Атрибуты x/y единственного <pt> внутри moveTo/lnTo; <pt/> закрывается здесь. */
private static String[] readPt(XMLStreamReader r) throws Exception {
while (r.hasNext()) {
if (r.next() == XMLStreamConstants.START_ELEMENT
&& "pt".equals(r.getLocalName())) {
String[] attrs = {
r.getAttributeValue(null, "x"),
r.getAttributeValue(null, "y"),
};
boolean closed = false;
while (!closed) {
closed = r.next() == XMLStreamConstants.END_ELEMENT
&& "pt".equals(r.getLocalName());
}
return attrs;
}
}
throw new IllegalStateException("у команды нет <pt>");
}
/** Формат движка: путь rect'а — ровно контур ячейки. */
@Test
void rectPathIsCellContour() {
PathIterator pi = PresetGeometry.build("rect", new int[0], 0, 0, 100, 100)
.getPathIterator(null);
double[] p = new double[6];
int segments = 0;
while (!pi.isDone()) {
if (pi.currentSegment(p) != PathIterator.SEG_CLOSE) {
segments++;
}
pi.next();
}
assertEquals(4, segments);
}
}
File diff suppressed because it is too large Load Diff