feat(core): правило 9 DistributeStampNormalizer - w:jc=distribute растягивает все строки (Part 1 17.18.44)
docx4j для DISTRIBUTE не эмитит в FO ничего - абзац печатался по левому краю. Нормализатор ставит в distribute-абзацы закладку-якорь pj-distribute-<часть>-<n> (после Hidden, content-части, идемпотентно), LayoutPostRenderer по якорю дописывает блоку пару text-align/text-align-last=justify - межсловный разнос всех строк, включая последнюю (пин форка DistributeLineTestCase). Паттерн якоря принимает и префиксную, и безпрефиксную сериализацию fo:inline (DOM-поддерево toNode). Фикстура distribute.docx (хвост трёхсловный - одно слово растягивать нечем), регрессии distribute_allLinesReachRightMargin + юниты нормализатора и фильтра. Доки: правила 1-9 (Ole - правило 10), шаг 4.25, FOP-оверлей в инвариантах и новая секция AGENTS; render-limitations - distribute перенесён в починенное. Дополнительно в AGENTS: заметки про гейт готовности podman-контейнеров.
This commit is contained in:
+187
@@ -0,0 +1,187 @@
|
||||
package ru.pjandro.wordpdf.internal;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
/**
|
||||
* {@code w:pPr/w:jc w:val="distribute"} → невидимая закладка-штамп в начале
|
||||
* абзаца — до загрузки docx4j (Part 1 §17.18.44).
|
||||
*
|
||||
* <p>Word при {@code distribute} растягивает межсловные пробелы каждой строки
|
||||
* абзаца, включая последнюю. docx4j для DISTRIBUTE не эмитит в FO ничего
|
||||
* ({@code Justification.setXslFO} не знает этого значения): абзац приходит в
|
||||
* FOP без {@code text-align} и печатается по левому краю. Канонический FO
|
||||
* эквивалент — {@code text-align="justify" text-align-last="justify"} (пин в
|
||||
* форке: DistributeLineTestCase), но в XSLT-стилиста дописать атрибутику jc
|
||||
* нельзя (дрейф-гейт {@code vendoredXsltTracksJarCopy}), а рендер-фильтр
|
||||
* {@code LayoutPostRenderer} видит только FO и опознал бы distribute-абзац
|
||||
* лишь по якорю. Штамп — этот якорь: {@code w:bookmarkStart
|
||||
* w:name="pj-distribute-<часть>-<n>"} сразу после {@code </w:pPr>}; экспорт
|
||||
* docx4j ({@code BookmarkStartWriter}) превращает её в {@code <fo:inline
|
||||
* id="pj-distribute-…"/>} первым инлайн-ребёнком блока, и фильтр дописывает
|
||||
* блоку пару justify-свойств. Имена закладок уникальны в пределах конвертации
|
||||
* (docx4j дубликаты выбрасывает с warn), поэтому счётчик per-part с меткой
|
||||
* части в имени.</p>
|
||||
*
|
||||
* <p>Штампуются только content-части (document/footnotes/endnotes): в
|
||||
* {@code numbering.xml} у {@code CT_Lvl} закладки быть не может (не входит в
|
||||
* EG_PPrGeneralContent, WML XSD), а {@code w:jc} в {@code trPr}/{@code tblPr}
|
||||
* (выравнивание таблицы/строки) не читается — разбор идёт только содержимым
|
||||
* {@code w:pPr}. Диапазон абзаца плоский: {@code w:p} не вложен в {@code w:p}.
|
||||
* Уже проштампованный абзац не дублируется (идемпотентность). Нечего менять →
|
||||
* {@code null} (контракт rewrite-хуков).</p>
|
||||
*
|
||||
* <p>Регрессии — DistributeStampNormalizerTest (юнит),
|
||||
* WordPdfConverterTest#distribute_allLinesReachRightMargin (конвейер),
|
||||
* фикстура samples/distribute.docx.</p>
|
||||
*/
|
||||
final class DistributeStampNormalizer {
|
||||
|
||||
/** Начало абзаца: {@code <w:p>} или {@code <w:p …>}; {@code w:pPr}-подобные не матчатся. */
|
||||
private static final Pattern PARA_START = Pattern.compile("<w:p(?=[ >/])");
|
||||
|
||||
/** justify-раскладка абзаца; ищем только внутри w:pPr. */
|
||||
private static final Pattern JC_DISTRIBUTE =
|
||||
Pattern.compile("<w:jc\\b[^>]*w:val=\"distribute\"");
|
||||
|
||||
/** Существующие id закладок — штампуете от max+1 (Part 1: id уникален в части). */
|
||||
private static final Pattern BOOKMARK_ID =
|
||||
Pattern.compile("<w:bookmarkStart\\b[^>]*w:id=\"(\\d+)\"");
|
||||
|
||||
/** Собственные штампы — защита от повторного штампа (идемпотентность). */
|
||||
private static final String STAMP_MARK = "pj-distribute-";
|
||||
|
||||
/** Закрывающий слэш открывающего тега: {@code <w:p/>} — абзац без содержимого. */
|
||||
private static final char SELF_CLOSE_SLASH = '/';
|
||||
|
||||
private DistributeStampNormalizer() {
|
||||
}
|
||||
|
||||
/** Шаг конвейера WordPdfConverter#normalizers: этот нормализатор как DocxNormalizer. */
|
||||
static final DocxNormalizer STEP = DistributeStampNormalizer::normalize;
|
||||
|
||||
/**
|
||||
* Штампует distribute-абзацы content-части.
|
||||
*
|
||||
* @param part имя zip-записи ({@code word/document.xml} и т. п.)
|
||||
* @param xml разметка части
|
||||
* @return размеченная разметка либо {@code null}, если менять нечего
|
||||
* (не content-часть / нет distribute-абзацев)
|
||||
*/
|
||||
static String rewrite(String part, String xml) {
|
||||
String tag = contentTag(part);
|
||||
if (tag == null) {
|
||||
return null;
|
||||
}
|
||||
Matcher starts = PARA_START.matcher(xml);
|
||||
StringBuilder sb = null;
|
||||
int mark = 0;
|
||||
int nextId = maxBookmarkId(xml) + 1;
|
||||
int seq = 0;
|
||||
while (starts.find()) {
|
||||
int body = starts.end();
|
||||
int gt = xml.indexOf('>', body);
|
||||
if (gt < 0) {
|
||||
break;
|
||||
}
|
||||
if (xml.charAt(gt - 1) == SELF_CLOSE_SLASH) {
|
||||
continue; // самозакрывающийся <w:p/> — pPr нет в помине
|
||||
}
|
||||
int end = xml.indexOf("</w:p>", gt);
|
||||
if (end < 0) {
|
||||
break;
|
||||
}
|
||||
int pprOpen = xml.indexOf("<w:pPr", body);
|
||||
if (pprOpen < 0 || pprOpen >= end) {
|
||||
continue;
|
||||
}
|
||||
int pprClose = xml.indexOf("</w:pPr>", pprOpen);
|
||||
if (pprClose < 0 || pprClose >= end) {
|
||||
continue;
|
||||
}
|
||||
CharSequence ppr = xml.subSequence(pprOpen, pprClose);
|
||||
if (!JC_DISTRIBUTE.matcher(ppr).find()) {
|
||||
continue;
|
||||
}
|
||||
int stamped = xml.indexOf(STAMP_MARK, gt);
|
||||
if (stamped >= 0 && stamped < end) {
|
||||
continue; // уже проштампован
|
||||
}
|
||||
seq++;
|
||||
if (sb == null) {
|
||||
sb = new StringBuilder(xml.length() + 64);
|
||||
}
|
||||
sb.append(xml, mark, pprClose + "</w:pPr>".length());
|
||||
sb.append("<w:bookmarkStart w:id=\"").append(nextId++).append("\" w:name=\"")
|
||||
.append(STAMP_MARK).append(tag).append('-').append(seq).append("\"/>")
|
||||
.append("<w:bookmarkEnd w:id=\"").append(nextId - 1).append("\"/>");
|
||||
mark = pprClose + "</w:pPr>".length();
|
||||
}
|
||||
return sb == null ? null : sb.append(xml, mark, xml.length()).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Метка части для имён закладок; {@code null} — часть не content
|
||||
* (в numbering/styles закладок быть не может, прочие не рендерятся).
|
||||
*/
|
||||
private static String contentTag(String part) {
|
||||
switch (part) {
|
||||
case "word/document.xml":
|
||||
return "document";
|
||||
case "word/footnotes.xml":
|
||||
return "footnotes";
|
||||
case "word/endnotes.xml":
|
||||
return "endnotes";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static int maxBookmarkId(String xml) {
|
||||
int max = 0;
|
||||
Matcher m = BOOKMARK_ID.matcher(xml);
|
||||
while (m.find()) {
|
||||
try {
|
||||
max = Math.max(max, Integer.parseInt(m.group(1)));
|
||||
} catch (NumberFormatException ignored) {
|
||||
// нечисловой id — не конкурент нашим id
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Самостоятельный zip-проход (тот же контракт, что у остальных; в
|
||||
* конвейере вызывается {@link #rewrite} через {@link DocxRewritePipeline}).
|
||||
*
|
||||
* @param docx байты .docx (zip)
|
||||
* @return те же или переупакованные байты
|
||||
*/
|
||||
static byte[] normalize(byte[] docx) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(docx.length);
|
||||
boolean changed = false;
|
||||
try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(docx));
|
||||
ZipOutputStream zos = new ZipOutputStream(out)) {
|
||||
ZipEntry entry;
|
||||
while ((entry = zis.getNextEntry()) != null) {
|
||||
byte[] data = zis.readAllBytes();
|
||||
String name = entry.getName();
|
||||
String fixed = name.startsWith("word/") && name.endsWith(".xml")
|
||||
? rewrite(name, new String(data, StandardCharsets.UTF_8))
|
||||
: null;
|
||||
zos.putNextEntry(new ZipEntry(name));
|
||||
zos.write(fixed != null ? fixed.getBytes(StandardCharsets.UTF_8) : data);
|
||||
zos.closeEntry();
|
||||
changed |= fixed != null;
|
||||
}
|
||||
}
|
||||
return changed ? out.toByteArray() : docx;
|
||||
}
|
||||
}
|
||||
@@ -15,13 +15,16 @@ import org.apache.commons.compress.utils.SeekableInMemoryByteChannel;
|
||||
/**
|
||||
* Единый zip-проход переписывания XML-частей (.docx) вместо отдельных
|
||||
* проходов нормализаторов: к каждой записи {@code word/*.xml} применяются
|
||||
* все восемь рерайтов в фиксированном порядке
|
||||
* Strict→OnOff→Invisible→GlyphCoverage→TableIndent→NumberingSuffix→Hidden→Ruby.
|
||||
* все девять рерайтов в фиксированном порядке
|
||||
* Strict→OnOff→Invisible→GlyphCoverage→TableIndent→NumberingSuffix→Hidden→Ruby→Distribute.
|
||||
* Порядок значим: Strict первым — дальше части в transitional-виде
|
||||
* (TableIndent читает transitional-атрибуты {@code w:}); GlyphCoverage
|
||||
* режет раны по финальному тексту рана (после Invisible); Hidden
|
||||
* последним — вырезает уже финальные раны (после GLYPH-разбиений),
|
||||
* а его OnOff-форма vanish читается после правила 2. Каждый
|
||||
* идёт после GlyphCoverage — вырезает уже финальные раны (после GLYPH-разбиений),
|
||||
* а его OnOff-форма vanish читается после правила 2; Distribute (штамп
|
||||
* {@code w:jc="distribute"} закладкой-якорем) — последним, он вставляет узел
|
||||
* после {@code </w:pPr>} и не трогает текст, но обязан видеть финальную
|
||||
* разметку, чтобы не штамповать абзац, вырезанный Hidden. Каждый
|
||||
* рерайт работает только содержимым одной части, поэтому по-частная
|
||||
* цепочка эквивалентна последовательным полным проходам. Исключения из
|
||||
* «по-частности» — контексты, читаемые один раз до цикла: правило 5
|
||||
@@ -59,7 +62,7 @@ public final class DocxRewritePipeline {
|
||||
public static final DocxNormalizer STEP = DocxRewritePipeline::normalize;
|
||||
|
||||
/**
|
||||
* Применяет восемь рерайтов к каждой записи {@code word/*.xml} за один
|
||||
* Применяет девять рерайтов к каждой записи {@code word/*.xml} за один
|
||||
* проход zip.
|
||||
*
|
||||
* @param docx байты .docx (валидный zip)
|
||||
@@ -132,6 +135,10 @@ public final class DocxRewritePipeline {
|
||||
if (next != null) {
|
||||
cur = next;
|
||||
}
|
||||
next = DistributeStampNormalizer.rewrite(name, cur);
|
||||
if (next != null) {
|
||||
cur = next;
|
||||
}
|
||||
if (cur != xml) {
|
||||
changed = true;
|
||||
rewritten = cur.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
@@ -27,6 +27,13 @@ import java.util.regex.Pattern;
|
||||
* обратно к {@code start-indent}. Вложенные таблицы: первой считается ячейка
|
||||
* внешней — принятая аппроксимация (компенсация всё равно от default
|
||||
* cellMar). Регрессия — WordPdfConverterTest#tableCellPadding_textInsetLikeWord.</li>
|
||||
* <li><b>distribute → justify-пара.</b> docx4j для {@code w:jc="distribute"}
|
||||
* не эмитит в FO ничего; по якорю-закладке {@code pj-distribute-…}
|
||||
* (DistributeStampNormalizer, правило 12) блоку дописывается
|
||||
* {@code text-align="justify" text-align-last="justify"} — Word растягивает
|
||||
* пробелы всех строк, включая последнюю (Part 1 §17.18.44). Регрессия —
|
||||
* LayoutPostRendererTest (фильтр),
|
||||
* WordPdfConverterTest#distribute_allLinesReachRightMargin (конвейер).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>{@code lineRule="auto"} НЕ правится: высота «single» 13.4277pt@11pt,
|
||||
@@ -56,6 +63,14 @@ public final class LayoutPostRenderer implements FORenderer {
|
||||
private static final double IN_TO_PT = 72.0;
|
||||
|
||||
private static final Pattern TABLE = Pattern.compile("<fo:table\\b[^>]*>");
|
||||
/**
|
||||
* Якорь distribute-абзаца: fo:inline с id закладки-штампа. docx4j пишет
|
||||
* его DOM-поддеревом ({@code XsltCommonFunctions.toNode}), на сериализации
|
||||
* префикс может не унаследоваться — форма {@code <inline xmlns="fo-uri" …/>},
|
||||
* поэтому префикс факультативен.
|
||||
*/
|
||||
private static final Pattern DISTRIBUTE_STAMP =
|
||||
Pattern.compile("<(?:fo:)?inline\\b[^>]*\\bid=\"pj-distribute-[^\"]*\"[^>]*/>");
|
||||
private static final Pattern START_INDENT = Pattern.compile("start-indent=\"(-?[0-9.]+)pt\"");
|
||||
private static final Pattern FIRST_CELL = Pattern.compile("<fo:table-cell\\b[^>]*>");
|
||||
private static final Pattern PADDING_LEFT =
|
||||
@@ -84,7 +99,59 @@ public final class LayoutPostRenderer implements FORenderer {
|
||||
* возвращает ту же строку.
|
||||
*/
|
||||
static String fix(String fo) {
|
||||
return compensateTablePadding(fo);
|
||||
return compensateTablePadding(justifyDistributed(fo));
|
||||
}
|
||||
|
||||
/**
|
||||
* Абзац со штампом {@code w:jc="distribute"} (якорь-закладка
|
||||
* {@code pj-distribute-…} от {@link DistributeStampNormalizer}) получает
|
||||
* пару {@code text-align="justify" text-align-last="justify"} —
|
||||
* канонический FO-эквивалент Word-раскладки (Part 1 §17.18.44; пин
|
||||
* поведения — форк DistributeLineTestCase). Атрибут дописывается в тег
|
||||
* ближайшего открывающего {@code fo:block} перед якорем; уже заданное
|
||||
* {@code text-align} не перетирается.
|
||||
*/
|
||||
private static String justifyDistributed(String fo) {
|
||||
Matcher stamp = DISTRIBUTE_STAMP.matcher(fo);
|
||||
StringBuilder sb = null;
|
||||
int mark = 0;
|
||||
int search = 0;
|
||||
while (stamp.find(search)) {
|
||||
search = stamp.end();
|
||||
int block = fo.lastIndexOf("<fo:block", stamp.start());
|
||||
int blockClose = block < mark ? -1 : fo.indexOf("</fo:block>", block);
|
||||
if (block < mark || block < 0 || (blockClose >= 0 && blockClose < stamp.start())) {
|
||||
continue; // якорь вне блока/после закрытия — править нечего
|
||||
}
|
||||
int blockEnd = fo.indexOf('>', block + "<fo:block".length());
|
||||
if (blockEnd < 0 || fo.charAt(blockEnd - 1) == '/') {
|
||||
continue; // пустой самозакрывающийся блок — не наш случай
|
||||
}
|
||||
String fixed = addJustify(fo.substring(block, blockEnd + 1));
|
||||
if (fixed != null) {
|
||||
if (sb == null) {
|
||||
sb = new StringBuilder(fo.length() + 64);
|
||||
}
|
||||
sb.append(fo, mark, block).append(fixed);
|
||||
mark = blockEnd + 1;
|
||||
}
|
||||
}
|
||||
return sb == null ? fo : sb.append(fo, mark, fo.length()).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return тег блока с дописанными justify-свойствами либо {@code null},
|
||||
* если {@code text-align-last} уже задан
|
||||
*/
|
||||
private static String addJustify(String blockTag) {
|
||||
if (blockTag.contains("text-align-last=")) {
|
||||
return null;
|
||||
}
|
||||
String attrs = blockTag.contains("text-align=\"")
|
||||
? " text-align-last=\"justify\""
|
||||
: " text-align=\"justify\" text-align-last=\"justify\"";
|
||||
int close = blockTag.endsWith("/>") ? blockTag.length() - 2 : blockTag.length() - 1;
|
||||
return blockTag.substring(0, close) + attrs + blockTag.substring(close);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -22,6 +22,7 @@ import org.apache.poi.xwpf.usermodel.XWPFAbstractNum;
|
||||
import org.apache.poi.xwpf.usermodel.XWPFNumbering;
|
||||
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
|
||||
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
|
||||
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.Color;
|
||||
@@ -76,6 +77,7 @@ public final class SampleDocxGenerator {
|
||||
exoticGlyphs(dir.resolve("exotic-glyphs.docx"));
|
||||
tooManyPages(dir.resolve("too-many-pages.docx"));
|
||||
staleCache(dir.resolve("stale-cache.docx"));
|
||||
distribute(dir.resolve("distribute.docx"));
|
||||
|
||||
System.out.println("Готово: " + dir.toAbsolutePath());
|
||||
}
|
||||
@@ -439,6 +441,35 @@ public final class SampleDocxGenerator {
|
||||
/** Сколько {@code w:t} в фикстуре stale-cache остаются без маркера. */
|
||||
private static final int STALE_CACHE_UNMARKED_RUNS = 1;
|
||||
|
||||
/**
|
||||
* w:jc="distribute" (+ контроль {@code both} и левый): Word растягивает
|
||||
* пробелы всех строк, включая последнюю (Part 1 §17.18.44); docx4j для
|
||||
* DISTRIBUTE не эмитит ничего, без правила 12 абзац печатается влево.
|
||||
* Регрессия — WordPdfConverterTest#distribute_allLinesReachRightMargin.
|
||||
*/
|
||||
private static void distribute(Path out) throws Exception {
|
||||
try (XWPFDocument doc = new XWPFDocument()) {
|
||||
heading(doc, "Distribute justification", "Calibri");
|
||||
String text = "alpha bravo charlie delta echo foxtrot golf hotel "
|
||||
+ "india juliett kilo lima mike november oscar papa quebec romeo sierra";
|
||||
XWPFParagraph p = doc.createParagraph();
|
||||
setJc(p, STJc.DISTRIBUTE);
|
||||
run(p, text, "Calibri", false, false);
|
||||
p = doc.createParagraph();
|
||||
run(p, text, "Calibri", false, false);
|
||||
p = doc.createParagraph();
|
||||
setJc(p, STJc.BOTH);
|
||||
run(p, text, "Calibri", false, false);
|
||||
save(doc, out);
|
||||
}
|
||||
}
|
||||
|
||||
/** w:jc прямо в pPr: POI-перечисление Alignment не знает DISTRIBUTE. */
|
||||
private static void setJc(XWPFParagraph p, STJc.Enum val) {
|
||||
CTPPr pPr = p.getCTP().isSetPPr() ? p.getCTP().getPPr() : p.getCTP().addNewPPr();
|
||||
pPr.addNewJc().setVal(val);
|
||||
}
|
||||
|
||||
// ================== Вспомогательные ==================
|
||||
|
||||
/** Абзац-заголовок: POI 5.5 не имеет createHeading, поэтому
|
||||
|
||||
@@ -2932,4 +2932,61 @@ class WordPdfConverterTest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* w:jc="distribute" (Part 1 §17.18.44): Word растягивает пробелы всех строк,
|
||||
* включая последнюю. docx4j для DISTRIBUTE не эмитит в FO ничего — без
|
||||
* правила 12 (DistributeStampNormalizer) и justify-пары (LayoutPostRenderer)
|
||||
* абзац печатается по левому краю. Фикстура — samples/distribute.docx:
|
||||
* один и тот же текст абзацами distribute / left / both; правое поле
|
||||
* A4 72pt → 523.28pt; хвостовая строка трёхсловная («quebec romeo sierra») —
|
||||
* одно слово растягивать нечем (нет склейки), такие строки Word тоже оставляет
|
||||
* на месте. last-line justify пинут в форке (DistributeLineTestCase).
|
||||
*/
|
||||
@Test
|
||||
void distribute_allLinesReachRightMargin() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("distribute.docx"), "distribute");
|
||||
Map<Long, double[]> ends = new LinkedHashMap<>();
|
||||
Map<Long, StringBuilder> lineTexts = new LinkedHashMap<>();
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
PDFTextStripper stripper = new PDFTextStripper() {
|
||||
@Override
|
||||
protected void processTextPosition(org.apache.pdfbox.text.TextPosition tp) {
|
||||
String u = tp.getUnicode();
|
||||
if (!u.trim().isEmpty()) {
|
||||
long y = Math.round(tp.getYDirAdj());
|
||||
double right = tp.getXDirAdj() + tp.getWidthDirAdj();
|
||||
double[] max = ends.computeIfAbsent(y, k -> new double[1]);
|
||||
max[0] = Math.max(max[0], right);
|
||||
lineTexts.computeIfAbsent(y, k -> new StringBuilder()).append(u);
|
||||
}
|
||||
super.processTextPosition(tp);
|
||||
}
|
||||
};
|
||||
String text = stripper.getText(doc);
|
||||
assertEquals(3, count(text, "quebec"), "все три абзаца напечатаны");
|
||||
}
|
||||
List<Double> tails = new ArrayList<>();
|
||||
for (Map.Entry<Long, StringBuilder> e : lineTexts.entrySet()) {
|
||||
if (e.getValue().toString().trim().endsWith("sierra")) {
|
||||
tails.add(Math.round(ends.get(e.getKey())[0] * 10) / 10.0);
|
||||
}
|
||||
}
|
||||
assertEquals(3, tails.size(), "найдены концы трёх абзацев");
|
||||
double right = 595.276 - 72.0;
|
||||
assertTrue(Math.abs(tails.get(0) - right) < 1.5,
|
||||
"distribute: последняя строка дотянута до правого поля, конец=" + tails.get(0));
|
||||
assertTrue(tails.get(1) < right - 20.0,
|
||||
"левый абзац остаётся рваным: конец=" + tails.get(1));
|
||||
assertTrue(tails.get(2) < right - 20.0,
|
||||
"both не растягивает последнюю строку: конец=" + tails.get(2));
|
||||
}
|
||||
|
||||
private static int count(String hay, String needle) {
|
||||
int n = 0;
|
||||
for (int i = hay.indexOf(needle); i >= 0; i = hay.indexOf(needle, i + 1)) {
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
package ru.pjandro.wordpdf.internal;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Юниты {@link DistributeStampNormalizer}: штамп {@code w:jc="distribute"}
|
||||
* закладкой-якорем после {@code </w:pPr>} (Part 1 §17.18.44, правило 12).
|
||||
*/
|
||||
class DistributeStampNormalizerTest {
|
||||
|
||||
private static String document(String body) {
|
||||
return "<w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">"
|
||||
+ "<w:body>" + body + "</w:body></w:document>";
|
||||
}
|
||||
|
||||
/** Абзац с pPr (или без, если pPrInner пуст) и одним раном. */
|
||||
private static String para(String pPrInner, String text) {
|
||||
return "<w:p>" + (pPrInner.isEmpty()
|
||||
? "" : "<w:pPr>" + pPrInner + "</w:pPr>")
|
||||
+ "<w:r><w:t>" + text + "</w:t></w:r></w:p>";
|
||||
}
|
||||
|
||||
private static final String JC_DISTRIBUTE = "<w:jc w:val=\"distribute\"/>";
|
||||
|
||||
/** distribute-абзац: штамп сразу после </w:pPr>, id=1 (закладок нет). */
|
||||
@Test
|
||||
void distribute_paragraphStampedAfterPPr() {
|
||||
String xml = document(para(JC_DISTRIBUTE, "раз"));
|
||||
String fixed = DistributeStampNormalizer.rewrite("word/document.xml", xml);
|
||||
assertEquals(document(para(JC_DISTRIBUTE, "раз")
|
||||
.replace("</w:pPr>", "</w:pPr><w:bookmarkStart w:id=\"1\""
|
||||
+ " w:name=\"pj-distribute-document-1\"/>"
|
||||
+ "<w:bookmarkEnd w:id=\"1\"/>")),
|
||||
fixed);
|
||||
}
|
||||
|
||||
/** Несколько абзацев: имена per-part по счёту, id за max существующих. */
|
||||
@Test
|
||||
void multipleParagraphs_namesAndIdsUnique() {
|
||||
String xml = document(
|
||||
para(JC_DISTRIBUTE, "раз")
|
||||
+ "<w:p><w:pPr><w:jc w:val=\"both\"/></w:pPr>"
|
||||
+ "<w:bookmarkStart w:id=\"41\" w:name=\"_Toc1\"/><w:bookmarkEnd w:id=\"41\"/>"
|
||||
+ "<w:r><w:t>два</w:t></w:r></w:p>"
|
||||
+ para(JC_DISTRIBUTE, "три"));
|
||||
String fixed = DistributeStampNormalizer.rewrite("word/document.xml", xml);
|
||||
assertTrue(fixed.contains("w:name=\"pj-distribute-document-1\""), fixed);
|
||||
assertTrue(fixed.contains("w:name=\"pj-distribute-document-2\""), fixed);
|
||||
assertFalse(fixed.contains("w:name=\"pj-distribute-document-3\""), fixed);
|
||||
assertTrue(fixed.contains("<w:bookmarkStart w:id=\"42\" w:name=\"pj-distribute-document-1\"")
|
||||
&& fixed.contains("<w:bookmarkStart w:id=\"43\" w:name=\"pj-distribute-document-2\""),
|
||||
"id продолжение существующих: " + fixed);
|
||||
assertEquals(2, countOf(fixed, "<w:bookmarkEnd w:id=\"42\"/>") + countOf(fixed, "<w:bookmarkEnd w:id=\"43\"/>"),
|
||||
"каждому start — свой end");
|
||||
}
|
||||
|
||||
private static int countOf(String s, String sub) {
|
||||
return (s.length() - s.replace(sub, "").length()) / sub.length();
|
||||
}
|
||||
|
||||
/** Повторный вызов на проштампованном — null (идемпотентность). */
|
||||
@Test
|
||||
void alreadyStamped_returnsNull() {
|
||||
String xml = document(para(JC_DISTRIBUTE, "раз"));
|
||||
String once = DistributeStampNormalizer.rewrite("word/document.xml", xml);
|
||||
assertNull(DistributeStampNormalizer.rewrite("word/document.xml", once));
|
||||
}
|
||||
|
||||
/** jc=center/both/нет — не our case: null. */
|
||||
@Test
|
||||
void otherJustification_returnsNull() {
|
||||
String xml = document(para("<w:jc w:val=\"center\"/>", "раз") + para("", "два"));
|
||||
assertNull(DistributeStampNormalizer.rewrite("word/document.xml", xml));
|
||||
}
|
||||
|
||||
/** jc вне w:pPr (например, w:jc строки таблицы в trPr) — не штампуется. */
|
||||
@Test
|
||||
void jcOutsidePPr_returnsNull() {
|
||||
String xml = document("<w:tr><w:trPr><w:jc w:val=\"distribute\"/></w:trPr>"
|
||||
+ para("", "раз") + "</w:tr>");
|
||||
assertNull(DistributeStampNormalizer.rewrite("word/document.xml", xml));
|
||||
}
|
||||
|
||||
/** numbering.xml (уровни списков с pPrGeneral) — часть не штампуется вовсе. */
|
||||
@Test
|
||||
void nonContentPart_returnsNull() {
|
||||
String xml = "<w:numbering><w:lvl><w:pPr>" + JC_DISTRIBUTE + "</w:pPr></w:lvl></w:numbering>";
|
||||
assertNull(DistributeStampNormalizer.rewrite("word/numbering.xml", xml));
|
||||
}
|
||||
|
||||
/** footnotes.xml — штампуется с меткой части (имена не коллизируют с document). */
|
||||
@Test
|
||||
void footnotes_partTagInName() {
|
||||
String xml = document(para(JC_DISTRIBUTE, "сноска"));
|
||||
String fixed = DistributeStampNormalizer.rewrite("word/footnotes.xml", xml);
|
||||
assertTrue(fixed.contains("w:name=\"pj-distribute-footnotes-1\""), fixed);
|
||||
}
|
||||
|
||||
/** Самозакрывающийся абзац — не ломает разбор. */
|
||||
@Test
|
||||
void selfClosingParagraph_survives() {
|
||||
String xml = document("<w:p w:rsidR=\"00A1\"/><w:p><w:pPr>" + JC_DISTRIBUTE
|
||||
+ "</w:pPr><w:r><w:t>тут</w:t></w:r></w:p>");
|
||||
String fixed = DistributeStampNormalizer.rewrite("word/document.xml", xml);
|
||||
assertTrue(fixed.contains("pj-distribute-document-1"), fixed);
|
||||
}
|
||||
|
||||
/** Контракт zip-пути: нечего менять → тот же массив; есть штамп → новые байты со штампом. */
|
||||
@Test
|
||||
void normalize_identityWhenNothing_stampWhenDistribute() throws IOException {
|
||||
byte[] clean = docx("<w:p><w:r><w:t>чисто</w:t></w:r></w:p>");
|
||||
assertSame(clean, DistributeStampNormalizer.normalize(clean));
|
||||
|
||||
byte[] dirty = docx("<w:p><w:pPr>" + JC_DISTRIBUTE + "</w:pPr>"
|
||||
+ "<w:r><w:t>тяни</w:t></w:r></w:p>");
|
||||
byte[] fixed = DistributeStampNormalizer.normalize(dirty);
|
||||
assertNotSame(dirty, fixed);
|
||||
String part = new String(entry(fixed, "word/document.xml"), StandardCharsets.UTF_8);
|
||||
assertTrue(part.contains("w:name=\"pj-distribute-document-1\""), part);
|
||||
}
|
||||
|
||||
// ================== Синтетический .docx ==================
|
||||
|
||||
private static byte[] docx(String body) throws IOException {
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zos = new ZipOutputStream(bos)) {
|
||||
zos.putNextEntry(new ZipEntry("[Content_Types].xml"));
|
||||
zos.write("<Types/>".getBytes(StandardCharsets.UTF_8));
|
||||
zos.closeEntry();
|
||||
zos.putNextEntry(new ZipEntry("word/document.xml"));
|
||||
zos.write(document(body).getBytes(StandardCharsets.UTF_8));
|
||||
zos.closeEntry();
|
||||
zos.putNextEntry(new ZipEntry("word/numbering.xml"));
|
||||
zos.write("<w:numbering/>".getBytes(StandardCharsets.UTF_8));
|
||||
zos.closeEntry();
|
||||
}
|
||||
return bos.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] entry(byte[] zip, String name) throws IOException {
|
||||
try (java.util.zip.ZipInputStream zis =
|
||||
new java.util.zip.ZipInputStream(new java.io.ByteArrayInputStream(zip))) {
|
||||
ZipEntry e;
|
||||
while ((e = zis.getNextEntry()) != null) {
|
||||
if (e.getName().equals(name)) {
|
||||
return zis.readAllBytes();
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("нет записи " + name);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package ru.pjandro.wordpdf.internal;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@@ -125,4 +126,57 @@ class LayoutPostRendererTest {
|
||||
String fo = "<fo:root><fo:block font-family=\"DejaVu Sans\">text</fo:block></fo:root>";
|
||||
assertSame(fo, LayoutPostRenderer.fix(fo));
|
||||
}
|
||||
|
||||
// ================== distribute-штамп ==================
|
||||
|
||||
/** Якорь-закладка: блок получает пару justify-свойств (Part 1 §17.18.44). */
|
||||
@Test
|
||||
void distributeStamp_justifyPairAdded() {
|
||||
String fo = "<fo:block font-family=\"Carlito Regular\"><fo:inline id=\"pj-distribute-document-1\"/>"
|
||||
+ "alpha bravo</fo:block>";
|
||||
String fixed = LayoutPostRenderer.fix(fo);
|
||||
assertTrue(fixed.contains("<fo:block font-family=\"Carlito Regular\""
|
||||
+ " text-align=\"justify\" text-align-last=\"justify\">"), fixed);
|
||||
}
|
||||
|
||||
/** Реальная форма сериализации docx4j: DOM-поддерево без префикса fo. */
|
||||
@Test
|
||||
void distributeStamp_unprefixedInline_stillStamped() {
|
||||
String fo = "<fo:block font-size=\"11.0pt\">"
|
||||
+ "<inline xmlns=\"http://www.w3.org/1999/XSL/Format\" id=\"pj-distribute-document-1\"/>"
|
||||
+ "alpha</fo:block>";
|
||||
String fixed = LayoutPostRenderer.fix(fo);
|
||||
assertTrue(fixed.contains("<fo:block font-size=\"11.0pt\""
|
||||
+ " text-align=\"justify\" text-align-last=\"justify\">"), fixed);
|
||||
}
|
||||
|
||||
/** Текст уже выровнен (both + наш штамп) — дописывается только align-last. */
|
||||
@Test
|
||||
void distributeStamp_existingTextAlignPreserved() {
|
||||
String fo = "<fo:block text-align=\"justify\"><fo:inline id=\"pj-distribute-document-2\"/>x</fo:block>";
|
||||
String fixed = LayoutPostRenderer.fix(fo);
|
||||
assertTrue(fixed.contains("text-align=\"justify\" text-align-last=\"justify\""), fixed);
|
||||
assertFalse(fixed.contains("text-align-last=\"justify\" text-align-last"), fixed);
|
||||
}
|
||||
|
||||
/** text-align-last уже задан — блок не трогается, чужая закладка молча живёт. */
|
||||
@Test
|
||||
void distributeStamp_alignLastAlreadySet_untouched() {
|
||||
String fo = "<fo:block text-align-last=\"center\"><fo:inline id=\"pj-distribute-footnotes-1\"/>x</fo:block>";
|
||||
assertSame(fo, LayoutPostRenderer.fix(fo));
|
||||
}
|
||||
|
||||
/** Закладка вне fo:block (после закрытия) — правки нет, FO не ломается. */
|
||||
@Test
|
||||
void distributeStamp_outsideBlock_untouched() {
|
||||
String fo = "<fo:block>до</fo:block><fo:inline id=\"pj-distribute-document-1\"/>";
|
||||
assertSame(fo, LayoutPostRenderer.fix(fo));
|
||||
}
|
||||
|
||||
/** Обычная закладка пользователя (не pj-distribute) — игнор. */
|
||||
@Test
|
||||
void userBookmark_ignored() {
|
||||
String fo = "<fo:block><fo:inline id=\"_Toc12345\"/>x</fo:block>";
|
||||
assertSame(fo, LayoutPostRenderer.fix(fo));
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
Reference in New Issue
Block a user