chart: barDir=bar по Word — подписи категорий слева, категория 0 внизу, заголовок резервирует все строки
PR checks / web (pull_request) Successful in 31s
PR checks / java (pull_request) Successful in 1m33s
Main: tests, deploy, autotests / web (push) Successful in 32s
Main: tests, deploy, autotests / images-web (push) Successful in 31s
Main: tests, deploy, autotests / java (push) Successful in 1m28s
Main: tests, deploy, autotests / images-app (push) Successful in 56s
Main: tests, deploy, autotests / deploy (push) Successful in 3m21s
Main: tests, deploy, autotests / autotests (push) Failing after 2m7s
Main: tests, deploy, autotests / rollback (push) Successful in 3m9s

- CartesianPainter: горизонтальный layout — резерв catLabelGutter слева под
  подписи категорий и topGutter сверху под подписи значений; подписи категорий
  вправо к оси (Paragraph align=null вместо «ctr», перекрывавшего defAlign);
  крайняя подпись значений клиппуется внутрь plot
- catPos: minMax → категория 0 внизу, парсинг c:orientation=maxMin (§21.2.2.130,
  ST_Orientation §21.2.3.30, MS-OI29500 §2.1.1511) → AxisSpec.reversed
- ChartRenderer.drawTitle: резерв = фактическое число строк жадного переноса
  (DrawMlText.lineCount), а не ровно 2 — заголовок 3+ строк больше не лезет
  на область построения
- регрессии: horizontalBar_categoriesBottomUp,
  horizontalBar_reversedOrientation_categoriesTopDown,
  horizontalBar_categoryLabelsVisible, horizontalBar_lastValueLabelNotClipped,
  longTitle_reservesAllWrappedLines, lineCount_wraps,
  catAxOrientationMaxMin_reversedParsed
