chart: ofPie по Word — «Other»-сектор, две связи c:serLines, центрирование пары (MS-OI29500 §2.1.1507(a)/§2.1.1545(a))
PR checks / web (pull_request) Successful in 32s
PR checks / java (pull_request) Successful in 1m27s
Main: tests, deploy, autotests / web (push) Successful in 31s
Main: tests, deploy, autotests / images-web (push) Successful in 30s
Main: tests, deploy, autotests / java (push) Successful in 1m40s
Main: tests, deploy, autotests / images-app (push) Successful in 43s
Main: tests, deploy, autotests / deploy (push) Successful in 1m32s
Main: tests, deploy, autotests / autotests (push) Successful in 57s
Main: tests, deploy, autotests / rollback (push) Has been skipped

This commit was merged in pull request #46.
This commit is contained in:
Pjandro
2026-10-25 16:15:58 +00:00
parent c7af4185cc
commit 3d77cc5034
6 changed files with 359 additions and 80 deletions
@@ -11,9 +11,10 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Генератор фикстуры {@code samples/chart-types.docx}: 10 диаграмм: 9 типов,
* Генератор фикстуры {@code samples/chart-types.docx}: 11 диаграмм: 9 типов,
* которых POI не пишет (scatter, bubble, radar, stock, ofPie, bar3D,
* area3D, line3D, surface2D), + lineChart с c:grouping=stacked — chart-XML
* area3D, line3D, surface2D), + ofPie pie-вариант + lineChart с
* c:grouping=stacked — chart-XML
* литералами по ECMA-376 §21.2
* (фикстура проходит docs/standards/validate-fixtures.py). Регрессия —
* WordPdfConverterTest#chartTypes_allTypesRenderAsImages.
@@ -37,7 +38,8 @@ public final class ChartTypesDocxGenerator {
List<String> titles = List.of(
"Точечная", "Пузырьковая", "Лепестковая", "Биржевая",
"Кольцевая-доля", "Объёмная с столбцами", "Объёмная с областями",
"Объёмная с линиями", "Поверхность", "График с накоплением");
"Объёмная с линиями", "Поверхность", "График с накоплением",
"Вторичная круговая");
List<String> charts = new ArrayList<>();
charts.add(scatter());
charts.add(bubble());
@@ -49,6 +51,7 @@ public final class ChartTypesDocxGenerator {
charts.add(line3d());
charts.add(surface());
charts.add(stackedLine());
charts.add(ofPiePie());
StringBuilder body = new StringBuilder();
body.append("<w:p><w:r><w:t>Типы диаграмм</w:t></w:r></w:p>");
@@ -171,6 +174,15 @@ public final class ChartTypesDocxGenerator {
+ "</c:ofPieChart>";
}
private static String ofPiePie() {
return "<c:ofPieChart><c:ofPieType val=\"pie\"/><c:varyColors val=\"1\"/>"
+ ser("Доли", cat("Север", "Юг", "Восток", "Запад", "Центр"),
num("40", "25", "18", "10", "7"))
+ "<c:splitType val=\"pos\"/><c:splitPos val=\"2\"/>"
+ "<c:serLines/>"
+ "</c:ofPieChart>";
}
private static String bar3d() {
return "<c:bar3DChart><c:barDir val=\"col\"/><c:grouping val=\"clustered\"/><c:varyColors val=\"0\"/>"
+ ser("План", cat("Q1", "Q2", "Q3"), num("5", "9", "7"))
@@ -171,9 +171,10 @@ class WordPdfConverterTest {
/**
* Фикстура chart-types.docx (создана вручную, chart-XML литералами — POI
* эти типы не пишет): все десять типов — точечная, пузырьковая,
* эти типы не пишет): все одиннадцать — точечная, пузырьковая,
* лепестковая, биржевая, кольцевая-доля, три объёмных декартовых,
* поверхность и график с накоплением (c:grouping=stacked, §21.2.2.76) —
* поверхность, график с накоплением (c:grouping=stacked, §21.2.2.76)
* и pie-вариант кольцевой-доли (c:ofPieType="pie") —
* рендерятся в растр, а не удаляются с warn.
* Регрессия — WordPdfConverterTest#chartTypes_allTypesRenderAsImages.
*/
@@ -183,8 +184,8 @@ class WordPdfConverterTest {
String text = norm(pdfText(pdf));
assertTrue(text.contains("Типы диаграмм"), "пропал текст: " + text);
assertEquals(10, distinctImageCount(pdf),
"каждый из 10 графиков должен стать PNG-вставкой");
assertEquals(11, distinctImageCount(pdf),
"каждый из 11 графиков должен стать PNG-вставкой");
}
/**
@@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@@ -18,10 +19,15 @@ class OfPiePainterTest {
private static final Color ACCENT1 = new Color(0x4472C4);
private static final Color ACCENT2 = new Color(0xED7D31);
private static final Color ACCENT4 = new Color(0xFF, 0xC0, 0x00);
private static final Color ACCENT5 = new Color(0x5B, 0x9B, 0xD5);
/** «Цветной» px — разброс каналов (как в пиксельных тестах chart-пейнтеров). */
private static final int GRAY_MAX_SPREAD = 25;
/** Склейка разорванных антиалиасингом интервалов одного объекта (px). */
private static final int MERGE_GAP_PX = 3;
/** cust-разбиение: заданные точки — во вторичном кластере справа. */
@Test
void custSplit_movesListedPointsToSecondary() {
@@ -74,6 +80,115 @@ class OfPiePainterTest {
"c:serLines не нарисована");
}
/** «Other»-сектор замыкает главный пирог (MS-OI29500 §2.1.1507(a)). */
@Test
void otherSlice_mainPieClosed() {
ChartSpec spec = ofPieSpec("cust", null);
spec.secondPiePts.add(1);
spec.secondPiePts.add(2);
BufferedImage img = render(spec);
assertTrue(countColor(img, ACCENT5) > 3000,
"главный пирог не замкнут «Other»-сектором (§2.1.1507(a))");
}
/** Центр «Other»-сектора — 3 часа: сектор обращён ко вторичной (§2.1.1507(a)). */
@Test
void otherWedge_facesRight() {
ChartSpec spec = ofPieSpec("cust", null);
spec.secondPiePts.add(1);
spec.secondPiePts.add(2);
BufferedImage img = render(spec);
double[] other = centroid(img, ACCENT5, 0);
double[] left = saturatedCentroid(img, 0, img.getWidth() / 2);
assertTrue(other[0] > left[0], "«Other»-сектор не справа от первичных секторов");
assertTrue(Math.abs(other[1] - img.getHeight() / 2.0) < 0.2 * img.getHeight(),
"центр «Other»-сектора не на 3 часах");
}
/** c:serLines — ровно две связи от границ «Other»-сектора (§2.1.1545(a)). */
@Test
void serLines_twoConnectors() {
ChartSpec spec = ofPieSpec("cust", null);
spec.series.get(0).values.add(5.0);
// accent3 (A5A5A5) совпал бы с цветом serLines по допуску — перекрашиваем точку 2
spec.series.get(0).pointFills.put(2, new Color(0, 0xB0, 0x50));
spec.secondPiePts.add(1);
spec.secondPiePts.add(2);
spec.secondPiePts.add(4);
spec.serLines = true;
BufferedImage img = render(spec);
assertEquals(2, runsAt(img, gapMid(img), OfPiePainter.SER_LINE_COLOR),
"в разрыве между тортами должно быть ровно 2 связи");
assertTrue(countColor(img, OfPiePainter.SER_LINE_COLOR) < 3000,
"c:serLines рисуется веером, а не двумя связями (§2.1.1545(a))");
}
/** Связи крепятся к левому ободу вторичного пирога, а не к серединам секторов. */
@Test
void serLines_attachToLeftRimOnly() {
ChartSpec spec = ofPieSpec("cust", null);
spec.series.get(0).values.add(5.0);
spec.series.get(0).pointFills.put(2, new Color(0, 0xB0, 0x50));
spec.secondPiePts.add(1);
spec.secondPiePts.add(2);
spec.secondPiePts.add(4);
spec.serLines = true;
BufferedImage img = render(spec);
double[] center = saturatedCentroid(img, gapMid(img) + 1, img.getWidth());
assertTrue(maxXOfColor(img, OfPiePainter.SER_LINE_COLOR) <= center[0] + 3,
"связи уходят за вертикаль центра вторичного пирога");
}
/** Вторичный пирог: сектора в порядке данных от конца «Other»-сектора. */
@Test
void secondaryPie_slicesInDataOrderFromWedgeEnd() {
ChartSpec spec = ofPieSpec("cust", null);
spec.series.get(0).values.clear();
spec.series.get(0).values.addAll(List.of(40.0, 25.0, 18.0, 10.0, 7.0));
spec.secondPiePts.add(3);
spec.secondPiePts.add(4);
BufferedImage img = render(spec);
int mid = gapMid(img);
double[] center = saturatedCentroid(img, mid + 1, img.getWidth());
double[] s3 = centroid(img, ACCENT4, mid + 1);
double[] s4 = centroid(img, ACCENT5, mid + 1);
assertEquals(226.5, angleDeg(center[0], center[1], s3[0], s3[1]), 20.0,
"сектор точки 3 не на биссектрисе 226.5° (старт не от конца «Other»?)");
assertEquals(46.5, angleDeg(center[0], center[1], s4[0], s4[1]), 20.0,
"сектор точки 4 не на биссектрисе 46.5° (старт не от конца «Other»?)");
}
/** Пара пирогов центрирована горизонтально (как в Word). */
@Test
void pairCentered_horizontally() {
ChartSpec spec = ofPieSpec("cust", null);
spec.secondPiePts.add(1);
spec.secondPiePts.add(2);
BufferedImage img = render(spec);
int leftGap = saturatedMinX(img);
int rightGap = img.getWidth() - 1 - saturatedMaxX(img);
assertTrue(Math.abs(leftGap - rightGap) < 0.1 * img.getWidth(),
"пара не центрирована: left=" + leftGap + ", right=" + rightGap);
}
/** bar-вариант: связи к левым углам столбца, ровно две (§2.1.1545(a)). */
@Test
void serLines_bar_attachToBarLeftCorners() {
ChartSpec spec = ofPieSpec("cust", null);
spec.ofPieType = "bar";
spec.series.get(0).values.clear();
spec.series.get(0).values.addAll(List.of(40.0, 25.0, 18.0, 10.0, 7.0));
spec.secondPiePts.add(3);
spec.secondPiePts.add(4);
spec.serLines = true;
BufferedImage img = render(spec);
int barLeft = rightMinX(img);
assertTrue(maxXOfColor(img, OfPiePainter.SER_LINE_COLOR) <= barLeft + 3,
"связи уходят в столбец, а не крепятся к его левому краю");
assertEquals(2, runsAt(img, gapMid(img), OfPiePainter.SER_LINE_COLOR),
"в разрыве должно быть ровно 2 связи");
}
private static ChartSpec ofPieSpec(String splitType, Double splitPos) {
ChartSpec spec = new ChartSpec();
spec.type = ChartSpec.Type.OF_PIE;
@@ -125,11 +240,7 @@ class OfPiePainterTest {
int max = -1;
for (int y = 0; y < img.getHeight(); y++) {
for (int x = 0; x < img.getWidth(); x++) {
int rgb = img.getRGB(x, y);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
if (Math.max(Math.max(r, g), b) - Math.min(Math.min(r, g), b) > GRAY_MAX_SPREAD) {
if (saturated(img.getRGB(x, y))) {
min = Math.min(min, x);
max = Math.max(max, x);
}
@@ -150,6 +261,146 @@ class OfPiePainterTest {
return n;
}
/** Насыщенный px — разброс каналов > GRAY_MAX_SPREAD (серый/белый/чёрный — нет). */
private static boolean saturated(int rgb) {
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = rgb & 0xFF;
return Math.max(Math.max(r, g), b) - Math.min(Math.min(r, g), b) > GRAY_MAX_SPREAD;
}
/** Средний px цвета c среди x ≥ xFrom. */
private static double[] centroid(BufferedImage img, Color c, int xFrom) {
double sx = 0;
double sy = 0;
long n = 0;
for (int y = 0; y < img.getHeight(); y++) {
for (int x = xFrom; x < img.getWidth(); x++) {
if (matches(img.getRGB(x, y), c)) {
sx += x;
sy += y;
n++;
}
}
}
assertTrue(n > 100, "нет пикселей цвета " + c);
return new double[]{sx / n, sy / n};
}
/** Центроид насыщенных px в полосе xFrom ≤ x < xTo. */
private static double[] saturatedCentroid(BufferedImage img, int xFrom, int xTo) {
double sx = 0;
double sy = 0;
long n = 0;
for (int y = 0; y < img.getHeight(); y++) {
for (int x = xFrom; x < xTo; x++) {
if (saturated(img.getRGB(x, y))) {
sx += x;
sy += y;
n++;
}
}
}
assertTrue(n > 100, "нет насыщенных пикселей в полосе");
return new double[]{sx / n, sy / n};
}
private static boolean columnHasSaturated(BufferedImage img, int x) {
for (int y = 0; y < img.getHeight(); y++) {
if (saturated(img.getRGB(x, y))) {
return true;
}
}
return false;
}
/** Середина наибольшего внутреннего разрыва (столбцы без насыщенных px). */
private static int gapMid(BufferedImage img) {
int w = img.getWidth();
int bestA = -1;
int bestLen = 0;
int a = -1;
for (int x = 0; x <= w; x++) {
boolean empty = x < w && !columnHasSaturated(img, x);
if (empty && a < 0) {
a = x;
}
if (!empty && a >= 0) {
if (a > 0 && x < w && x - a > bestLen) {
bestLen = x - a;
bestA = a;
}
a = -1;
}
}
assertTrue(bestLen > 0, "нет внутреннего разрыва между тортами");
return bestA + bestLen / 2;
}
/** Первый насыщенный столбец правее разрыва. */
private static int rightMinX(BufferedImage img) {
for (int x = gapMid(img); x < img.getWidth(); x++) {
if (columnHasSaturated(img, x)) {
return x;
}
}
throw new AssertionError("правее разрыва нет насыщенных пикселей");
}
/** Число y-интервалов цвета c в колонке x (склейка зазоров ≤ 3 px). */
private static int runsAt(BufferedImage img, int x, Color c) {
int runs = 0;
int gap = MERGE_GAP_PX + 1;
for (int y = 0; y < img.getHeight(); y++) {
if (matches(img.getRGB(x, y), c)) {
if (gap > MERGE_GAP_PX) {
runs++;
}
gap = 0;
} else {
gap++;
}
}
return runs;
}
private static int maxXOfColor(BufferedImage img, Color c) {
int max = -1;
for (int y = 0; y < img.getHeight(); y++) {
for (int x = img.getWidth() - 1; x > max; x--) {
if (matches(img.getRGB(x, y), c)) {
max = x;
break;
}
}
}
return max;
}
private static int saturatedMinX(BufferedImage img) {
for (int x = 0; x < img.getWidth(); x++) {
if (columnHasSaturated(img, x)) {
return x;
}
}
throw new AssertionError("нет насыщенных пикселей");
}
private static int saturatedMaxX(BufferedImage img) {
for (int x = img.getWidth() - 1; x >= 0; x--) {
if (columnHasSaturated(img, x)) {
return x;
}
}
throw new AssertionError("нет насыщенных пикселей");
}
/** Word-угол точки (x, y) от центра: 0 = 12 часов, по часовой. */
private static double angleDeg(double cx, double cy, double x, double y) {
double a = Math.toDegrees(Math.atan2(x - cx, cy - y));
return a < 0 ? a + 360 : a;
}
private static boolean matches(int rgb, Color c) {
return Math.abs(((rgb >> 16) & 0xFF) - c.getRed()) <= 24
&& Math.abs(((rgb >> 8) & 0xFF) - c.getGreen()) <= 24