chart: линейчатая с накоплением — подписи категорий, порядок, заголовок #48

Merged
pjandro merged 1 commits from fix/horizontal-bar-labels-order into main 2026-10-25 20:28:08 +03:00
8 changed files with 295 additions and 35 deletions
Showing only changes of commit 7f0c7f1b73 - Show all commits
@@ -25,6 +25,7 @@ final class CartesianPainter {
boolean horizontal = spec.type == ChartSpec.Type.BAR_HORIZONTAL; boolean horizontal = spec.type == ChartSpec.Type.BAR_HORIZONTAL;
ChartSpec.AxisSpec valAxis = spec.valAxis != null ? spec.valAxis : new ChartSpec.AxisSpec(); ChartSpec.AxisSpec valAxis = spec.valAxis != null ? spec.valAxis : new ChartSpec.AxisSpec();
ChartSpec.AxisSpec catAxis = spec.catAxis != null ? spec.catAxis : new ChartSpec.AxisSpec(); ChartSpec.AxisSpec catAxis = spec.catAxis != null ? spec.catAxis : new ChartSpec.AxisSpec();
boolean catReversed = catAxis.reversed;
int nCat = 0; int nCat = 0;
for (ChartSpec.Series s : spec.series) { for (ChartSpec.Series s : spec.series) {
@@ -53,12 +54,25 @@ final class CartesianPainter {
DrawMlText.Style valStyle = valAxis.labelStyle; DrawMlText.Style valStyle = valAxis.labelStyle;
DrawMlText.Style catStyle = catAxis.labelStyle; DrawMlText.Style catStyle = catAxis.labelStyle;
// 1. Поля под подписи осей // 1. Поля под подписи осей. barDir=bar (горизонтальный): подписи категорий
// слева (у оси, выравнивание вправо), подписи значений сверху; вертикальный —
// значения слева, категории снизу. Раньше горизонтальный резервировал слева
// ширину подписей значений, а подписи категорий уезжали за край холста.
// Регрессия — CartesianPainterTest#horizontalBar_categoryLabelsVisible,
// фикстура samples/chart-types.docx (chart12).
double catGutter = 0; double catGutter = 0;
if (!cats.isEmpty()) { if (!cats.isEmpty()) {
catGutter = DrawMlText.textHeight(catStyle); catGutter = DrawMlText.textHeight(catStyle);
} }
catGutter += 6; // auto-layout Word: отступ от подписей до области (Word-эмпирика) catGutter += 6; // вертикальный: снизу (auto-layout Word-эмпирика, как раньше)
double catLabelGutter = 0; // горизонтальный: слева — ширина подписей категорий
if (!cats.isEmpty()) {
for (String label : cats) {
catLabelGutter = Math.max(catLabelGutter, DrawMlText.textWidth(label, catStyle));
}
}
catLabelGutter += 8;
// Word укрупняет шаг оси значений, если подписи не влезают: интервал // Word укрупняет шаг оси значений, если подписи не влезают: интервал
// между делениями не меньше ~2,5 высоты строки подписи. В word-export.pdf // между делениями не меньше ~2,5 высоты строки подписи. В word-export.pdf
@@ -68,7 +82,7 @@ final class CartesianPainter {
&& valAxis.majorUnit == null && valAxis.max == null) { && valAxis.majorUnit == null && valAxis.max == null) {
double labelH = DrawMlText.textHeight(valStyle); double labelH = DrawMlText.textHeight(valStyle);
double axisLen = Math.max(10, double axisLen = Math.max(10,
(horizontal ? box.getWidth() : box.getHeight()) - catGutter); horizontal ? box.getWidth() - catLabelGutter : box.getHeight() - catGutter);
while (hi - lo > unit && axisLen / ((hi - lo) / unit) < 2.5 * labelH) { while (hi - lo > unit && axisLen / ((hi - lo) / unit) < 2.5 * labelH) {
unit = ChartRenderer.nextUnit(unit); unit = ChartRenderer.nextUnit(unit);
double top = range[1] + (range[1] - range[0]) / 20.0; double top = range[1] + (range[1] - range[0]) / 20.0;
@@ -91,10 +105,14 @@ final class CartesianPainter {
} }
valGutter += 8; // auto-layout Word: отступ от подписей до области (Word-эмпирика) valGutter += 8; // auto-layout Word: отступ от подписей до области (Word-эмпирика)
// Горизонтальный: сверху подписи значений — резерв по высоте строки.
// Guard valStyle != null — регрессия CartesianPainterTest#nullValAxisSkipsValueLabels.
double topGutter = (valStyle != null ? DrawMlText.textHeight(valStyle) : 0) + 6;
Rectangle2D plot = horizontal Rectangle2D plot = horizontal
? new Rectangle2D.Double(box.getX() + valGutter, box.getY() + catGutter, ? new Rectangle2D.Double(box.getX() + catLabelGutter, box.getY() + topGutter,
Math.max(10, box.getWidth() - valGutter), Math.max(10, box.getWidth() - catLabelGutter),
Math.max(10, box.getHeight() - catGutter)) Math.max(10, box.getHeight() - topGutter))
: new Rectangle2D.Double(box.getX() + valGutter, box.getY(), : new Rectangle2D.Double(box.getX() + valGutter, box.getY(),
Math.max(10, box.getWidth() - valGutter), Math.max(10, box.getWidth() - valGutter),
Math.max(10, box.getHeight() - catGutter)); Math.max(10, box.getHeight() - catGutter));
@@ -119,9 +137,10 @@ final class CartesianPainter {
// 3. Ряды // 3. Ряды
switch (spec.type) { switch (spec.type) {
case LINE -> drawLines(g, spec, plot, palette, lo, hi, nCat, horizontal, cum); case LINE -> drawLines(g, spec, plot, palette, lo, hi, nCat, horizontal, catReversed, cum);
case AREA -> drawAreas(g, spec, plot, palette, lo, hi, nCat, horizontal); case AREA -> drawAreas(g, spec, plot, palette, lo, hi, nCat, horizontal, catReversed);
case BAR, BAR_HORIZONTAL -> drawBars(g, spec, plot, palette, lo, hi, nCat, horizontal, cum); case BAR, BAR_HORIZONTAL -> drawBars(g, spec, plot, palette, lo, hi, nCat,
horizontal, catReversed, cum);
default -> { default -> {
} }
} }
@@ -139,7 +158,7 @@ final class CartesianPainter {
plot.getX() + plot.getWidth(), y)); plot.getX() + plot.getWidth(), y));
} }
} }
drawCategoryLabels(g, cats, plot, catStyle, horizontal); drawCategoryLabels(g, cats, plot, catStyle, horizontal, catReversed);
drawValueLabels(g, valLabels, plot, valStyle, lo, hi, horizontal); drawValueLabels(g, valLabels, plot, valStyle, lo, hi, horizontal);
} }
@@ -161,7 +180,8 @@ final class CartesianPainter {
} }
private static void drawCategoryLabels(Graphics2D g, List<String> cats, Rectangle2D plot, private static void drawCategoryLabels(Graphics2D g, List<String> cats, Rectangle2D plot,
DrawMlText.Style style, boolean horizontal) { DrawMlText.Style style, boolean horizontal,
boolean reversed) {
if (style == null || cats.isEmpty()) { if (style == null || cats.isEmpty()) {
return; return;
} }
@@ -173,12 +193,13 @@ final class CartesianPainter {
continue; continue;
} }
if (horizontal) { if (horizontal) {
double cy = plot.getY() + plot.getHeight() * (i + 0.5) / n; double cy = catPos(i, (int) n, plot, true, reversed);
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, style, "ctr")), double w = DrawMlText.textWidth(label, style);
new Rectangle2D.Double(plot.getX() - 60, cy - h / 2, 56, h), DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, style, null)),
new Rectangle2D.Double(plot.getX() - 6 - w, cy - h / 2, w, h),
"r", "ctr", 1.0); "r", "ctr", 1.0);
} else { } else {
double cx = plot.getX() + plot.getWidth() * (i + 0.5) / n; double cx = catPos(i, (int) n, plot, false, reversed);
double w = DrawMlText.textWidth(label, style); double w = DrawMlText.textWidth(label, style);
double slot = plot.getWidth() / n; double slot = plot.getWidth() / n;
// Word прячет подписи, которые не помещаются в слот // Word прячет подписи, которые не помещаются в слот
@@ -206,6 +227,8 @@ final class CartesianPainter {
double w = DrawMlText.textWidth(labels.get(i), style); double w = DrawMlText.textWidth(labels.get(i), style);
if (horizontal) { if (horizontal) {
double x = plot.getX() + t * plot.getWidth(); double x = plot.getX() + t * plot.getWidth();
x = Math.max(plot.getX() + w / 2, Math.min(x,
plot.getX() + plot.getWidth() - w / 2));
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(labels.get(i), style, "ctr")), DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(labels.get(i), style, "ctr")),
new Rectangle2D.Double(x - w / 2, plot.getY() - h - 3, w, h), new Rectangle2D.Double(x - w / 2, plot.getY() - h - 3, w, h),
"ctr", "t", 1.0); "ctr", "t", 1.0);
@@ -226,16 +249,20 @@ final class CartesianPainter {
: plot.getY() + (1 - t) * plot.getHeight(); : plot.getY() + (1 - t) * plot.getHeight();
} }
private static double catPos(int i, int n, Rectangle2D plot, boolean horizontal) { private static double catPos(int i, int n, Rectangle2D plot, boolean horizontal,
boolean reversed) {
double t = (i + 0.5) / n; double t = (i + 0.5) / n;
if (reversed) {
t = 1 - t;
}
return horizontal return horizontal
? plot.getY() + t * plot.getHeight() ? plot.getY() + (1 - t) * plot.getHeight()
: plot.getX() + t * plot.getWidth(); : plot.getX() + t * plot.getWidth();
} }
private static void drawLines(Graphics2D g, ChartSpec spec, Rectangle2D plot, private static void drawLines(Graphics2D g, ChartSpec spec, Rectangle2D plot,
List<Color> palette, double lo, double hi, int nCat, List<Color> palette, double lo, double hi, int nCat,
boolean horizontal, double[][] cum) { boolean horizontal, boolean reversed, double[][] cum) {
for (int si = 0; si < spec.series.size(); si++) { for (int si = 0; si < spec.series.size(); si++) {
ChartSpec.Series s = spec.series.get(si); ChartSpec.Series s = spec.series.get(si);
Color c = s.lineColor != null ? s.lineColor : s.fillAt(si, palette); Color c = s.lineColor != null ? s.lineColor : s.fillAt(si, palette);
@@ -247,7 +274,7 @@ final class CartesianPainter {
List<Double> cross = new ArrayList<>(); List<Double> cross = new ArrayList<>();
if (cum != null) { if (cum != null) {
for (int i = 0; i < nCat; i++) { for (int i = 0; i < nCat; i++) {
along.add(catPos(i, nCat, plot, horizontal)); along.add(catPos(i, nCat, plot, horizontal, reversed));
cross.add(valuePos(cum[si][i], lo, hi, plot, horizontal)); cross.add(valuePos(cum[si][i], lo, hi, plot, horizontal));
} }
} else { } else {
@@ -256,7 +283,7 @@ final class CartesianPainter {
if (v == null) { if (v == null) {
continue; continue;
} }
along.add(catPos(i, nCat, plot, horizontal)); along.add(catPos(i, nCat, plot, horizontal, reversed));
cross.add(valuePos(v, lo, hi, plot, horizontal)); cross.add(valuePos(v, lo, hi, plot, horizontal));
} }
} }
@@ -287,7 +314,7 @@ final class CartesianPainter {
private static void drawAreas(Graphics2D g, ChartSpec spec, Rectangle2D plot, private static void drawAreas(Graphics2D g, ChartSpec spec, Rectangle2D plot,
List<Color> palette, double lo, double hi, int nCat, List<Color> palette, double lo, double hi, int nCat,
boolean horizontal) { boolean horizontal, boolean reversed) {
for (int si = 0; si < spec.series.size(); si++) { for (int si = 0; si < spec.series.size(); si++) {
ChartSpec.Series s = spec.series.get(si); ChartSpec.Series s = spec.series.get(si);
Color c = s.fill != null ? s.fill : s.fillAt(si, palette); Color c = s.fill != null ? s.fill : s.fillAt(si, palette);
@@ -298,7 +325,7 @@ final class CartesianPainter {
if (v == null) { if (v == null) {
continue; continue;
} }
along.add(catPos(i, nCat, plot, horizontal)); along.add(catPos(i, nCat, plot, horizontal, reversed));
cross.add(valuePos(v, lo, hi, plot, horizontal)); cross.add(valuePos(v, lo, hi, plot, horizontal));
} }
if (along.size() < MIN_POLYLINE_POINTS) { if (along.size() < MIN_POLYLINE_POINTS) {
@@ -339,7 +366,7 @@ final class CartesianPainter {
private static void drawBars(Graphics2D g, ChartSpec spec, Rectangle2D plot, private static void drawBars(Graphics2D g, ChartSpec spec, Rectangle2D plot,
List<Color> palette, double lo, double hi, int nCat, List<Color> palette, double lo, double hi, int nCat,
boolean horizontal, double[][] cum) { boolean horizontal, boolean reversed, double[][] cum) {
int nSer = spec.series.size(); int nSer = spec.series.size();
double slot = (horizontal ? plot.getHeight() : plot.getWidth()) / nCat; double slot = (horizontal ? plot.getHeight() : plot.getWidth()) / nCat;
if (cum != null) { if (cum != null) {
@@ -360,7 +387,7 @@ final class CartesianPainter {
} }
Color c = s.fillAt(i, palette); Color c = s.fillAt(i, palette);
g.setColor(c); g.setColor(c);
double center = catPos(i, nCat, plot, horizontal); double center = catPos(i, nCat, plot, horizontal, reversed);
double start = center - barW / 2; double start = center - barW / 2;
double prev = si == 0 ? 0 : cum[si - 1][i]; double prev = si == 0 ? 0 : cum[si - 1][i];
double p0 = valuePos(prev, lo, hi, plot, horizontal); double p0 = valuePos(prev, lo, hi, plot, horizontal);
@@ -399,7 +426,7 @@ final class CartesianPainter {
} }
Color c = s.fillAt(i, palette); Color c = s.fillAt(i, palette);
g.setColor(c); g.setColor(c);
double center = catPos(i, nCat, plot, horizontal); double center = catPos(i, nCat, plot, horizontal, reversed);
double start = center - groupW / 2 + si * step; double start = center - groupW / 2 + si * step;
double end = valuePos(v, lo, hi, plot, horizontal); double end = valuePos(v, lo, hi, plot, horizontal);
if (horizontal) { if (horizontal) {
@@ -139,23 +139,20 @@ final class ChartRenderer {
} }
} }
/** Заголовок сверху; возвращает занятую высоту. */ /** Заголовок сверху; возвращает занятую высоту (все строки переноса + отступ).
* Резервируется фактическое число строк жадного переноса — раньше резерв был
* ровно 2 строки, и заголовок в 3+ строки рисовался поверх области построения.
* Регрессия — ChartRendererTest#longTitle_reservesAllWrappedLines. */
private static double drawTitle(Graphics2D g, ChartSpec spec, Rectangle2D box) { private static double drawTitle(Graphics2D g, ChartSpec spec, Rectangle2D box) {
if (spec.title == null || spec.titleStyle == null) { if (spec.title == null || spec.titleStyle == null) {
return 0; return 0;
} }
double lineH = DrawMlText.textHeight(spec.titleStyle); double lineH = DrawMlText.textHeight(spec.titleStyle);
double width = DrawMlText.textWidth(spec.title, spec.titleStyle); int lines = DrawMlText.lineCount(spec.title, spec.titleStyle, box.getWidth());
double height = lineH + 4; double height = lines * lineH + 4;
if (width > box.getWidth()) {
DrawMlText.paint(g, List.of(new Paragraph(spec.title, spec.titleStyle, "ctr")),
new Rectangle2D.Double(box.getX(), box.getY(), box.getWidth(), height * 2),
"ctr", "t", 1.0);
return height * 2;
}
DrawMlText.paint(g, List.of(new Paragraph(spec.title, spec.titleStyle, "ctr")), DrawMlText.paint(g, List.of(new Paragraph(spec.title, spec.titleStyle, "ctr")),
new Rectangle2D.Double(box.getX(), box.getY(), box.getWidth(), height), new Rectangle2D.Double(box.getX(), box.getY(), box.getWidth(), height),
"ctr", "ctr", 1.0); "ctr", "t", 1.0);
return height; return height;
} }
@@ -52,6 +52,7 @@ import org.docx4j.dml.chart.CTTitle;
import org.docx4j.dml.chart.CTTx; import org.docx4j.dml.chart.CTTx;
import org.docx4j.dml.chart.CTValAx; import org.docx4j.dml.chart.CTValAx;
import org.docx4j.dml.chart.CTView3D; import org.docx4j.dml.chart.CTView3D;
import org.docx4j.dml.chart.STOrientation;
import java.awt.Color; import java.awt.Color;
import java.util.ArrayList; import java.util.ArrayList;
@@ -135,6 +136,9 @@ final class ChartSpec {
double axisLineWidth = 0.75; double axisLineWidth = 0.75;
DrawMlText.Style labelStyle; DrawMlText.Style labelStyle;
String numFmt = "General"; String numFmt = "General";
/** c:scaling/c:orientation=maxMin (ECMA-376 §21.2.2.130, ST_Orientation §21.2.3.30;
* MS-OI29500 §2.1.1511): значения оси в обратном порядке. */
boolean reversed;
} }
Type type = Type.UNSUPPORTED; Type type = Type.UNSUPPORTED;
@@ -834,6 +838,9 @@ final class ChartSpec {
if (scaling.getMax() != null) { if (scaling.getMax() != null) {
a.max = scaling.getMax().getVal(); a.max = scaling.getMax().getVal();
} }
if (scaling.getOrientation() != null && scaling.getOrientation().getVal() != null) {
a.reversed = scaling.getOrientation().getVal() == STOrientation.MAX_MIN;
}
} }
a.gridlines = grid != null; a.gridlines = grid != null;
if (grid != null && grid.getSpPr() != null && grid.getSpPr().getLn() != null if (grid != null && grid.getSpPr() != null && grid.getSpPr().getLn() != null
@@ -267,6 +267,11 @@ final class DrawMlText {
return fontFor(style).advance(text, style.sizePt()); return fontFor(style).advance(text, style.sizePt());
} }
/** Число строк после жадного переноса по ширине (та же разбивка, что в paint). */
static int lineCount(String text, Style style, double maxWidth) {
return wrapLines(text, fontFor(style), style.sizePt(), maxWidth).size();
}
/** Высота строки (ascent+descent+leading) для стиля. */ /** Высота строки (ascent+descent+leading) для стиля. */
static double textHeight(Style style) { static double textHeight(Style style) {
GlyphFont f = fontFor(style); GlyphFont f = fontFor(style);
@@ -677,4 +677,130 @@ class CartesianPainterTest {
} }
return new int[]{xs.get(0), xs.get(xs.size() / 2), xs.get(xs.size() - 1)}; return new int[]{xs.get(0), xs.get(xs.size() / 2), xs.get(xs.size() - 1)};
} }
/**
* barDir=bar: Word рисует категорию 0 внизу (ось категорий при дефолтном
* c:orientation=minMax идёт снизу-вверх, ECMA-376 §21.2.2.130, MS-OI29500
* §2.1.1511). Один ряд с per-point fill: RED — категория 0, BLUE — категория 1;
* вся красная полоса ниже всей синей.
* Регрессия — CartesianPainterTest#horizontalBar_categoriesBottomUp.
*/
@Test
void horizontalBar_categoriesBottomUp() {
BufferedImage img = ChartRenderer.render(horizontalCatSpec(), 219.23, 149.08,
new DrawMlColor(null));
int[] red = yStats(img, Color.RED);
int[] blue = yStats(img, Color.BLUE);
assertTrue(red[1] < NO_LINE, "красная полоса (категория 0) не найдена");
assertTrue(blue[1] < NO_LINE, "синяя полоса (категория 1) не найдена");
assertTrue(red[0] > blue[2],
"minMax: категория 0 (RED) должна быть ниже категории 1 (BLUE): redMinY="
+ red[0] + ", blueMaxY=" + blue[2]);
}
/** c:orientation=maxMin (§21.2.2.130) переворачивает порядок: категория 0 сверху. */
@Test
void horizontalBar_reversedOrientation_categoriesTopDown() {
ChartSpec spec = horizontalCatSpec();
spec.catAxis.reversed = true;
BufferedImage img = ChartRenderer.render(spec, 219.23, 149.08,
new DrawMlColor(null));
int[] red = yStats(img, Color.RED);
int[] blue = yStats(img, Color.BLUE);
assertTrue(red[1] < NO_LINE, "красная полоса не найдена");
assertTrue(blue[1] < NO_LINE, "синяя полоса не найдена");
assertTrue(blue[0] > red[2],
"maxMin: категория 1 (BLUE) должна быть ниже категории 0 (RED): blueMinY="
+ blue[0] + ", redMaxY=" + red[2]);
}
/**
* barDir=bar: подписи категорий (Q1/Q2/Q3) видны слева от оси. Раньше в
* Paragraph был захардкожен align="ctr", перекрывающий defAlign="r": текст
* центрировался в боксе левее области и уходил за левый край холста.
* Считаем серый подписи (0x595959) в регионе слева от области построения.
* Регрессия — CartesianPainterTest#horizontalBar_categoryLabelsVisible,
* фикстура samples/chart-types.docx (chart12).
*/
@Test
void horizontalBar_categoryLabelsVisible() {
BufferedImage img = ChartRenderer.render(horizontalLabelSpec(), 219.23, 149.08,
new DrawMlColor(null));
Color label = new Color(0x59, 0x59, 0x59);
int gray = 0;
for (int y = img.getHeight() / 2; y < img.getHeight(); y++) {
for (int x = 0; x < img.getWidth() / 4; x++) {
if (closeTo(img.getRGB(x, y), label, 40)) {
gray++;
}
}
}
assertTrue(gray >= 10, "подписей категорий слева от оси нет: " + gray + " px");
}
/** Крайняя подпись оси значений («15») не обрезается правым краем холста. */
@Test
void horizontalBar_lastValueLabelNotClipped() {
BufferedImage img = ChartRenderer.render(horizontalLabelSpec(), 219.23, 149.08,
new DrawMlColor(null));
Color label = new Color(0x59, 0x59, 0x59);
for (int y = 0; y < img.getHeight(); y++) {
for (int x = img.getWidth() - 2; x < img.getWidth(); x++) {
assertFalse(closeTo(img.getRGB(x, y), label, 40),
"подпись обрезана правым краем холста, пиксель (" + x + "," + y + ")");
}
}
}
/** Горизонтальный ряд: RED=категория 0, BLUE=категория 1, категории A/B. */
private static ChartSpec horizontalCatSpec() {
ChartSpec spec = new ChartSpec();
spec.type = ChartSpec.Type.BAR_HORIZONTAL;
spec.legendPos = null;
DrawMlText.Style style = new DrawMlText.Style(9, false, false,
new Color(0x59, 0x59, 0x59), "carlito");
spec.catAxis = new ChartSpec.AxisSpec();
spec.catAxis.labelStyle = style;
spec.valAxis = new ChartSpec.AxisSpec();
spec.valAxis.labelStyle = style;
spec.categories.add("A");
spec.categories.add("B");
ChartSpec.Series s = new ChartSpec.Series();
s.values.add(5.0);
s.values.add(5.0);
s.pointFills.put(0, Color.RED);
s.pointFills.put(1, Color.BLUE);
spec.series.add(s);
return spec;
}
/** Горизонтальный ряд Q1..Q3 со значениями до 15 (как chart12). */
private static ChartSpec horizontalLabelSpec() {
ChartSpec spec = new ChartSpec();
spec.type = ChartSpec.Type.BAR_HORIZONTAL;
spec.legendPos = null;
DrawMlText.Style style = new DrawMlText.Style(9, false, false,
new Color(0x59, 0x59, 0x59), "carlito");
spec.catAxis = new ChartSpec.AxisSpec();
spec.catAxis.labelStyle = style;
spec.valAxis = new ChartSpec.AxisSpec();
spec.valAxis.labelStyle = style;
spec.categories.add("Q1");
spec.categories.add("Q2");
spec.categories.add("Q3");
ChartSpec.Series s = new ChartSpec.Series();
s.values.add(5.0);
s.values.add(8.0);
s.values.add(15.0);
spec.series.add(s);
return spec;
}
/** Пиксель близок к target (дельта каналов < maxDelta). */
private static boolean closeTo(int rgb, Color target, int maxDelta) {
int dr = Math.abs(((rgb >> 16) & 0xFF) - target.getRed());
int dg = Math.abs(((rgb >> 8) & 0xFF) - target.getGreen());
int db = Math.abs((rgb & 0xFF) - target.getBlue());
return Math.max(Math.max(dr, dg), db) < maxDelta;
}
} }
@@ -478,4 +478,59 @@ class ChartRendererTest {
} }
return false; return false;
} }
/**
* Заголовок в 3 строки переноса резервирует фактическую высоту: бар
* начинается ниже трёхстрочной полосы. Раньше резерв был ровно 2 строки,
* и третья строка рисовалась поверх области построения.
* Регрессия — ChartRendererTest#longTitle_reservesAllWrappedLines.
*/
@Test
void longTitle_reservesAllWrappedLines() {
ChartSpec spec = new ChartSpec();
spec.type = ChartSpec.Type.BAR;
spec.legendPos = null;
DrawMlText.Style axisStyle = new DrawMlText.Style(9, false, false,
new Color(0x59, 0x59, 0x59), "carlito");
spec.catAxis = new ChartSpec.AxisSpec();
spec.catAxis.labelStyle = axisStyle;
spec.valAxis = new ChartSpec.AxisSpec();
spec.valAxis.labelStyle = axisStyle;
DrawMlText.Style style = new DrawMlText.Style(14, false, false,
new Color(0x59, 0x59, 0x59), "carlito");
spec.titleStyle = style;
spec.title = "Очень длинное название диаграммы которое не должно помещаться "
+ "в две строки и поэтому обязано занять три или четыре строки";
assertEquals(3, DrawMlText.lineCount(spec.title, style, 360 - 2 * 4),
"заголовок должен переноситься ровно в 3 строки при ширине бокса");
ChartSpec.Series s = new ChartSpec.Series();
s.fill = new Color(68, 114, 196);
s.values.add(5.0);
s.values.add(5.0);
spec.series.add(s);
BufferedImage img = ChartRenderer.render(spec, 360, 216, new DrawMlColor(null));
int minY = -1;
outer:
for (int y = 0; y < img.getHeight(); y++) {
for (int x = 0; x < img.getWidth(); x++) {
if (isBarFill(img.getRGB(x, y))) {
minY = y;
break outer;
}
}
}
assertTrue(minY >= 0, "заливки бара не найдено");
double threeLineBand = (4 + 3 * DrawMlText.textHeight(style))
* ChartRenderer.DPI / 72.0 - 1;
assertTrue(minY >= threeLineBand,
"бар начинается в полосе заголовка: minY=" + minY
+ ", нижний край трёхстрочной полосы=" + threeLineBand);
}
/** Пиксель — заливка ряда (0x4472C4) с запасом на AA-края. */
private static boolean isBarFill(int rgb) {
return Math.abs(((rgb >> 16) & 0xFF) - 68) < 30
&& Math.abs(((rgb >> 8) & 0xFF) - 114) < 30
&& Math.abs((rgb & 0xFF) - 196) < 30;
}
} }
@@ -53,6 +53,8 @@ import org.docx4j.dml.chart.CTLine3DChart;
import org.docx4j.dml.chart.CTPieChart; import org.docx4j.dml.chart.CTPieChart;
import org.docx4j.dml.chart.CTPlotArea; import org.docx4j.dml.chart.CTPlotArea;
import org.docx4j.dml.chart.CTScaling; import org.docx4j.dml.chart.CTScaling;
import org.docx4j.dml.chart.CTOrientation;
import org.docx4j.dml.chart.STOrientation;
import org.docx4j.dml.chart.CTOfPieChart; import org.docx4j.dml.chart.CTOfPieChart;
import org.docx4j.dml.chart.CTOfPieType; import org.docx4j.dml.chart.CTOfPieType;
import org.docx4j.dml.chart.CTPerspective; import org.docx4j.dml.chart.CTPerspective;
@@ -1509,6 +1511,37 @@ class ChartSpecTest {
() -> ChartSpec.parse(spaceWith(ct), new DrawMlColor(null))); () -> ChartSpec.parse(spaceWith(ct), new DrawMlColor(null)));
} }
/**
* c:scaling/c:orientation (ECMA-376 §21.2.2.130, ST_Orientation §21.2.3.30):
* maxMin → reversed; minMax и отсутствие элемента — прямое направление.
* Регрессия — ChartSpecTest#catAxOrientationMaxMin_reversedParsed.
*/
@Test
void catAxOrientationMaxMin_reversedParsed() {
assertTrue(ChartSpec.parse(spaceWith(chartWithCatOrientation(STOrientation.MAX_MIN)),
new DrawMlColor(null)).catAxis.reversed, "maxMin должен взводить reversed");
assertFalse(ChartSpec.parse(spaceWith(chartWithCatOrientation(STOrientation.MIN_MAX)),
new DrawMlColor(null)).catAxis.reversed, "minMax — дефолтное направление");
assertFalse(ChartSpec.parse(spaceWith(chartWithCatOrientation(null)),
new DrawMlColor(null)).catAxis.reversed, "нет c:orientation — дефолтное направление");
}
private static CTChart chartWithCatOrientation(STOrientation orientation) {
CTChart chart = new CTChart();
CTPlotArea pa = new CTPlotArea();
CTCatAx cat = new CTCatAx();
CTScaling scaling = new CTScaling();
if (orientation != null) {
CTOrientation o = new CTOrientation();
o.setVal(orientation);
scaling.setOrientation(o);
}
cat.setScaling(scaling);
pa.getValAxOrCatAxOrDateAx().add(cat);
chart.setPlotArea(pa);
return chart;
}
private static CTNumData numCache(double... vals) { private static CTNumData numCache(double... vals) {
CTNumData cache = new CTNumData(); CTNumData cache = new CTNumData();
for (int i = 0; i < vals.length; i++) { for (int i = 0; i < vals.length; i++) {
@@ -276,4 +276,14 @@ class DrawMlTextTest {
new Rectangle2D.Double(0, 0, 50, 40), null, "t"); new Rectangle2D.Double(0, 0, 50, 40), null, "t");
assertEquals(0, inkBands(blank), "пробельный абзац — чернил нет"); assertEquals(0, inkBands(blank), "пробельный абзац — чернил нет");
} }
/** lineCount — та же жадная разбивка, что в paint: 1/2/3 строки при 100 pt. */
@Test
void lineCount_wraps() {
DrawMlText.Style s = new DrawMlText.Style(9, false, false, Color.BLACK, "carlito");
assertEquals(1, DrawMlText.lineCount("short", s, 100));
assertEquals(2, DrawMlText.lineCount("альфа бета гамма дельта эпсилон", s, 100));
assertEquals(3, DrawMlText.lineCount(
"альфа бета гамма дельта эпсилон зета эта йота капа лямбда", s, 100));
}
} }