This commit was merged in pull request #48.
This commit is contained in:
Pjandro
2026-10-25 17:26:23 +00:00
parent ce3fc813ce
commit 7f0c7f1b73
8 changed files with 295 additions and 35 deletions
@@ -25,6 +25,7 @@ final class CartesianPainter {
boolean horizontal = spec.type == ChartSpec.Type.BAR_HORIZONTAL;
ChartSpec.AxisSpec valAxis = spec.valAxis != null ? spec.valAxis : new ChartSpec.AxisSpec();
ChartSpec.AxisSpec catAxis = spec.catAxis != null ? spec.catAxis : new ChartSpec.AxisSpec();
boolean catReversed = catAxis.reversed;
int nCat = 0;
for (ChartSpec.Series s : spec.series) {
@@ -53,12 +54,25 @@ final class CartesianPainter {
DrawMlText.Style valStyle = valAxis.labelStyle;
DrawMlText.Style catStyle = catAxis.labelStyle;
// 1. Поля под подписи осей
// 1. Поля под подписи осей. barDir=bar (горизонтальный): подписи категорий
// слева (у оси, выравнивание вправо), подписи значений сверху; вертикальный —
// значения слева, категории снизу. Раньше горизонтальный резервировал слева
// ширину подписей значений, а подписи категорий уезжали за край холста.
// Регрессия — CartesianPainterTest#horizontalBar_categoryLabelsVisible,
// фикстура samples/chart-types.docx (chart12).
double catGutter = 0;
if (!cats.isEmpty()) {
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 укрупняет шаг оси значений, если подписи не влезают: интервал
// между делениями не меньше ~2,5 высоты строки подписи. В word-export.pdf
@@ -68,7 +82,7 @@ final class CartesianPainter {
&& valAxis.majorUnit == null && valAxis.max == null) {
double labelH = DrawMlText.textHeight(valStyle);
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) {
unit = ChartRenderer.nextUnit(unit);
double top = range[1] + (range[1] - range[0]) / 20.0;
@@ -91,10 +105,14 @@ final class CartesianPainter {
}
valGutter += 8; // auto-layout Word: отступ от подписей до области (Word-эмпирика)
// Горизонтальный: сверху подписи значений — резерв по высоте строки.
// Guard valStyle != null — регрессия CartesianPainterTest#nullValAxisSkipsValueLabels.
double topGutter = (valStyle != null ? DrawMlText.textHeight(valStyle) : 0) + 6;
Rectangle2D plot = horizontal
? new Rectangle2D.Double(box.getX() + valGutter, box.getY() + catGutter,
Math.max(10, box.getWidth() - valGutter),
Math.max(10, box.getHeight() - catGutter))
? new Rectangle2D.Double(box.getX() + catLabelGutter, box.getY() + topGutter,
Math.max(10, box.getWidth() - catLabelGutter),
Math.max(10, box.getHeight() - topGutter))
: new Rectangle2D.Double(box.getX() + valGutter, box.getY(),
Math.max(10, box.getWidth() - valGutter),
Math.max(10, box.getHeight() - catGutter));
@@ -119,9 +137,10 @@ final class CartesianPainter {
// 3. Ряды
switch (spec.type) {
case LINE -> drawLines(g, spec, plot, palette, lo, hi, nCat, horizontal, cum);
case AREA -> drawAreas(g, spec, plot, palette, lo, hi, nCat, horizontal);
case BAR, BAR_HORIZONTAL -> drawBars(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, catReversed);
case BAR, BAR_HORIZONTAL -> drawBars(g, spec, plot, palette, lo, hi, nCat,
horizontal, catReversed, cum);
default -> {
}
}
@@ -139,7 +158,7 @@ final class CartesianPainter {
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);
}
@@ -161,7 +180,8 @@ final class CartesianPainter {
}
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()) {
return;
}
@@ -173,12 +193,13 @@ final class CartesianPainter {
continue;
}
if (horizontal) {
double cy = plot.getY() + plot.getHeight() * (i + 0.5) / n;
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, style, "ctr")),
new Rectangle2D.Double(plot.getX() - 60, cy - h / 2, 56, h),
double cy = catPos(i, (int) n, plot, true, reversed);
double w = DrawMlText.textWidth(label, style);
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);
} 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 slot = plot.getWidth() / n;
// Word прячет подписи, которые не помещаются в слот
@@ -206,6 +227,8 @@ final class CartesianPainter {
double w = DrawMlText.textWidth(labels.get(i), style);
if (horizontal) {
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")),
new Rectangle2D.Double(x - w / 2, plot.getY() - h - 3, w, h),
"ctr", "t", 1.0);
@@ -226,16 +249,20 @@ final class CartesianPainter {
: 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;
if (reversed) {
t = 1 - t;
}
return horizontal
? plot.getY() + t * plot.getHeight()
? plot.getY() + (1 - t) * plot.getHeight()
: plot.getX() + t * plot.getWidth();
}
private static void drawLines(Graphics2D g, ChartSpec spec, Rectangle2D plot,
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++) {
ChartSpec.Series s = spec.series.get(si);
Color c = s.lineColor != null ? s.lineColor : s.fillAt(si, palette);
@@ -247,7 +274,7 @@ final class CartesianPainter {
List<Double> cross = new ArrayList<>();
if (cum != null) {
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));
}
} else {
@@ -256,7 +283,7 @@ final class CartesianPainter {
if (v == null) {
continue;
}
along.add(catPos(i, nCat, plot, horizontal));
along.add(catPos(i, nCat, plot, horizontal, reversed));
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,
List<Color> palette, double lo, double hi, int nCat,
boolean horizontal) {
boolean horizontal, boolean reversed) {
for (int si = 0; si < spec.series.size(); si++) {
ChartSpec.Series s = spec.series.get(si);
Color c = s.fill != null ? s.fill : s.fillAt(si, palette);
@@ -298,7 +325,7 @@ final class CartesianPainter {
if (v == null) {
continue;
}
along.add(catPos(i, nCat, plot, horizontal));
along.add(catPos(i, nCat, plot, horizontal, reversed));
cross.add(valuePos(v, lo, hi, plot, horizontal));
}
if (along.size() < MIN_POLYLINE_POINTS) {
@@ -339,7 +366,7 @@ final class CartesianPainter {
private static void drawBars(Graphics2D g, ChartSpec spec, Rectangle2D plot,
List<Color> palette, double lo, double hi, int nCat,
boolean horizontal, double[][] cum) {
boolean horizontal, boolean reversed, double[][] cum) {
int nSer = spec.series.size();
double slot = (horizontal ? plot.getHeight() : plot.getWidth()) / nCat;
if (cum != null) {
@@ -360,7 +387,7 @@ final class CartesianPainter {
}
Color c = s.fillAt(i, palette);
g.setColor(c);
double center = catPos(i, nCat, plot, horizontal);
double center = catPos(i, nCat, plot, horizontal, reversed);
double start = center - barW / 2;
double prev = si == 0 ? 0 : cum[si - 1][i];
double p0 = valuePos(prev, lo, hi, plot, horizontal);
@@ -399,7 +426,7 @@ final class CartesianPainter {
}
Color c = s.fillAt(i, palette);
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 end = valuePos(v, lo, hi, plot, 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) {
if (spec.title == null || spec.titleStyle == null) {
return 0;
}
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")),
new Rectangle2D.Double(box.getX(), box.getY(), box.getWidth(), height * 2),
"ctr", "t", 1.0);
return height * 2;
}
int lines = DrawMlText.lineCount(spec.title, spec.titleStyle, box.getWidth());
double height = lines * lineH + 4;
DrawMlText.paint(g, List.of(new Paragraph(spec.title, spec.titleStyle, "ctr")),
new Rectangle2D.Double(box.getX(), box.getY(), box.getWidth(), height),
"ctr", "ctr", 1.0);
"ctr", "t", 1.0);
return height;
}
@@ -52,6 +52,7 @@ import org.docx4j.dml.chart.CTTitle;
import org.docx4j.dml.chart.CTTx;
import org.docx4j.dml.chart.CTValAx;
import org.docx4j.dml.chart.CTView3D;
import org.docx4j.dml.chart.STOrientation;
import java.awt.Color;
import java.util.ArrayList;
@@ -135,6 +136,9 @@ final class ChartSpec {
double axisLineWidth = 0.75;
DrawMlText.Style labelStyle;
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;
@@ -834,6 +838,9 @@ final class ChartSpec {
if (scaling.getMax() != null) {
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;
if (grid != null && grid.getSpPr() != null && grid.getSpPr().getLn() != null
@@ -267,6 +267,11 @@ final class DrawMlText {
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) для стиля. */
static double textHeight(Style style) {
GlyphFont f = fontFor(style);