Merge pull request 'PMD: 4 новых правила (errorprone + ForLoopCanBeForeach) и чистка нарушений' (#29) from pmd-four-rules into main
Main: tests, deploy, autotests / java (push) Successful in 44s
Main: tests, deploy, autotests / web (push) Successful in 53s
Main: tests, deploy, autotests / images (push) Successful in 1m9s
Main: tests, deploy, autotests / deploy (push) Successful in 3m4s
Main: tests, deploy, autotests / autotests (push) Successful in 37s
Main: tests, deploy, autotests / rollback (push) Has been skipped
Main: tests, deploy, autotests / java (push) Successful in 44s
Main: tests, deploy, autotests / web (push) Successful in 53s
Main: tests, deploy, autotests / images (push) Successful in 1m9s
Main: tests, deploy, autotests / deploy (push) Successful in 3m4s
Main: tests, deploy, autotests / autotests (push) Successful in 37s
Main: tests, deploy, autotests / rollback (push) Has been skipped
Reviewed-on: #29
This commit was merged in pull request #29.
This commit is contained in:
@@ -135,7 +135,7 @@ SSH-пользователи/логины, ни хосты, ни директо
|
|||||||
- `wordpdf-app/pom.xml` — `spring-boot-maven-plugin` с **явной** execution `repackage` (в 4.1.1 сам не связывается, jar останется тонким); `slf4j-simple` исключён; `spring-boot-starter-webmvc` (Boot 4: переименован из starter-web) + `spring-boot-starter-actuator` (нужен HEALTHCHECK контейнера `/actuator/health`); тест-зависимости: `spring-boot-webmvc-test` (в Boot 4 автоконфиг MockMvc вынесен из starter-test), test-jar core.
|
- `wordpdf-app/pom.xml` — `spring-boot-maven-plugin` с **явной** execution `repackage` (в 4.1.1 сам не связывается, jar останется тонким); `slf4j-simple` исключён; `spring-boot-starter-webmvc` (Boot 4: переименован из starter-web) + `spring-boot-starter-actuator` (нужен HEALTHCHECK контейнера `/actuator/health`); тест-зависимости: `spring-boot-webmvc-test` (в Boot 4 автоконфиг MockMvc вынесен из starter-test), test-jar core.
|
||||||
- `wordpdf-core/pom.xml` — `maven-jar-plugin` execution `test-jar` (публикует фикстуры для app).
|
- `wordpdf-core/pom.xml` — `maven-jar-plugin` execution `test-jar` (публикует фикстуры для app).
|
||||||
- Корневой `pom.xml` — все версии зависимостей (в модулях версии не объявлять): docx4j `17.3.2`, slf4j `2.0.20`, JUnit `6.1.3`, PDFBox `3.0.8` (test), POI `5.5.1` (test, только генератор фикстур), Spring Boot `4.1.1` (BOM-import), springdoc `3.1.1`; pluginManagement: compiler `3.16.0`, surefire `3.6.0` с `-Djava.awt.headless=true`, jar `3.5.1`, PMD `3.28.0`.
|
- Корневой `pom.xml` — все версии зависимостей (в модулях версии не объявлять): docx4j `17.3.2`, slf4j `2.0.20`, JUnit `6.1.3`, PDFBox `3.0.8` (test), POI `5.5.1` (test, только генератор фикстур), Spring Boot `4.1.1` (BOM-import), springdoc `3.1.1`; pluginManagement: compiler `3.16.0`, surefire `3.6.0` с `-Djava.awt.headless=true`, jar `3.5.1`, PMD `3.28.0`.
|
||||||
- Корневой `pmd-ruleset.xml` — ruleset PMD (см. Testing & QA): `category/java/codestyle.xml` минус opinionated-правила, `MethodNamingConventions` с `junit5TestPattern` под underscore-имена регрессий, `TooManyStaticImports` до 12, XPath-правило `LiteralFirstInEquals`, unused-правила из `bestpractices.xml`.
|
- Корневой `pmd-ruleset.xml` — ruleset PMD (см. Testing & QA): `category/java/codestyle.xml` минус opinionated-правила, `MethodNamingConventions` с `junit5TestPattern` под underscore-имена регрессий, `TooManyStaticImports` до 12, XPath-правило `LiteralFirstInEquals`, unused-правила из `bestpractices.xml`, `ReturnEmptyCollectionRatherThanNull` (errorprone, priority 1), `AvoidLiteralsInIfCondition` (errorprone, дефолтная 3), `EmptyCatchBlock` (errorprone) и `ForLoopCanBeForeach` (bestpractices) — оба priority 2.
|
||||||
- `wordpdf-core/src/main/resources/slf4j-simple.properties` — без него предупреждение лезет в PDF.
|
- `wordpdf-core/src/main/resources/slf4j-simple.properties` — без него предупреждение лезет в PDF.
|
||||||
- `gateway/nginx.conf` — единственный вход: `/api/`, `/swagger-ui`, `/v3/api-docs`, `/actuator` → `app:8080`, остальное → `web:80`; `client_max_body_size 100m` (без директивы upload режется HTML-413 шлюза вместо JSON-ошибки API); `resolver 10.113.0.1` + `proxy_pass` через переменные (статический proxy_pass резолвит имя один раз при старте — gateway раньше app поднялся бы с 502 до перезапуска). `wordpdf-web/nginx.conf` — чистая статика с SPA-fallback, `/api` НЕ проксирует.
|
- `gateway/nginx.conf` — единственный вход: `/api/`, `/swagger-ui`, `/v3/api-docs`, `/actuator` → `app:8080`, остальное → `web:80`; `client_max_body_size 100m` (без директивы upload режется HTML-413 шлюза вместо JSON-ошибки API); `resolver 10.113.0.1` + `proxy_pass` через переменные (статический proxy_pass резолвит имя один раз при старте — gateway раньше app поднялся бы с 502 до перезапуска). `wordpdf-web/nginx.conf` — чистая статика с SPA-fallback, `/api` НЕ проксирует.
|
||||||
- `wordpdf-core/src/test/java/ru/pjandro/wordpdf/SampleDocxGenerator.java` — main()-утилита пересоздания фикстур.
|
- `wordpdf-core/src/test/java/ru/pjandro/wordpdf/SampleDocxGenerator.java` — main()-утилита пересоздания фикстур.
|
||||||
@@ -153,7 +153,7 @@ SSH-пользователи/логины, ни хосты, ни директо
|
|||||||
|
|
||||||
## Testing & QA
|
## Testing & QA
|
||||||
|
|
||||||
- Гейт `maven-pmd-plugin` 3.28.0 (PMD 7.17) на `verify` для обоих модулей, ruleset `pmd-ruleset.xml` (codestyle без opinionated-правил + unused-правила + XPath `LiteralFirstInEquals` — строковый литерал слева в `equals`/`equalsIgnoreCase`; `junit5TestPattern` разрешает underscore-имена регрессий; `includeTests=true` — тесты сканируются).
|
- Гейт `maven-pmd-plugin` 3.28.0 (PMD 7.17) на `verify` для обоих модулей, ruleset `pmd-ruleset.xml` (codestyle без opinionated-правил + unused-правила + XPath `LiteralFirstInEquals` — строковый литерал слева в `equals`/`equalsIgnoreCase`; `junit5TestPattern` разрешает underscore-имена регрессий; `includeTests=true` — тесты сканируются; `failurePriority` не задан — дефолт 2, т.е. нарушения priority ≤ 2 валят build, priority 3 — только WARNING в отчёт). Литералы в условиях `if` — только именованными константами (`AvoidLiteralsInIfCondition`), `null` вместо пустой коллекции запрещён (`ReturnEmptyCollectionRatherThanNull` — `GlyphCoverageNormalizer.split` возвращает пустой список).
|
||||||
- 15 тестовых классов / 144 `@Test` (core 12/118, app 3/26). JUnit 6 (`org.junit.jupiter:junit-jupiter`), surefire 3.6.0 с `-Djava.awt.headless=true` в argLine; только `Assertions` (Mockito/AssertJ не использовать, несмотря на test-classpath Boot; в app-тестах допустим inline-Hamcrest `org.hamcrest.Matchers.containsString` в `andExpect`); тестовые классы package-private, зеркалят main-пакеты; только `@Test` (+ единственный `@BeforeAll` — warm-up шрифтов в `GlyphCoverageNormalizerTest`).
|
- 15 тестовых классов / 144 `@Test` (core 12/118, app 3/26). JUnit 6 (`org.junit.jupiter:junit-jupiter`), surefire 3.6.0 с `-Djava.awt.headless=true` в argLine; только `Assertions` (Mockito/AssertJ не использовать, несмотря на test-classpath Boot; в app-тестах допустим inline-Hamcrest `org.hamcrest.Matchers.containsString` в `andExpect`); тестовые классы package-private, зеркалят main-пакеты; только `@Test` (+ единственный `@BeforeAll` — warm-up шрифтов в `GlyphCoverageNormalizerTest`).
|
||||||
- **PDF сравнивается текстом, не растеризацией**: PDFBox 3 (`Loader.loadPDF`) — `PDFTextStripper` для текста (пер-странично `setStartPage/setEndPage`), override `processTextPosition` для шрифта конкретного символа (`fontNameOf`), обход ресурсов страниц для встроенных шрифтов (`EAAAAA+Carlito-Bold`) и счётчика картинок (`imageCount`). Негативные маркеры — регрессии: `assertFalse(text.contains("#"))` (.notdef), `assertFalse(font.startsWith("Helvetica"))`. Текст нормализуется по пробелам (`norm`); в `tableImage_tableAndImage` — полное удаление пробелов (docx4j переносит слова в auto-fit таблицах).
|
- **PDF сравнивается текстом, не растеризацией**: PDFBox 3 (`Loader.loadPDF`) — `PDFTextStripper` для текста (пер-странично `setStartPage/setEndPage`), override `processTextPosition` для шрифта конкретного символа (`fontNameOf`), обход ресурсов страниц для встроенных шрифтов (`EAAAAA+Carlito-Bold`) и счётчика картинок (`imageCount`). Негативные маркеры — регрессии: `assertFalse(text.contains("#"))` (.notdef), `assertFalse(font.startsWith("Helvetica"))`. Текст нормализуется по пробелам (`norm`); в `tableImage_tableAndImage` — полное удаление пробелов (docx4j переносит слова в auto-fit таблицах).
|
||||||
- Пиксели (BufferedImage) — только в unit-тестах chart-пейнтеров: безразмерные отношения к эталону Word, допуски `assertRatio` <0.06 (`PiePainterTest` аспект h/w=0.585) / <0.10 (`Surface3dPainterTest`, + `assertRange` ±6 pt для центров силуэта); пороги залитых px и перцентильные коридоры яркости. Эталонные замеры — по Word-экспорту 300 dpi (`develop/`, вне git).
|
- Пиксели (BufferedImage) — только в unit-тестах chart-пейнтеров: безразмерные отношения к эталону Word, допуски `assertRatio` <0.06 (`PiePainterTest` аспект h/w=0.585) / <0.10 (`Surface3dPainterTest`, + `assertRange` ±6 pt для центров силуэта); пороги залитых px и перцентильные коридоры яркости. Эталонные замеры — по Word-экспорту 300 dpi (`develop/`, вне git).
|
||||||
|
|||||||
@@ -63,4 +63,15 @@
|
|||||||
<rule ref="category/java/bestpractices.xml/UnusedLocalVariable"/>
|
<rule ref="category/java/bestpractices.xml/UnusedLocalVariable"/>
|
||||||
<rule ref="category/java/bestpractices.xml/UnusedPrivateField"/>
|
<rule ref="category/java/bestpractices.xml/UnusedPrivateField"/>
|
||||||
<rule ref="category/java/bestpractices.xml/UnusedPrivateMethod"/>
|
<rule ref="category/java/bestpractices.xml/UnusedPrivateMethod"/>
|
||||||
|
|
||||||
|
<!-- null вместо пустой коллекции запрещён (priority 1 по умолчанию — валит verify) -->
|
||||||
|
<rule ref="category/java/errorprone.xml/ReturnEmptyCollectionRatherThanNull"/>
|
||||||
|
<!-- литералы в условиях if — только именованными константами -->
|
||||||
|
<rule ref="category/java/errorprone.xml/AvoidLiteralsInIfCondition"/>
|
||||||
|
<rule ref="category/java/errorprone.xml/EmptyCatchBlock">
|
||||||
|
<priority>2</priority>
|
||||||
|
</rule>
|
||||||
|
<rule ref="category/java/bestpractices.xml/ForLoopCanBeForeach">
|
||||||
|
<priority>2</priority>
|
||||||
|
</rule>
|
||||||
</ruleset>
|
</ruleset>
|
||||||
|
|||||||
@@ -61,6 +61,9 @@ import java.util.zip.ZipInputStream;
|
|||||||
*/
|
*/
|
||||||
public final class WordPdfValidator {
|
public final class WordPdfValidator {
|
||||||
|
|
||||||
|
/** Элемент-контейнер body, внутри которого sectPr — межсекционный разрыв. */
|
||||||
|
private static final String BODY_ELEMENT = "body";
|
||||||
|
|
||||||
private WordPdfValidator() {
|
private WordPdfValidator() {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -392,7 +395,7 @@ public final class WordPdfValidator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
case "sectPr" -> {
|
case "sectPr" -> {
|
||||||
if ("body".equals(parent)) {
|
if (BODY_ELEMENT.equals(parent)) {
|
||||||
inBodySectPr = true;
|
inBodySectPr = true;
|
||||||
sectTypeVal = null;
|
sectTypeVal = null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -202,7 +202,7 @@ public final class GlyphCoverageNormalizer {
|
|||||||
}
|
}
|
||||||
String decoded = decode(text.group(2));
|
String decoded = decode(text.group(2));
|
||||||
List<Segment> segments = split(decoded, runFamily);
|
List<Segment> segments = split(decoded, runFamily);
|
||||||
if (segments == null) {
|
if (segments.isEmpty()) {
|
||||||
return block;
|
return block;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -219,7 +219,7 @@ public final class GlyphCoverageNormalizer {
|
|||||||
/**
|
/**
|
||||||
* Разбивает текст на части по семейству, которое обязано его отрисовать.
|
* Разбивает текст на части по семейству, которое обязано его отрисовать.
|
||||||
*
|
*
|
||||||
* @return части либо null, если весь текст остаётся на шрифте ранa
|
* @return части либо пустой список, если весь текст остаётся на шрифте ранa
|
||||||
* (или ни один бандл-шрифт не покрывает недостающие знаки)
|
* (или ни один бандл-шрифт не покрывает недостающие знаки)
|
||||||
*/
|
*/
|
||||||
static List<Segment> split(String text, String runFamily) {
|
static List<Segment> split(String text, String runFamily) {
|
||||||
@@ -240,11 +240,11 @@ public final class GlyphCoverageNormalizer {
|
|||||||
i = next;
|
i = next;
|
||||||
}
|
}
|
||||||
if (text.isEmpty()) {
|
if (text.isEmpty()) {
|
||||||
return null;
|
return List.of();
|
||||||
}
|
}
|
||||||
segments.add(new Segment(text.substring(start), current));
|
segments.add(new Segment(text.substring(start), current));
|
||||||
boolean changed = segments.size() > 1 || segments.get(0).family != null;
|
boolean changed = segments.size() > 1 || segments.get(0).family != null;
|
||||||
return changed ? segments : null;
|
return changed ? segments : List.of();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -15,6 +15,9 @@ import java.util.List;
|
|||||||
*/
|
*/
|
||||||
final class CartesianPainter {
|
final class CartesianPainter {
|
||||||
|
|
||||||
|
/** Линия/область рисуется только из двух и более точек. */
|
||||||
|
private static final int MIN_POLYLINE_POINTS = 2;
|
||||||
|
|
||||||
private CartesianPainter() {
|
private CartesianPainter() {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -236,7 +239,7 @@ final class CartesianPainter {
|
|||||||
along.add(catPos(i, nCat, plot, horizontal));
|
along.add(catPos(i, nCat, plot, horizontal));
|
||||||
cross.add(valuePos(v, lo, hi, plot, horizontal));
|
cross.add(valuePos(v, lo, hi, plot, horizontal));
|
||||||
}
|
}
|
||||||
if (along.size() > 1) {
|
if (along.size() >= MIN_POLYLINE_POINTS) {
|
||||||
g.draw(ChartRenderer.polyline(along, cross, false));
|
g.draw(ChartRenderer.polyline(along, cross, false));
|
||||||
}
|
}
|
||||||
if (s.marker) {
|
if (s.marker) {
|
||||||
@@ -271,7 +274,7 @@ final class CartesianPainter {
|
|||||||
along.add(catPos(i, nCat, plot, horizontal));
|
along.add(catPos(i, nCat, plot, horizontal));
|
||||||
cross.add(valuePos(v, lo, hi, plot, horizontal));
|
cross.add(valuePos(v, lo, hi, plot, horizontal));
|
||||||
}
|
}
|
||||||
if (along.size() < 2) {
|
if (along.size() < MIN_POLYLINE_POINTS) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
Path2D p = new Path2D.Double();
|
Path2D p = new Path2D.Double();
|
||||||
|
|||||||
@@ -32,6 +32,14 @@ final class ChartRenderer {
|
|||||||
/** Поля вокруг chartSpace от рамки графика. Auto-layout Word — Word-эмпирика. */
|
/** Поля вокруг chartSpace от рамки графика. Auto-layout Word — Word-эмпирика. */
|
||||||
private static final double PADDING = 4.0;
|
private static final double PADDING = 4.0;
|
||||||
|
|
||||||
|
/** «Круглые» множители шага делений 1/2/5·10ⁿ (как подбирает Word). */
|
||||||
|
private static final double NICE_STEP_ONE = 1;
|
||||||
|
private static final double NICE_STEP_TWO = 2;
|
||||||
|
private static final double NICE_STEP_FIVE = 5;
|
||||||
|
|
||||||
|
/** Порог «значение целое» при форматировании подписей. */
|
||||||
|
private static final double INTEGER_EPSILON = 1e-9;
|
||||||
|
|
||||||
private ChartRenderer() {
|
private ChartRenderer() {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,8 +216,7 @@ final class ChartRenderer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
default -> {
|
default -> {
|
||||||
for (int i = 0; i < spec.series.size(); i++) {
|
for (ChartSpec.Series s : spec.series) {
|
||||||
ChartSpec.Series s = spec.series.get(i);
|
|
||||||
Color c = s.lineColor != null ? s.lineColor
|
Color c = s.lineColor != null ? s.lineColor
|
||||||
: s.fillAt(0, palette);
|
: s.fillAt(0, palette);
|
||||||
boolean lineLike = spec.type == ChartSpec.Type.LINE;
|
boolean lineLike = spec.type == ChartSpec.Type.LINE;
|
||||||
@@ -281,14 +288,14 @@ final class ChartRenderer {
|
|||||||
double exp = Math.floor(Math.log10(raw));
|
double exp = Math.floor(Math.log10(raw));
|
||||||
double base = Math.pow(10, exp);
|
double base = Math.pow(10, exp);
|
||||||
double frac = raw / base;
|
double frac = raw / base;
|
||||||
if (frac <= 1) {
|
if (frac <= NICE_STEP_ONE) {
|
||||||
return base;
|
return base;
|
||||||
}
|
}
|
||||||
if (frac <= 2) {
|
if (frac <= NICE_STEP_TWO) {
|
||||||
return 2 * base;
|
return NICE_STEP_TWO * base;
|
||||||
}
|
}
|
||||||
if (frac <= 5) {
|
if (frac <= NICE_STEP_FIVE) {
|
||||||
return 5 * base;
|
return NICE_STEP_FIVE * base;
|
||||||
}
|
}
|
||||||
return 10 * base;
|
return 10 * base;
|
||||||
}
|
}
|
||||||
@@ -353,7 +360,7 @@ final class ChartRenderer {
|
|||||||
return String.format(java.util.Locale.ROOT, "%.1f", v);
|
return String.format(java.util.Locale.ROOT, "%.1f", v);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (Math.abs(v - Math.rint(v)) < 1e-9) {
|
if (Math.abs(v - Math.rint(v)) < INTEGER_EPSILON) {
|
||||||
return String.valueOf((long) Math.rint(v));
|
return String.valueOf((long) Math.rint(v));
|
||||||
}
|
}
|
||||||
String s = String.format(java.util.Locale.ROOT, "%.2f", v);
|
String s = String.format(java.util.Locale.ROOT, "%.2f", v);
|
||||||
|
|||||||
@@ -50,6 +50,10 @@ final class DrawMlColor {
|
|||||||
"hlink", "0563C1", "folHlink", "954F72",
|
"hlink", "0563C1", "folHlink", "954F72",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Word: bg1/tx1 — псевдонимы lt1/dk1. */
|
||||||
|
private static final String ALIAS_BG1 = "bg1";
|
||||||
|
private static final String ALIAS_TX1 = "tx1";
|
||||||
|
|
||||||
DrawMlColor(Theme theme) {
|
DrawMlColor(Theme theme) {
|
||||||
for (int i = 0; i < OFFICE_DEFAULT.length; i += 2) {
|
for (int i = 0; i < OFFICE_DEFAULT.length; i += 2) {
|
||||||
scheme.put(OFFICE_DEFAULT[i], decodeHex(OFFICE_DEFAULT[i + 1]));
|
scheme.put(OFFICE_DEFAULT[i], decodeHex(OFFICE_DEFAULT[i + 1]));
|
||||||
@@ -112,9 +116,9 @@ final class DrawMlColor {
|
|||||||
}
|
}
|
||||||
String n = name.toLowerCase(Locale.ROOT);
|
String n = name.toLowerCase(Locale.ROOT);
|
||||||
// Word: bg1/tx1 — псевдонимы lt1/dk1
|
// Word: bg1/tx1 — псевдонимы lt1/dk1
|
||||||
if ("bg1".equals(n)) {
|
if (ALIAS_BG1.equals(n)) {
|
||||||
n = "lt1";
|
n = "lt1";
|
||||||
} else if ("tx1".equals(n)) {
|
} else if (ALIAS_TX1.equals(n)) {
|
||||||
n = "dk1";
|
n = "dk1";
|
||||||
}
|
}
|
||||||
Color c = scheme.get(n);
|
Color c = scheme.get(n);
|
||||||
|
|||||||
@@ -44,6 +44,10 @@ final class DrawMlText {
|
|||||||
record Paragraph(String text, Style style, String align) {
|
record Paragraph(String text, Style style, String align) {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Значения выравнивания DrawingML (a:pPr/@algn, a:bodyPr/@anchor). */
|
||||||
|
private static final String ALIGN_CTR = "ctr";
|
||||||
|
private static final String VALIGN_BOTTOM = "b";
|
||||||
|
|
||||||
private DrawMlText() {
|
private DrawMlText() {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -193,9 +197,9 @@ final class DrawMlText {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
double y = box.getY();
|
double y = box.getY();
|
||||||
if ("ctr".equals(vAlign)) {
|
if (ALIGN_CTR.equals(vAlign)) {
|
||||||
y += (box.getHeight() - totalHeight) / 2.0;
|
y += (box.getHeight() - totalHeight) / 2.0;
|
||||||
} else if ("b".equals(vAlign)) {
|
} else if (VALIGN_BOTTOM.equals(vAlign)) {
|
||||||
y += box.getHeight() - totalHeight;
|
y += box.getHeight() - totalHeight;
|
||||||
}
|
}
|
||||||
y = Math.max(box.getY(), y);
|
y = Math.max(box.getY(), y);
|
||||||
@@ -203,7 +207,7 @@ final class DrawMlText {
|
|||||||
g.setColor(line.style().color());
|
g.setColor(line.style().color());
|
||||||
double x = box.getX();
|
double x = box.getX();
|
||||||
String align = line.align() != null ? line.align() : defAlign;
|
String align = line.align() != null ? line.align() : defAlign;
|
||||||
if ("ctr".equals(align)) {
|
if (ALIGN_CTR.equals(align)) {
|
||||||
x += (box.getWidth() - line.width()) / 2.0;
|
x += (box.getWidth() - line.width()) / 2.0;
|
||||||
} else if ("r".equals(align) || "far".equals(align)) {
|
} else if ("r".equals(align) || "far".equals(align)) {
|
||||||
x += box.getWidth() - line.width();
|
x += box.getWidth() - line.width();
|
||||||
|
|||||||
+6
-6
@@ -104,7 +104,7 @@ public final class DrawingPreRenderer {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
List<Object> content = contentOf(p);
|
List<Object> content = contentOf(p);
|
||||||
if (content == null || content.isEmpty()) {
|
if (content.isEmpty()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
walk(p, content, pkg, colors, idSeq, options);
|
walk(p, content, pkg, colors, idSeq, options);
|
||||||
@@ -114,11 +114,11 @@ public final class DrawingPreRenderer {
|
|||||||
/** Содержимое части, в котором могут лежать w:drawing. */
|
/** Содержимое части, в котором могут лежать w:drawing. */
|
||||||
private static List<Object> contentOf(Part part) {
|
private static List<Object> contentOf(Part part) {
|
||||||
if (!(part instanceof JaxbXmlPart<?> jaxb)) {
|
if (!(part instanceof JaxbXmlPart<?> jaxb)) {
|
||||||
return null;
|
return List.of();
|
||||||
}
|
}
|
||||||
Object root = jaxb.getJaxbElement();
|
Object root = jaxb.getJaxbElement();
|
||||||
if (root == null) {
|
if (root == null) {
|
||||||
return null;
|
return List.of();
|
||||||
}
|
}
|
||||||
if (root instanceof org.docx4j.wml.Document doc) {
|
if (root instanceof org.docx4j.wml.Document doc) {
|
||||||
return doc.getBody() == null ? doc.getContent() : doc.getBody().getContent();
|
return doc.getBody() == null ? doc.getContent() : doc.getBody().getContent();
|
||||||
@@ -142,7 +142,7 @@ public final class DrawingPreRenderer {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
List<Object> nested = invokeList(v, "getContent");
|
List<Object> nested = invokeList(v, "getContent");
|
||||||
if (nested != null && !nested.isEmpty() && nested != content) {
|
if (!nested.isEmpty() && nested != content) {
|
||||||
walk(part, nested, pkg, colors, idSeq, options);
|
walk(part, nested, pkg, colors, idSeq, options);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -158,9 +158,9 @@ public final class DrawingPreRenderer {
|
|||||||
try {
|
try {
|
||||||
Method m = target.getClass().getMethod(getter);
|
Method m = target.getClass().getMethod(getter);
|
||||||
Object r = m.invoke(target);
|
Object r = m.invoke(target);
|
||||||
return r instanceof List ? (List<Object>) r : null;
|
return r instanceof List ? (List<Object>) r : List.of();
|
||||||
} catch (ReflectiveOperationException | RuntimeException e) {
|
} catch (ReflectiveOperationException | RuntimeException e) {
|
||||||
return null;
|
return List.of();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,9 @@ import java.awt.geom.RoundRectangle2D;
|
|||||||
*/
|
*/
|
||||||
final class PrstGeomShapes {
|
final class PrstGeomShapes {
|
||||||
|
|
||||||
|
/** Минимальный заметный дуге размах, градусы. */
|
||||||
|
private static final double MIN_ARC_SPAN_DEG = 1;
|
||||||
|
|
||||||
private PrstGeomShapes() {
|
private PrstGeomShapes() {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,7 +119,7 @@ final class PrstGeomShapes {
|
|||||||
double rInner = Math.max(1, rOuter - thickness);
|
double rInner = Math.max(1, rOuter - thickness);
|
||||||
double startDeg = deg(adj, 1, 2700000);
|
double startDeg = deg(adj, 1, 2700000);
|
||||||
double endDeg = deg(adj, 2, 3600000);
|
double endDeg = deg(adj, 2, 3600000);
|
||||||
if (Math.abs(endDeg - startDeg) < 1) {
|
if (Math.abs(endDeg - startDeg) < MIN_ARC_SPAN_DEG) {
|
||||||
endDeg = startDeg + 270;
|
endDeg = startDeg + 270;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,14 @@ import java.awt.Color;
|
|||||||
*/
|
*/
|
||||||
final class RgbHsl {
|
final class RgbHsl {
|
||||||
|
|
||||||
|
/** Насыщенность «бесцветный». */
|
||||||
|
private static final double SATURATION_NONE = 0.0;
|
||||||
|
/** Границы цикла тона hueToRgb, доли оборота. */
|
||||||
|
private static final double HUE_CYCLE_MIN = 0.0;
|
||||||
|
private static final double HUE_CYCLE_MAX = 1.0;
|
||||||
|
/** Середина цикла тона: между p и q. */
|
||||||
|
private static final double HUE_MID = 0.5;
|
||||||
|
|
||||||
private RgbHsl() {
|
private RgbHsl() {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,7 +50,7 @@ final class RgbHsl {
|
|||||||
double ss = Math.max(0, Math.min(1, s));
|
double ss = Math.max(0, Math.min(1, s));
|
||||||
double ll = Math.max(0, Math.min(1, l));
|
double ll = Math.max(0, Math.min(1, l));
|
||||||
double r, g, b;
|
double r, g, b;
|
||||||
if (ss == 0.0) {
|
if (ss == SATURATION_NONE) {
|
||||||
r = g = b = ll;
|
r = g = b = ll;
|
||||||
} else {
|
} else {
|
||||||
double q = ll < 0.5 ? ll * (1.0 + ss) : ll + ss - ll * ss;
|
double q = ll < 0.5 ? ll * (1.0 + ss) : ll + ss - ll * ss;
|
||||||
@@ -60,16 +68,16 @@ final class RgbHsl {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static double hueToRgb(double p, double q, double t) {
|
private static double hueToRgb(double p, double q, double t) {
|
||||||
if (t < 0.0) {
|
if (t < HUE_CYCLE_MIN) {
|
||||||
t += 1.0;
|
t += 1.0;
|
||||||
}
|
}
|
||||||
if (t > 1.0) {
|
if (t > HUE_CYCLE_MAX) {
|
||||||
t -= 1.0;
|
t -= 1.0;
|
||||||
}
|
}
|
||||||
if (t < 1.0 / 6.0) {
|
if (t < 1.0 / 6.0) {
|
||||||
return p + (q - p) * 6.0 * t;
|
return p + (q - p) * 6.0 * t;
|
||||||
}
|
}
|
||||||
if (t < 0.5) {
|
if (t < HUE_MID) {
|
||||||
return q;
|
return q;
|
||||||
}
|
}
|
||||||
if (t < 2.0 / 3.0) {
|
if (t < 2.0 / 3.0) {
|
||||||
|
|||||||
@@ -42,6 +42,9 @@ final class SmartArtRenderer {
|
|||||||
|
|
||||||
static final int DPI = ChartRenderer.DPI;
|
static final int DPI = ChartRenderer.DPI;
|
||||||
|
|
||||||
|
/** Порог «фигура повёрнута», градусы: меньше — поворот незначим. */
|
||||||
|
private static final double ROTATION_EPSILON_DEG = 0.01;
|
||||||
|
|
||||||
private SmartArtRenderer() {
|
private SmartArtRenderer() {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -168,7 +171,7 @@ final class SmartArtRenderer {
|
|||||||
double sh = it.h() * scale;
|
double sh = it.h() * scale;
|
||||||
|
|
||||||
AffineTransform saved = g.getTransform();
|
AffineTransform saved = g.getTransform();
|
||||||
if (Math.abs(it.rotDeg()) > 0.01) {
|
if (Math.abs(it.rotDeg()) > ROTATION_EPSILON_DEG) {
|
||||||
g.rotate(Math.toRadians(it.rotDeg()), x + sw / 2.0, y + sh / 2.0);
|
g.rotate(Math.toRadians(it.rotDeg()), x + sw / 2.0, y + sh / 2.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -58,6 +58,13 @@ final class Surface3dPainter {
|
|||||||
private static final double LIGHT_Y = 0.48;
|
private static final double LIGHT_Y = 0.48;
|
||||||
private static final double LIGHT_Z = 0.28;
|
private static final double LIGHT_Z = 0.28;
|
||||||
|
|
||||||
|
/** Вырожденная нормаль грани (нулевое векторное произведение). */
|
||||||
|
private static final double NORMAL_EPSILON = 1e-12;
|
||||||
|
/** Минимальный осмысленный многоугольник грани. */
|
||||||
|
private static final int MIN_POLYGON_VERTICES = 3;
|
||||||
|
/** Порог «перспектива выключена» (c:view3D/perspective, градусы). */
|
||||||
|
private static final double ORTHO_PERSPECTIVE_EPS = 0.01;
|
||||||
|
|
||||||
private Surface3dPainter() {
|
private Surface3dPainter() {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -275,7 +282,7 @@ final class Surface3dPainter {
|
|||||||
double ny = e1z * e2x - e1x * e2z;
|
double ny = e1z * e2x - e1x * e2z;
|
||||||
double nz = e1x * e2y - e1y * e2x;
|
double nz = e1x * e2y - e1y * e2x;
|
||||||
double len = Math.hypot(Math.hypot(nx, ny), nz);
|
double len = Math.hypot(Math.hypot(nx, ny), nz);
|
||||||
if (len < 1e-12) {
|
if (len < NORMAL_EPSILON) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
nx /= len;
|
nx /= len;
|
||||||
@@ -316,7 +323,7 @@ final class Surface3dPainter {
|
|||||||
double a = wBase + k * wUnit;
|
double a = wBase + k * wUnit;
|
||||||
double b = wBase + (k + 1) * wUnit;
|
double b = wBase + (k + 1) * wUnit;
|
||||||
List<double[]> piece = clipW(List.of(pts[0], pts[1], pts[2]), a, b);
|
List<double[]> piece = clipW(List.of(pts[0], pts[1], pts[2]), a, b);
|
||||||
if (piece.size() < 3) {
|
if (piece.size() < MIN_POLYGON_VERTICES) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
Path2D path = new Path2D.Double();
|
Path2D path = new Path2D.Double();
|
||||||
@@ -344,7 +351,7 @@ final class Surface3dPainter {
|
|||||||
/** Отсечение многоугольника полосой w в [lo, hi] (Сазерленд-Ходжман). */
|
/** Отсечение многоугольника полосой w в [lo, hi] (Сазерленд-Ходжман). */
|
||||||
private static List<double[]> clipW(List<double[]> poly, double lo, double hi) {
|
private static List<double[]> clipW(List<double[]> poly, double lo, double hi) {
|
||||||
List<double[]> out = clipHalf(poly, lo, true);
|
List<double[]> out = clipHalf(poly, lo, true);
|
||||||
if (out.size() < 3) {
|
if (out.size() < MIN_POLYGON_VERTICES) {
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
return clipHalf(out, hi, false);
|
return clipHalf(out, hi, false);
|
||||||
@@ -512,7 +519,7 @@ final class Surface3dPainter {
|
|||||||
double depth = y1 * cb - w * sb;
|
double depth = y1 * cb - w * sb;
|
||||||
double height = y1 * sb + w * cb;
|
double height = y1 * sb + w * cb;
|
||||||
double k = 1.0;
|
double k = 1.0;
|
||||||
if (perspective > 0.01) {
|
if (perspective > ORTHO_PERSPECTIVE_EPS) {
|
||||||
double d = cameraDistance(depthScale, perspective);
|
double d = cameraDistance(depthScale, perspective);
|
||||||
k = d / Math.max(0.05, d + depth);
|
k = d / Math.max(0.05, d + depth);
|
||||||
}
|
}
|
||||||
@@ -524,11 +531,11 @@ final class Surface3dPainter {
|
|||||||
* полуширины): поле зрения c:view3D/perspective (θ, градусы, Word
|
* полуширины): поле зрения c:view3D/perspective (θ, градусы, Word
|
||||||
* default 30) накрывает описанную сферу коробки — полуширина 0.5 (u) и
|
* default 30) накрывает описанную сферу коробки — полуширина 0.5 (u) и
|
||||||
* полуглубина 0.5·depthScale (v) => R = sqrt(0.25 + 0.25·ds²),
|
* полуглубина 0.5·depthScale (v) => R = sqrt(0.25 + 0.25·ds²),
|
||||||
* d = R/tan(θ/2). Ортография (perspective ≤ 0.01) — бесконечность.
|
* d = R/tan(θ/2). Ортография (perspective ≤ ORTHO_PERSPECTIVE_EPS) — бесконечность.
|
||||||
* Единая камера surface и pie3D (PiePainter).
|
* Единая камера surface и pie3D (PiePainter).
|
||||||
*/
|
*/
|
||||||
static double cameraDistance(double depthScale, double perspective) {
|
static double cameraDistance(double depthScale, double perspective) {
|
||||||
if (perspective <= 0.01) {
|
if (perspective <= ORTHO_PERSPECTIVE_EPS) {
|
||||||
return Double.POSITIVE_INFINITY;
|
return Double.POSITIVE_INFINITY;
|
||||||
}
|
}
|
||||||
return Math.sqrt(0.25 + 0.25 * depthScale * depthScale)
|
return Math.sqrt(0.25 + 0.25 * depthScale * depthScale)
|
||||||
|
|||||||
@@ -54,6 +54,11 @@ import java.util.List;
|
|||||||
*/
|
*/
|
||||||
public final class SampleDocxGenerator {
|
public final class SampleDocxGenerator {
|
||||||
|
|
||||||
|
/** Первая страница нумерации (разрыв ставится со второй). */
|
||||||
|
private static final int FIRST_PAGE = 1;
|
||||||
|
/** Путь основной части документа в zip. */
|
||||||
|
private static final String DOCUMENT_PART = "word/document.xml";
|
||||||
|
|
||||||
private SampleDocxGenerator() {
|
private SampleDocxGenerator() {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -280,7 +285,7 @@ public final class SampleDocxGenerator {
|
|||||||
|
|
||||||
for (int page = 1; page <= 3; page++) {
|
for (int page = 1; page <= 3; page++) {
|
||||||
XWPFParagraph p = doc.createParagraph();
|
XWPFParagraph p = doc.createParagraph();
|
||||||
if (page > 1) {
|
if (page > FIRST_PAGE) {
|
||||||
p.getCTP().addNewPPr().addNewPageBreakBefore();
|
p.getCTP().addNewPPr().addNewPageBreakBefore();
|
||||||
}
|
}
|
||||||
run(p, "Страница " + page, "Times New Roman", false, false);
|
run(p, "Страница " + page, "Times New Roman", false, false);
|
||||||
@@ -392,7 +397,7 @@ public final class SampleDocxGenerator {
|
|||||||
java.util.zip.ZipEntry e;
|
java.util.zip.ZipEntry e;
|
||||||
while ((e = zin.getNextEntry()) != null) {
|
while ((e = zin.getNextEntry()) != null) {
|
||||||
byte[] data = zin.readAllBytes();
|
byte[] data = zin.readAllBytes();
|
||||||
if ("word/document.xml".equals(e.getName())) {
|
if (DOCUMENT_PART.equals(e.getName())) {
|
||||||
String xml = new String(data, java.nio.charset.StandardCharsets.UTF_8);
|
String xml = new String(data, java.nio.charset.StandardCharsets.UTF_8);
|
||||||
StringBuilder sb = new StringBuilder(xml.length() + 4096);
|
StringBuilder sb = new StringBuilder(xml.length() + 4096);
|
||||||
int i = 0;
|
int i = 0;
|
||||||
|
|||||||
@@ -20,6 +20,11 @@ import static org.junit.jupiter.api.Assertions.*;
|
|||||||
*/
|
*/
|
||||||
class WordPdfValidatorTest {
|
class WordPdfValidatorTest {
|
||||||
|
|
||||||
|
/** Лимит страниц в тесте точной границы (99 разрывов проходят, 100 — нет). */
|
||||||
|
private static final int PAGE_LIMIT = 100;
|
||||||
|
/** Путь основной части документа в zip. */
|
||||||
|
private static final String DOCUMENT_PART = "word/document.xml";
|
||||||
|
|
||||||
private static byte[] docxWithPageBreaks(int count) throws Exception {
|
private static byte[] docxWithPageBreaks(int count) throws Exception {
|
||||||
try (XWPFDocument doc = new XWPFDocument()) {
|
try (XWPFDocument doc = new XWPFDocument()) {
|
||||||
for (int i = 0; i < count; i++) {
|
for (int i = 0; i < count; i++) {
|
||||||
@@ -106,11 +111,11 @@ class WordPdfValidatorTest {
|
|||||||
void checkPageCount_limitBoundary() throws Exception {
|
void checkPageCount_limitBoundary() throws Exception {
|
||||||
for (int breaks : new int[]{0, 3, 99, 100, 101}) {
|
for (int breaks : new int[]{0, 3, 99, 100, 101}) {
|
||||||
byte[] bytes = docxWithPageBreaks(breaks);
|
byte[] bytes = docxWithPageBreaks(breaks);
|
||||||
if (breaks < 100) {
|
if (breaks < PAGE_LIMIT) {
|
||||||
assertDoesNotThrow(() -> WordPdfValidator.checkPageCount(bytes, 100));
|
assertDoesNotThrow(() -> WordPdfValidator.checkPageCount(bytes, PAGE_LIMIT));
|
||||||
} else {
|
} else {
|
||||||
ValidationException ex = assertThrows(ValidationException.class,
|
ValidationException ex = assertThrows(ValidationException.class,
|
||||||
() -> WordPdfValidator.checkPageCount(bytes, 100));
|
() -> WordPdfValidator.checkPageCount(bytes, PAGE_LIMIT));
|
||||||
assertTrue(ex.getMessage().contains("не менее " + (1 + breaks)),
|
assertTrue(ex.getMessage().contains("не менее " + (1 + breaks)),
|
||||||
"оценка = 1 + число разрывов: " + ex.getMessage());
|
"оценка = 1 + число разрывов: " + ex.getMessage());
|
||||||
}
|
}
|
||||||
@@ -169,7 +174,7 @@ class WordPdfValidatorTest {
|
|||||||
ZipEntry e;
|
ZipEntry e;
|
||||||
while ((e = zin.getNextEntry()) != null) {
|
while ((e = zin.getNextEntry()) != null) {
|
||||||
byte[] data = zin.readAllBytes();
|
byte[] data = zin.readAllBytes();
|
||||||
if ("word/document.xml".equals(e.getName())) {
|
if (DOCUMENT_PART.equals(e.getName())) {
|
||||||
String xml = new String(data, StandardCharsets.UTF_8);
|
String xml = new String(data, StandardCharsets.UTF_8);
|
||||||
StringBuilder sb = new StringBuilder();
|
StringBuilder sb = new StringBuilder();
|
||||||
for (String t : types) {
|
for (String t : types) {
|
||||||
|
|||||||
@@ -14,6 +14,9 @@ import static org.junit.jupiter.api.Assertions.*;
|
|||||||
*/
|
*/
|
||||||
class PiePainterTest {
|
class PiePainterTest {
|
||||||
|
|
||||||
|
/** Максимальный разброс каналов у «серого» пикселя (фон/антialiasing). */
|
||||||
|
private static final int GRAY_MAX_SPREAD = 25;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Форма торта (не масштаб — он зависит от заголовка и легенды): в эталоне
|
* Форма торта (не масштаб — он зависит от заголовка и легенды): в эталоне
|
||||||
* Word силуэт 540×316 px, т.е. h/w = 0,585 при ry/rx = 0,475 и глубине
|
* Word силуэт 540×316 px, т.е. h/w = 0,585 при ry/rx = 0,475 и глубине
|
||||||
@@ -35,7 +38,7 @@ class PiePainterTest {
|
|||||||
int r = (rgb >> 16) & 0xFF;
|
int r = (rgb >> 16) & 0xFF;
|
||||||
int g = (rgb >> 8) & 0xFF;
|
int g = (rgb >> 8) & 0xFF;
|
||||||
int b = rgb & 0xFF;
|
int b = rgb & 0xFF;
|
||||||
if (Math.max(Math.max(r, g), b) - Math.min(Math.min(r, g), b) <= 25) {
|
if (Math.max(Math.max(r, g), b) - Math.min(Math.min(r, g), b) <= GRAY_MAX_SPREAD) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
painted++;
|
painted++;
|
||||||
|
|||||||
+10
-3
@@ -20,6 +20,13 @@ import static org.junit.jupiter.api.Assertions.*;
|
|||||||
*/
|
*/
|
||||||
class Surface3dPainterTest {
|
class Surface3dPainterTest {
|
||||||
|
|
||||||
|
/** Минимальная альфа «залитого» пикселя. */
|
||||||
|
private static final int PAINTED_ALPHA_MIN = 200;
|
||||||
|
/** Индекс жёлтой полосы палитры (accent4) в тесте седловой ячейки. */
|
||||||
|
private static final int YELLOW_BAND = 3;
|
||||||
|
/** Ограничение длины диагностической строки расхождений. */
|
||||||
|
private static final int SEEN_LIMIT = 40;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void project_perspectiveMakesFrontEdgeWider() {
|
void project_perspectiveMakesFrontEdgeWider() {
|
||||||
double rotX = Math.toRadians(15);
|
double rotX = Math.toRadians(15);
|
||||||
@@ -68,7 +75,7 @@ class Surface3dPainterTest {
|
|||||||
for (int y = 0; y < img.getHeight(); y++) {
|
for (int y = 0; y < img.getHeight(); y++) {
|
||||||
for (int x = 0; x < img.getWidth(); x++) {
|
for (int x = 0; x < img.getWidth(); x++) {
|
||||||
int argb = img.getRGB(x, y);
|
int argb = img.getRGB(x, y);
|
||||||
if (((argb >>> 24) & 0xFF) < 200) {
|
if (((argb >>> 24) & 0xFF) < PAINTED_ALPHA_MIN) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
Color c = new Color(argb);
|
Color c = new Color(argb);
|
||||||
@@ -252,9 +259,9 @@ class Surface3dPainterTest {
|
|||||||
}
|
}
|
||||||
checked++;
|
checked++;
|
||||||
int band = bandOf(new Color(img.getRGB(x, y)), palette);
|
int band = bandOf(new Color(img.getRGB(x, y)), palette);
|
||||||
if (band == 3) {
|
if (band == YELLOW_BAND) {
|
||||||
yellow++;
|
yellow++;
|
||||||
} else if (seen.length() < 40) {
|
} else if (seen.length() < SEEN_LIMIT) {
|
||||||
seen.append("x=").append(x).append(" полоса ").append(band).append("; ");
|
seen.append("x=").append(x).append(" полоса ").append(band).append("; ");
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
|
|||||||
Reference in New Issue
Block a user