Мост .doc → .docx: стили (STSH), таблицы (TAP/TDefTable/Brc), списки (PlfLst/PlfLfo → numbering.xml), секции и колонтитуки каждой секции; табуляции колонтитулов через sprmPChgTabs
PR checks / web (pull_request) Successful in 39s
PR checks / java (pull_request) Successful in 1m34s
Main: tests, deploy, autotests / web (push) Successful in 31s
Main: tests, deploy, autotests / java (push) Successful in 1m4s
Main: tests, deploy, autotests / images-web (push) Successful in 32s
Main: tests, deploy, autotests / images-app (push) Successful in 42s
Main: tests, deploy, autotests / deploy (push) Successful in 1m40s
Main: tests, deploy, autotests / autotests (push) Failing after 41s
Main: tests, deploy, autotests / rollback (push) Successful in 1m26s

- Styles: STSH (§2.9.271) → цепочки papx/chpx стилей, base-first last-wins, снисходительный разбор
- Tables: TAP (§2.6.3) → w:tbl/w:tr/w:tc: сетка TDefTable (§2.9.321), границы §2.9.302/.303, выравнивание sprmTJc/sprmTJc90; деградация строки без корректной сетки
- Lists: PlfLst/PlfLfo (§2.9.200/.201) → word/numbering.xml, w:numPr в pPr (sprmPIlfo/sprmPIlvl, ilvl=0x0C и неразрешённый numId — без numPr)
- Sections/Headers/PapxIndex: PlcfSed → posекционные sectPr (continuous, кламп к ccpText), Plcfhdd → headerN/footerN каждой секции, istd из PapxInFkp сохраняется
- Табуляции: sprmPChgTabs (0xC615, §2.9.182) — радиус удаления rgdxaClose (XAS_plusOne), длина 0xFF-операнда 3+4n+3m (обрыв обхода grpprl больше не теряет свойства стиля); sprmPChgTabsPapx (0xC60D) без изменений. Чинит слипание табуляций колонтитулов (develop/docTest.doc: 193/265 → 283/481 pt, LO-эталон 277/468)
- Доки: ms-doc-full.md ([MS-DOC] с packet diagram'ами и таблицами sprm), AGENTS.md, .gitignore, compose.dev.yml (--force-recreate)
This commit was merged in pull request #76.
This commit is contained in:
Pjandro
2026-10-31 18:18:46 +00:00
parent ef3feaa94d
commit f3f3db342f
29 changed files with 63841 additions and 265 deletions
@@ -9,8 +9,10 @@ import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.io.IOException;
@@ -928,6 +930,27 @@ class WordPdfConverterTest {
assertEquals(196.15, xOfMarker(pdf, 'Q'), 1.0);
}
/**
* w:jc="center" БЕЗ w:tblInd: Word центрирует сетку, текст = поле +
* (полоса−ΣgridCol)/2 + padding. TableIndentNormalizer сворачивает jc с
* X=0 в абсолютный tblInd — иначе docx4j пишет центрированию start-indent
* без вычета cellMar и padding-компенсация LayoutPostRenderer уводит
* текст на +5.4pt (замер: 165.57). Та же геометрия и та же ожидаемая
* точка, что у docFooterTableCentered_shiftedLikeWord.
*/
@Test
void tableCenteredNoIndent_shiftedLikeWord() throws Exception {
byte[] docx = minimalDocx("<w:tbl><w:tblPr><w:jc w:val=\"center\"/></w:tblPr>"
+ "<w:tblGrid><w:gridCol w:w=\"3000\"/><w:gridCol w:w=\"3000\"/></w:tblGrid>"
+ "<w:tr><w:tc><w:p><w:r><w:t>Q</w:t></w:r></w:p></w:tc></w:tr></w:tbl>",
"<w:sectPr><w:pgSz w:w=\"11906\" w:h=\"16838\"/>"
+ "<w:pgMar w:top=\"1134\" w:right=\"850\" w:bottom=\"1134\" w:left=\"1134\""
+ " w:header=\"720\" w:footer=\"720\" w:gutter=\"0\"/></w:sectPr>");
Path pdf = convertPdf(docx, "t");
// margin 56.7 + (9922−6000)/2÷20 = 98.05 + cell padding 5.4
assertEquals(160.15, xOfMarker(pdf, 'Q'), 1.0);
}
/**
* w:suff="space": Word пишет после номера обычный пробел (Part 1
* §17.3.1.28), docx4j разделитель не эмитит вовсе (дамп n4.fo).
@@ -1314,4 +1337,445 @@ class WordPdfConverterTest {
"лимит 1 страница не удержал двухстраничный .doc");
}
/**
* Синтетический .doc со списками (ни одна фикстура заказчика списков не
* содержит — крафт POIFS, дубль хелперов DocToDocxFormattingTest):
* PlfLst/PlfLfo → numbering.xml + w:numPr — decimal «1.»/«2.», буквенный
* подуровень «a)»/«b)», Symbol-буллет (PUA в w:lvl чинит
* SymbolFontNormalizer — та же цепочка, что symbol-bullets.docx).
* Регрессия — internal.doc.Lists + DocxBody#numPrXml.
*/
@Test
void docLists_numberingAndBulletsRendered() throws Exception {
Path pdf = convertPdf(listsDoc(), "doc-lists");
String text = norm(pdfText(pdf));
assertTrue(text.contains("1."), "decimal-номер: " + text);
assertTrue(text.contains("2."), "второй пункт: " + text);
assertTrue(text.contains("a)"), "буквенный подуровень: " + text);
assertTrue(text.contains("b)"), "второй пункт подуровня: " + text);
assertTrue(text.contains("\u2022"), "Symbol-буллет: " + text);
assertFalse(text.contains("#"), ".notdef-боксы в тексте");
}
/**
* Синтетический .doc с двумя секциями (крафт POIFS, дубль хелперов
* DocToDocxFormattingTest): колонтитуки каждой секции — свой sectPr.
* Секция 0: odd hdr «ШАПКА-1», odd ftr «ПОДВАЛ-1»; секция 1: odd hdr
* «ШАПКА-2», odd ftr не определён ([x,x), §2.4.4) → docx4j наследует
* «ПОДВАЛ-1». Страница 1 — ШАПКА-1+ПОДВАЛ-1, страница 2 — ШАПКА-2 +
* унаследованный ПОДВАЛ-1 без ШАПКА-1. Регрессия — internal.doc
* (Sections/Headers/DocToDocx, многосекционный перенос колонтитуков).
*/
@Test
void docMultiSection_perSectionHeaders() throws Exception {
Path pdf = convertPdf(multiSectionDoc(), "doc-multi-section");
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
assertEquals(2, doc.getNumberOfPages(), "межсекционный разрыв не дал страницу");
}
String p1 = norm(pdfPageText(pdf, 1));
String p2 = norm(pdfPageText(pdf, 2));
assertTrue(p1.contains("ШАПКА-1"), "заголовок секции 1: " + p1);
assertTrue(p1.contains("ПОДВАЛ-1"), "футер секции 1: " + p1);
assertTrue(p2.contains("ШАПКА-2"), "заголовок секции 2: " + p2);
assertFalse(p2.contains("ШАПКА-1"), "колонтитук секции 1 утек во 2-ю: " + p2);
assertTrue(p2.contains("ПОДВАЛ-1"),
"неопределённый футер секции 2 должен наследоваться: " + p2);
}
/**
* Таблица с w:jc=center + w:tblInd в word/header1.xml: полоса набора у
* header-части своя отсутствует — TableIndentNormalizer.rewritePart
* сворачивает по band из document.xml (9922): (9922−6000)/2+720 = 2681
* twips = 134.05pt (без свёртки docx4j игнорирует tblInd при jc≠left —
* x был бы 160.15). Регрессия — TableIndentNormalizer#rewritePart +
* DocxRewritePipeline (band из document.xml).
*/
@Test
void headerTableIndent_centeredInHeader() throws Exception {
String w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
String hdr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<w:hdr xmlns:w=\"" + w + "\" xmlns:r=\"http://schemas.openxmlformats.org"
+ "/officeDocument/2006/relationships\">"
+ "<w:tbl><w:tblPr><w:jc w:val=\"center\"/>"
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/></w:tblPr>"
+ "<w:tblGrid><w:gridCol w:w=\"3000\"/><w:gridCol w:w=\"3000\"/></w:tblGrid>"
+ "<w:tr><w:tc><w:p><w:r><w:t>Q</w:t></w:r></w:p></w:tc></w:tr></w:tbl>"
+ "</w:hdr>";
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(out)) {
putZip(zos, "[Content_Types].xml",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">"
+ "<Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>"
+ "<Default Extension=\"xml\" ContentType=\"application/xml\"/>"
+ "<Override PartName=\"/word/document.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml\"/>"
+ "<Override PartName=\"/word/header1.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml\"/>"
+ "</Types>");
putZip(zos, "_rels/.rels",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">"
+ "<Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\" Target=\"word/document.xml\"/>"
+ "</Relationships>");
putZip(zos, "word/document.xml",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<w:document xmlns:w=\"" + w + "\""
+ " xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\">"
+ "<w:body><w:p><w:r><w:t>МАРКЕР</w:t></w:r></w:p>"
+ "<w:sectPr><w:headerReference w:type=\"default\" r:id=\"rId1\"/>"
+ "<w:pgSz w:w=\"11906\" w:h=\"16838\"/>"
+ "<w:pgMar w:top=\"1134\" w:right=\"850\" w:bottom=\"1134\" w:left=\"1134\""
+ " w:header=\"720\" w:footer=\"720\" w:gutter=\"0\"/></w:sectPr>"
+ "</w:body></w:document>");
putZip(zos, "word/_rels/document.xml.rels",
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">"
+ "<Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/header\" Target=\"header1.xml\"/>"
+ "</Relationships>");
putZip(zos, "word/header1.xml", hdr);
}
Path pdf = convertPdf(out.toByteArray(), "hdr-table");
assertTrue(norm(pdfText(pdf)).contains("МАРКЕР"), "тело пропало");
// margin 56.7 + tblInd 134.05 + cell padding 5.4 — та же арифметика,
// что у body-регрессии tableIndentCentered_shiftedLikeWord
assertEquals(196.15, xOfMarker(pdf, 'Q'), 1.0);
}
// --- крафт .doc с двумя секциями (дубль DocToDocxFormattingTest) -----
private static final int MULTI_TEXT_FC = 2048;
/**
* Две секции: «Текст1⌬Текст2⏎» (0x0C на CP6), PlcfSed aCp [0,7,14]
* (fcSepx=0 — дефолты Word 97 у обеих); Header Document: 6 разделителей,
* у секции 0 odd hdr «ШАПКА-1» + odd ftr «ПОДВАЛ-1», у секции 1 odd hdr
* «ШАПКА-2», odd ftr — пустой диапазон [x,x) (наследование).
*/
private static byte[] multiSectionDoc() throws IOException {
String text = "Текст1" + (char) 0x0C + "Текст2\r"
+ "\r\r\r\r\r\r" + "\r" + "ШАПКА-1\r" + "\r" + "ПОДВАЛ-1\r" + "\r" + "\r"
+ "\r" + "ШАПКА-2\r" + "\r" + "\r" + "\r";
byte[] wd = new byte[MULTI_TEXT_FC + text.length() * 2];
put16(wd, 0, 0xA5EC);
put16(wd, 2, 0x00C1);
put16(wd, 10, 1 << 9);
put16(wd, 62, 4);
put32(wd, 64, wd.length);
put32(wd, 76, 14); // ccpText
put32(wd, 80, 0); // ccpFtn
put32(wd, 84, text.length() - 14); // ccpHdd
put16(wd, 152, 98);
pair(wd, 6, 0, 36); // PlcfSed: aCp(3) + SED(2×12)
pair(wd, 11, 36, 76); // Plcfhdd: aCp(19)
pair(wd, 33, 112, 21); // Clx
byte[] t = text.getBytes(StandardCharsets.UTF_16LE);
System.arraycopy(t, 0, wd, MULTI_TEXT_FC, t.length);
byte[] tab = new byte[133];
// PlcfSed @0: aCp [0, 7, 14], fcSepx=0/0 (дефолтная геометрия)
put32(tab, 0, 0);
put32(tab, 4, 7);
put32(tab, 8, 14);
// Plcfhdd @36: aCp относительные; odd ftr секции 1 — [37,37) (пустая)
int[] hdd = {0, 1, 2, 3, 4, 5, 6, 7, 15, 16, 25, 26, 27,
28, 36, 37, 37, 38, 39};
for (int i = 0; i < hdd.length; i++) {
put32(tab, 36 + i * 4, hdd[i]);
}
// Clx @112: Pcdt, один несжатый кусок
tab[112] = 0x02;
put32(tab, 113, 16);
put32(tab, 117, 0);
put32(tab, 121, text.length());
put32(tab, 127, MULTI_TEXT_FC);
try (POIFSFileSystem fs = new POIFSFileSystem();
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
fs.getRoot().createDocument("WordDocument", new ByteArrayInputStream(wd));
fs.getRoot().createDocument("1Table", new ByteArrayInputStream(tab));
fs.getRoot().createDocument("Data", new ByteArrayInputStream(new byte[64]));
fs.writeFilesystem(out);
return out.toByteArray();
}
}
// --- крафт .doc с таблицей по центру в футере (sprmTJc) -------------
/**
* Одна секция, A4 11906×16838 с полями 1134/850 (Sepx — та же полоса
* набора 9922, что у docx-регрессии tableIndentCentered_shiftedLikeWord):
* body «T⏎»; odd footer — табличная строка (ячейка «Q␇» с sprmPFInTable +
* TTP-абзац «␇» с TAP: sprmTDefTable 2×3000 + sprmTJc=1 → center) +
* guard-¶ (§2.4.4 — отдельный ¶ после последней строки).
*/
private static byte[] footerCenterTableDoc() throws IOException {
String text = "T\r" + "\r\r\r\r\r\r" + "\r\r\r"
+ "Q" + (char) 7 + (char) 7 + "\r" + "\r\r";
byte[] wd = new byte[MULTI_TEXT_FC + text.length() * 2];
put16(wd, 0, 0xA5EC);
put16(wd, 2, 0x00C1);
put16(wd, 10, 1 << 9);
put16(wd, 62, 4);
put32(wd, 64, wd.length);
put32(wd, 76, 2); // ccpText
put32(wd, 80, 0); // ccpFtn
put32(wd, 84, text.length() - 2); // ccpHdd
put16(wd, 152, 98);
pair(wd, 6, 0, 20); // PlcfSed: aCp(2) + SED(1), fcSepx @10
pair(wd, 11, 20, 52); // Plcfhdd: aCp(13)
pair(wd, 13, 72, 12); // PlcfBtePapx
pair(wd, 33, 84, 21); // Clx
// Sepx @1024 (WordDocument): cb(2) + grpprl — геометрия секции
byte[] sepx = concat(prl2(0xB01F, 11906), prl2(0xB020, 16838),
prl2(0xB021, 1134), prl2(0xB022, 850));
put16(wd, 1024, sepx.length);
System.arraycopy(sepx, 0, wd, 1026, sepx.length);
byte[] t = text.getBytes(StandardCharsets.UTF_16LE);
System.arraycopy(t, 0, wd, MULTI_TEXT_FC, t.length);
// PapxFkp pn=3: «Q␇» (InTable) + «␇» (TTP: сетка 2×3000 + sprmTJc=1)
int page = 3 * 512;
put32(wd, page, MULTI_TEXT_FC + 22);
put32(wd, page + 4, MULTI_TEXT_FC + 26);
put32(wd, page + 8, MULTI_TEXT_FC + 28);
wd[page + 12] = 87;
wd[page + 12 + 13] = 94;
wd[page + 511] = 2; // cpara
byte[] inTable = prl(0x2416, 1);
papxEntry(wd, page, 87, inTable);
papxEntry(wd, page, 94, concat(inTable, prl(0x2417, 1),
tdefTable(2, new int[] {0, 3000, 6000}), prl2(0x548A, 1)));
byte[] tab = new byte[105];
put32(tab, 0, 0); // PlcfSed aCp [0, 2)
put32(tab, 4, 2);
put32(tab, 10, 1024); // SED fcSepx (sedBase 8 + 2)
// Plcfhdd @20: aCp относительные; odd footer — [9,14) («Q␇␇» + guard-¶)
int[] hdd = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 13, 14, 15};
for (int i = 0; i < hdd.length; i++) {
put32(tab, 20 + i * 4, hdd[i]);
}
put32(tab, 72, MULTI_TEXT_FC + 22); // PlcfBtePapx aFc + pn=3
put32(tab, 76, MULTI_TEXT_FC + 28);
put32(tab, 80, 3);
tab[84] = 0x02; // Clx Pcdt, один несжатый кусок
put32(tab, 85, 16);
put32(tab, 89, 0);
put32(tab, 93, text.length());
put32(tab, 99, MULTI_TEXT_FC);
try (POIFSFileSystem fs = new POIFSFileSystem();
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
fs.getRoot().createDocument("WordDocument", new ByteArrayInputStream(wd));
fs.getRoot().createDocument("1Table", new ByteArrayInputStream(tab));
fs.getRoot().createDocument("Data", new ByteArrayInputStream(new byte[64]));
fs.writeFilesystem(out);
return out.toByteArray();
}
}
/** TDefTableOperand (§2.9.321): cb(2)=остаток+1, ncols, centers, TC80 по 20 Б. */
private static byte[] tdefTable(int ncols, int[] centers) {
byte[] op = new byte[3 + 2 * centers.length + 20 * ncols];
put16(op, 0, op.length - 2 + 1);
op[2] = (byte) ncols;
for (int i = 0; i < centers.length; i++) {
put16(op, 3 + 2 * i, centers[i]);
}
return concat(new byte[] {(byte) 0xD608, (byte) (0xD608 >>> 8)}, op);
}
/**
* sprmTJc=1 из TAP футерной строки → w:jc="center" в tblPr (мост),
* docx4j+FOP центрируют таблицу как Word: полоса 9922 = 11906−1134−850,
* x = margin 56.7 + (9922−6000)/2÷20 = 98.05 + cell padding 5.4
* (та же арифметика, что у tableIndentCentered_shiftedLikeWord без
* tblInd). Без переноса sprmTJc таблица прижата к левому краю (x≈62.1).
*/
@Test
void docFooterTableCentered_shiftedLikeWord() throws Exception {
Path pdf = convertPdf(footerCenterTableDoc(), "doc-footer-jc");
assertEquals(160.15, xOfMarker(pdf, 'Q'), 1.0);
}
// --- крафт .doc со списками (дубль DocToDocxFormattingTest) ----------
private static final int LISTS_TEXT_FC = 2048;
/**
* 5 абзацев: «one»/«two» (ilfo=1, ilvl=0 — decimal), «sub1»/«sub2»
* (ilfo=1, ilvl=1 — lowerLetter), «mark» (ilfo=2 — bullet Symbol).
* PlfLst: LSTF lsid=100 (9 уровней) + LSTF lsid=200 (fSimpleList);
* PlfLfo: два LFO без переопределений; SttbfFfn: Symbol на ftc0=0.
*/
private static byte[] listsDoc() throws IOException {
String text = "one\r" + "two\r" + "sub1\r" + "sub2\r" + "mark\r";
byte[] wd = new byte[LISTS_TEXT_FC + text.length() * 2];
put16(wd, 0, 0xA5EC);
put16(wd, 2, 0x00C1);
put16(wd, 10, 1 << 9);
put16(wd, 62, 4);
put32(wd, 64, wd.length);
put32(wd, 76, text.length());
put16(wd, 152, 98);
pair(wd, 6, 0, 20); // PlcfSed
pair(wd, 13, 20, 12); // PlcfBtePapx
pair(wd, 33, 32, 21); // Clx
byte[] t = text.getBytes(StandardCharsets.UTF_16LE);
System.arraycopy(t, 0, wd, LISTS_TEXT_FC, t.length);
int page = 3 * 512;
// rgfc — FC (UTF-16LE): границы «one|two|sub1|sub2|mark|»
int[] rgfc = {LISTS_TEXT_FC, LISTS_TEXT_FC + 8, LISTS_TEXT_FC + 16,
LISTS_TEXT_FC + 26, LISTS_TEXT_FC + 36, LISTS_TEXT_FC + 2 * text.length()};
for (int i = 0; i < rgfc.length; i++) {
put32(wd, page + i * 4, rgfc[i]);
}
int rgbx = page + rgfc.length * 4;
int[] bx = {87, 94, 101, 108, 115};
for (int i = 0; i < bx.length; i++) {
wd[rgbx + i * 13] = (byte) bx[i];
}
wd[page + 511] = 5; // cpara
papxEntry(wd, page, 87, concat(prl2(0x460B, 1), prl(0x260A, 0)));
papxEntry(wd, page, 94, concat(prl2(0x460B, 1), prl(0x260A, 0)));
papxEntry(wd, page, 101, concat(prl2(0x460B, 1), prl(0x260A, 1)));
papxEntry(wd, page, 108, concat(prl2(0x460B, 1), prl(0x260A, 1)));
papxEntry(wd, page, 115, concat(prl2(0x460B, 2), prl(0x260A, 0)));
// табличный поток: PlcfSed, PlcfBtePapx, Clx, SttbfFfn, PlfLst+LVL, PlfLfo
byte[] fonts = sttbfFfn("Symbol");
byte[] lvls = listLevels();
byte[] plfLst = concat(u16(2), lstf(100, false), lstf(200, true));
byte[] plfLfo = concat(u32(2), lfo(100), lfo(200), u32(0xFFFFFFFF), u32(0xFFFFFFFF));
int fontsAt = 54;
int lstAt = fontsAt + fonts.length;
int lvlAt = lstAt + plfLst.length;
int lfoAt = lvlAt + lvls.length;
byte[] tab = new byte[lfoAt + plfLfo.length];
put32(tab, 0, 0);
put32(tab, 4, text.length());
put32(tab, 20, LISTS_TEXT_FC);
put32(tab, 24, LISTS_TEXT_FC + 2 * text.length());
put32(tab, 28, 3);
tab[32] = 0x02; // Clx Pcdt, один несжатый кусок
put32(tab, 33, 16);
put32(tab, 37, 0);
put32(tab, 41, text.length());
put32(tab, 47, LISTS_TEXT_FC);
System.arraycopy(fonts, 0, tab, fontsAt, fonts.length);
System.arraycopy(plfLst, 0, tab, lstAt, plfLst.length);
System.arraycopy(lvls, 0, tab, lvlAt, lvls.length);
System.arraycopy(plfLfo, 0, tab, lfoAt, plfLfo.length);
pair(wd, 15, fontsAt, fonts.length); // SttbfFfn
pair(wd, 73, lstAt, plfLst.length); // PlfLst
pair(wd, 74, lfoAt, plfLfo.length); // PlfLfo
try (POIFSFileSystem fs = new POIFSFileSystem();
ByteArrayOutputStream out = new ByteArrayOutputStream()) {
fs.getRoot().createDocument("WordDocument", new ByteArrayInputStream(wd));
fs.getRoot().createDocument("1Table", new ByteArrayInputStream(tab));
fs.getRoot().createDocument("Data", new ByteArrayInputStream(new byte[64]));
fs.writeFilesystem(out);
return out.toByteArray();
}
}
/** GrpPrlAndIstd в форме cb≠0 (grpprl нечётный: istd=0 впереди). */
private static void papxEntry(byte[] wd, int page, int bx, byte[] grpprl) {
int at = page + bx * 2;
wd[at] = (byte) ((grpprl.length + 3) / 2);
put16(wd, at + 1, 0);
System.arraycopy(grpprl, 0, wd, at + 3, grpprl.length);
}
/** SttbfFfn (§2.9.147): одно семейство на ftc0=0. */
private static byte[] sttbfFfn(String family) {
byte[] fam = (family + "\0").getBytes(StandardCharsets.UTF_16LE);
byte[] t = new byte[4 + 1 + 39 + fam.length];
put16(t, 0, 1);
t[4] = (byte) (39 + fam.length);
System.arraycopy(fam, 0, t, 5 + 39, fam.length);
return t;
}
/** 9 LVL lsid=100 (decimal «%1.», lowerLetter «%2)») + bullet LVL lsid=200. */
private static byte[] listLevels() {
byte[][] ls = new byte[10][];
ls[0] = listLvl(0x00, 0, new byte[0], new int[] {0, '.'});
ls[1] = listLvl(0x04, 0, new byte[0], new int[] {1, ')'});
for (int i = 2; i < 9; i++) {
ls[i] = listLvl(0x00, 0, new byte[0], new int[] {i, '.'});
}
ls[9] = listLvl(0x17, 1, prl2(0x4A4F, 0), new int[] {0xF0B7});
return concat(ls);
}
private static byte[] listLvl(int nfc, int follow, byte[] chpx, int[] xst) {
byte[] b = new byte[28];
put32(b, 0, 1); // iStartAt
b[4] = (byte) nfc;
b[15] = (byte) follow;
b[24] = (byte) chpx.length;
byte[] x = new byte[2 + 2 * xst.length];
put16(x, 0, xst.length);
for (int i = 0; i < xst.length; i++) {
put16(x, 2 + 2 * i, xst[i]);
}
return concat(b, chpx, x);
}
private static byte[] lstf(int lsid, boolean simple) {
byte[] b = new byte[28];
put32(b, 0, lsid);
b[26] = (byte) (simple ? 1 : 0);
return b;
}
private static byte[] lfo(int lsid) {
byte[] b = new byte[16];
put32(b, 0, lsid);
return b;
}
private static byte[] prl(int sprm, int operand) {
return new byte[] {(byte) sprm, (byte) (sprm >>> 8), (byte) operand};
}
private static byte[] prl2(int sprm, int v) {
return new byte[] {(byte) sprm, (byte) (sprm >>> 8), (byte) v, (byte) (v >>> 8)};
}
private static byte[] u16(int v) {
byte[] b = new byte[2];
put16(b, 0, v);
return b;
}
private static byte[] u32(long v) {
byte[] b = new byte[4];
put32(b, 0, (int) v);
return b;
}
private static byte[] concat(byte[]... parts) {
int len = 0;
for (byte[] p : parts) {
len += p.length;
}
byte[] out = new byte[len];
int at = 0;
for (byte[] p : parts) {
System.arraycopy(p, 0, out, at, p.length);
at += p.length;
}
return out;
}
private static void pair(byte[] wd, int index, int fc, int lcb) {
put32(wd, 154 + index * 8, fc);
put32(wd, 154 + index * 8 + 4, lcb);
}
private static void put16(byte[] b, int off, int v) {
b[off] = (byte) v;
b[off + 1] = (byte) (v >>> 8);
}
private static void put32(byte[] b, int off, int v) {
put16(b, off, v & 0xFFFF);
put16(b, off + 2, (v >>> 16) & 0xFFFF);
}
}
@@ -78,18 +78,45 @@ class TableIndentNormalizerTest {
assertNull(TableIndentNormalizer.rewrite(xml));
}
/** jc без tblInd — аудит PASS (docx4j центрирует), не трогаем. */
/**
* jc без tblInd — сворачивается в абсолютный tblInd (X=0): docx4j пишет
* центрированию start-indent без вычета cellMar, padding-компенсация
* LayoutPostRenderer прибавила бы padding поверх (+5.4pt к Word).
*/
@Test
void jcWithoutIndent_returnsNull() {
void jcWithoutIndent_folded() {
String xml = doc(table("<w:jc w:val=\"center\"/>", GRID_6000));
assertNull(TableIndentNormalizer.rewrite(xml));
String fixed = TableIndentNormalizer.rewrite(xml);
assertTrue(fixed.contains("<w:tblInd w:w=\"1961\" w:type=\"dxa\"/>"), fixed);
assertFalse(fixed.contains("<w:jc"), fixed);
}
/** tblInd=0 с jc — сдвига нет, не трогаем. */
/** right без tblInd: (9922−6000) = 3922. */
@Test
void zeroIndent_returnsNull() {
void rightWithoutIndent_folded() {
String xml = doc(table("<w:jc w:val=\"right\"/>", GRID_6000));
String fixed = TableIndentNormalizer.rewrite(xml);
assertTrue(fixed.contains("<w:tblInd w:w=\"3922\" w:type=\"dxa\"/>"), fixed);
}
/** tblInd=0 с jc — тот же fold (X=0), прежнему поведению не канон. */
@Test
void zeroIndent_folded() {
String xml = doc(table("<w:jc w:val=\"center\"/>"
+ "<w:tblInd w:w=\"0\" w:type=\"dxa\"/>", GRID_6000));
String fixed = TableIndentNormalizer.rewrite(xml);
assertTrue(fixed.contains("<w:tblInd w:w=\"1961\" w:type=\"dxa\"/>"), fixed);
assertFalse(fixed.contains("<w:jc"), fixed);
}
/**
* tblCellSpacing без tblInd — tblInd по CT_TblPrBase идёт после
* tblCellSpacing, вставить некуда: консервативный пропуск.
*/
@Test
void cellSpacingWithoutIndent_returnsNull() {
String xml = doc(table("<w:jc w:val=\"center\"/>"
+ "<w:tblCellSpacing w:w=\"20\" w:type=\"dxa\"/>", GRID_6000));
assertNull(TableIndentNormalizer.rewrite(xml));
}
@@ -171,6 +198,82 @@ class TableIndentNormalizerTest {
assertNull(TableIndentNormalizer.rewrite(xml));
}
private static String hdr(String body) {
return "<w:hdr xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">"
+ body + "</w:hdr>";
}
/** header-часть со своей sectPr не содержит — полоса приходит извне. */
@Test
void rewritePart_header_foldsWithGivenBand() {
String xml = hdr(table("<w:jc w:val=\"center\"/>"
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000));
String fixed = TableIndentNormalizer.rewritePart("word/header1.xml", xml, 9922);
assertTrue(fixed.contains("<w:tblInd w:w=\"2681\" w:type=\"dxa\"/>"), fixed);
assertFalse(fixed.contains("<w:jc"), "jc удалён: " + fixed);
}
/** footer-часть — тот же путь. */
@Test
void rewritePart_footer_foldsWithGivenBand() {
String xml = hdr(table("<w:jc w:val=\"right\"/>"
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000))
.replace("w:hdr", "w:ftr");
String fixed = TableIndentNormalizer.rewritePart("word/footer2.xml", xml, 9922);
assertTrue(fixed.contains("<w:tblInd w:w=\"4642\" w:type=\"dxa\"/>"), fixed);
}
/** Многосекционный документ (band = −1) — полоса неоднозначна, пропускаем. */
@Test
void rewritePart_negativeBand_returnsNull() {
String xml = hdr(table("<w:jc w:val=\"center\"/>"
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000));
assertNull(TableIndentNormalizer.rewritePart("word/header1.xml", xml, -1));
}
/** Прочие word/*.xml (footnotes и пр.) — не трогаем. */
@Test
void rewritePart_otherPart_returnsNull() {
String xml = hdr(table("<w:jc w:val=\"center\"/>"
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000));
assertNull(TableIndentNormalizer.rewritePart("word/footnotes.xml", xml, 9922));
}
/** Header без таблиц — null (контракт «нечего менять»). */
@Test
void rewritePart_headerWithoutTables_returnsNull() {
assertNull(TableIndentNormalizer.rewritePart("word/header1.xml",
hdr("<w:p><w:r><w:t>hi</w:t></w:r></w:p>"), 9922));
}
/** document.xml делегирует rewrite: полоса — из собственной sectPr, не из band. */
@Test
void rewritePart_document_usesOwnSectPr() {
String xml = doc(table("<w:jc w:val=\"center\"/>"
+ "<w:tblInd w:w=\"720\" w:type=\"dxa\"/>", GRID_6000));
String fixed = TableIndentNormalizer.rewritePart("word/document.xml", xml, 12345);
assertTrue(fixed.contains("<w:tblInd w:w=\"2681\" w:type=\"dxa\"/>"),
"собственная полоса 9922, не внешний band: " + fixed);
}
/** strict-pgMar (w:start/w:end) — band считается, а не берётся из дефолтов. */
@Test
void bandOf_strictStartEndFields() {
String xml = "<w:document xmlns:w=\"http://purl.oclc.org/ooxml/wordprocessingml/main\">"
+ "<w:body><w:sectPr><w:pgSz w:w=\"11906\" w:h=\"16838\"/>"
+ "<w:pgMar w:top=\"1134\" w:end=\"850\" w:bottom=\"1134\" w:start=\"1134\"/>"
+ "</w:sectPr></w:body></w:document>";
assertEquals(9922, TableIndentNormalizer.bandOf(xml));
}
/** bandOf: несколько body-level sectPr — полоса неоднозначна (−1). */
@Test
void bandOf_ambiguous_returnsMinusOne() {
String xml = doc("<w:p/>").replace("</w:sectPr></w:body>",
"</w:sectPr><w:sectPr><w:pgSz w:w=\"12240\"/></w:sectPr></w:body>");
assertEquals(-1, TableIndentNormalizer.bandOf(xml));
}
private static byte[] zip(Map<String, String> parts) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(out)) {
@@ -87,6 +87,29 @@ class DocToDocxTest {
// конец строки таблицы (пустой абзац с 0x07+sprmPFTtp) в вывод не попадает
assertTrue(xml.indexOf("Ячейка 2") < xml.indexOf("Ячейка 3"), "между строками мусор");
assertTrue(!xml.contains("<w:p/>"), "пустые абзацы-концы строк не выброшены");
// таблица переносится структурой, а не плоскими абзацами (TAP → w:tbl)
assertTrue(xml.contains("<w:tbl>"), "w:tbl потерян");
assertEquals(2, xml.split("<w:tr>", -1).length - 1, "строки таблицы");
assertEquals(4, xml.split("<w:tc>", -1).length - 1, "ячейки таблицы");
int tblEnd = xml.indexOf("</w:tbl>");
assertTrue(tblEnd > xml.indexOf("Ячейка 4"), "ячейки утёкли из w:tbl");
assertTrue(xml.contains("<w:gridCol"), "сетка таблицы потеряна");
}
@Test
void tableFixture_becomesTblWithImage() throws IOException {
byte[] docx = DocToDocx.convert(sample("ru-table-image.doc"));
String xml = documentXml(sample("ru-table-image.doc"));
assertTrue(xml.contains("<w:tbl>"), "таблица не перенесена структурой");
assertTrue(xml.contains("<w:gridCol"), "сетка потеряна");
boolean hasImage = false;
try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(docx))) {
ZipEntry e;
while ((e = zip.getNextEntry()) != null) {
hasImage |= e.getName().startsWith("word/media/");
}
}
assertTrue(hasImage, "картинка в фикстуре потеряна");
}
@Test
@@ -59,6 +59,57 @@ class GrpprlTest {
assertEquals(0, count[0]);
}
@Test
void scan_tDefTable_twoByteLength() {
// sprmTDefTable 0xD608 (§2.9.321): cb — 2 байта, «остаток + 1»;
// cb=304 > 255 — формула «1 + первый байт» сбилась бы на 49
byte[] buf = new byte[2 + 305 + 3];
buf[0] = 0x08;
buf[1] = (byte) 0xD6;
buf[2] = 0x30;
buf[3] = 0x01; // cb = 304
buf[2 + 305] = 0x35;
buf[3 + 305] = 0x08;
buf[4 + 305] = 0x01;
List<Integer> sizes = new ArrayList<>();
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> sizes.add(len));
assertEquals(List.of(305, 1), sizes, "второй Prl найден — разбор не сместился");
}
@Test
void scan_tDefTable_truncated_stops() {
byte[] buf = {0x08, (byte) 0xD6, 0x30, 0x01, 0x00}; // cb=304, данных нет
int[] count = {0};
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> count[0]++);
assertEquals(0, count[0]);
}
@Test
void scan_pChgTabsSentinel_stops() {
// PChgTabsPapxOperand (§2.9.183, 0xC60D): cb=0xFF длины не выражается —
// обрыв, «1+cb» сдвинул бы разбор на 1 байт
byte[] buf = {0x0D, (byte) 0xC6, (byte) 0xFF, 0x35, 0x08, 0x01};
int[] count = {0};
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> count[0]++);
assertEquals(0, count[0], "0xFF-длина не должна сдвигать разбор на 1 байт");
}
@Test
void scan_pChgTabsSentinel_lengthByFormula() {
// sprmPChgTabs 0xC615 (§2.9.182): cb=0xFF — длина 3 + 4·cTabsDel +
// 3·cTabsAdd; здесь n=1, m=1 → 10, следующий Prl (0x0835) не съеден
byte[] buf = {0x15, (byte) 0xC6, (byte) 0xFF, 0x01,
0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x35, 0x08, 0x01};
List<Integer> seen = new ArrayList<>();
List<Integer> sizes = new ArrayList<>();
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> {
seen.add(sprm);
sizes.add(len);
});
assertEquals(List.of(0xC615, 0x0835), seen, "разбор не сместился и не оборвался");
assertEquals(List.of(10, 1), sizes);
}
@Test
void operandInt_widths() {
byte[] buf = {0x34, 0x12, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF};
@@ -71,4 +122,51 @@ class GrpprlTest {
assertTrue(Grpprl.toggleOn(new byte[] {1}, 0));
assertFalse(Grpprl.toggleOn(new byte[] {2}, 0));
}
@Test
void indents_80FamilyNestAndDefaults() {
Grpprl.Indents empty = new Grpprl.Indents();
assertEquals(0, empty.left());
assertEquals(-1, empty.right());
assertEquals(Integer.MIN_VALUE, empty.left1());
// только 80-е семейство: nest80 к dxaLeft80, left180 со знаком, right80
byte[] only80 = {
(byte) 0x0F, (byte) 0x84, (byte) 0x80, 0x02, // dxaLeft80 = 640
(byte) 0x10, 0x46, 0x2C, 0x00, // nest80 = 44
0x11, (byte) 0x84, (byte) 0x98, (byte) 0xFE, // dxaLeft180 = −360
(byte) 0x0E, (byte) 0x84, 0x1E, 0x00, // dxaRight80 = 30
};
Grpprl.Indents ind = new Grpprl.Indents();
Grpprl.scan(only80, 0, only80.length, ind::prl);
assertEquals(684, ind.left(), "nest80 прибавляется к dxaLeft80");
assertEquals(-360, ind.left1(), "dxaLeft180 — XAS со знаком");
assertEquals(30, ind.right());
}
@Test
void indents_modernFamilySupersedes80() {
// хоть один современный sprm левого отступа → 80-е семейство целиком в стороне
byte[] mixed = {
(byte) 0x0F, (byte) 0x84, (byte) 0x80, 0x02, // dxaLeft80 = 640
(byte) 0x10, 0x46, 0x2C, 0x00, // nest80 = 44
(byte) 0x5E, (byte) 0x84, 0x10, 0x01, // dxaLeft = 272
};
Grpprl.Indents m = new Grpprl.Indents();
Grpprl.scan(mixed, 0, mixed.length, m::prl);
assertEquals(272, m.left(), "современное семейство вытесняет 80-е");
// современный nest к своему left; right и left1 — слияние last-wins
byte[] modern = {
(byte) 0x5E, (byte) 0x84, 0x10, 0x01, // dxaLeft = 272
0x5F, 0x46, 0x0A, 0x00, // nest = 10
(byte) 0x0E, (byte) 0x84, 0x1E, 0x00, // dxaRight80 = 30
(byte) 0x5D, (byte) 0x84, 0x2C, 0x01, // dxaRight = 300 — last-wins
0x11, (byte) 0x84, (byte) 0x98, (byte) 0xFE, // dxaLeft180 = −360
0x60, (byte) 0x84, 0x78, 0x00, // dxaLeft1 = 120 — last-wins
};
Grpprl.Indents md = new Grpprl.Indents();
Grpprl.scan(modern, 0, modern.length, md::prl);
assertEquals(282, md.left(), "nest прибавляется к dxaLeft");
assertEquals(300, md.right(), "right — слияние last-wins");
assertEquals(120, md.left1(), "left1 — слияние last-wins");
}
}
@@ -66,6 +66,21 @@ class HeadersTest {
assertEquals(0, h.oddHeader(1).cpEnd());
}
/**
* §2.4.4: [x,x) — история НЕ определена (Word наследует полосы
* предыдущей секции); [x,x+1) — определена, но только guard-¶
* (явно пустой колонтитул, обрывающий наследование).
*/
@Test
void emptyVsGuardOnly() {
assertTrue(new Headers.Story(5, 5).empty());
assertFalse(new Headers.Story(5, 5).hasContent());
assertFalse(new Headers.Story(5, 6).empty());
assertFalse(new Headers.Story(5, 6).hasContent());
assertFalse(new Headers.Story(5, 7).empty());
assertTrue(new Headers.Story(5, 7).hasContent());
}
private static void put32(byte[] b, int off, int v) {
b[off] = (byte) v;
b[off + 1] = (byte) (v >>> 8);
@@ -0,0 +1,427 @@
package ru.pjandro.wordpdf.internal.doc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
/**
* Списки [MS-DOC] на крафтовых байтовых потоках (образец {@link TablesTest}):
* PlfLst/LSTF/LVL → abstractNum (счёт LVL по fSimpleList, плейсхолдеры xst,
* MSONFC → ST_NumberFormat, ixchFollow → w:suff, grpprl уровня → w:ind/
* w:rFonts), PlfLfo/LFOLVL → w:num с w:startOverride/w:lvl; деградации
* (нулевые lcb, обрыв массива LVL, lsid без LSTF).
*/
class ListsTest {
// --- крафт -----------------------------------------------------------
/** LSTF (28 Б, §2.9.147): lsid + flags bit0 fSimpleList. */
private static byte[] lstf(int lsid, boolean simple) {
byte[] b = new byte[28];
put32(b, 0, lsid);
b[26] = (byte) (simple ? 1 : 0);
return b;
}
/** LVL (§2.9.149) = LVLF(28) + grpprlPapx + grpprlChpx + Xst. */
private static byte[] lvl(int startAt, int nfc, int jc, int follow, byte[] papx,
byte[] chpx, int[] xst) {
byte[] b = new byte[28];
put32(b, 0, startAt);
b[4] = (byte) nfc;
b[5] = (byte) jc;
b[15] = (byte) follow;
b[24] = (byte) chpx.length;
b[25] = (byte) papx.length;
byte[] x = new byte[2 + 2 * xst.length];
put16(x, 0, xst.length);
for (int i = 0; i < xst.length; i++) {
put16(x, 2 + 2 * i, xst[i]);
}
return concat(b, papx, chpx, x);
}
/** Плоский уровень без grpprl: decimal «%{ilvl+1}.» (плейсхолдер 0x0N). */
private static byte[] plainLvl(int level) {
return lvl(1, 0x00, 0, 0, new byte[0], new byte[0], new int[] {level, '.'});
}
/** LFOLVL (§2.9.133): iStartAt + битполе (iLvl|fStartAt<<4|fFormatting<<5) + LVL. */
private static byte[] lfoLvl(int ilvl, boolean startAt, int start, boolean formatting,
byte[] lvlBytes) {
int bits = ilvl | (startAt ? 1 << 4 : 0) | (formatting ? 1 << 5 : 0);
return concat(u32(start), u32(bits), formatting ? lvlBytes : new byte[0]);
}
/** PlfLfo: lfoMac + rgLfo[16] + rgLfoData (cp + rgLfoLvl). */
private static byte[] plfLfo(int lsid, int clfolvl, byte[] lfoData) {
byte[] lfo = new byte[16];
put32(lfo, 0, lsid);
lfo[12] = (byte) clfolvl;
return concat(u32(1), lfo, u32(0xFFFFFFFFL), lfoData);
}
/** SttbfFfn (§2.9.147 FontTable) с одним семейством на индексе ftc. */
private static FontTable fonts(String... names) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] header = new byte[4];
put16(header, 0, names.length);
out.writeBytes(header);
for (String name : names) {
byte[] fam = (name + "\0").getBytes(StandardCharsets.UTF_16LE);
int cch = 39 + fam.length;
out.write(cch);
out.writeBytes(new byte[39]);
out.writeBytes(fam);
}
byte[] table = out.toByteArray();
return FontTable.read(table, 0, table.length);
}
private static Lists lists(byte[] plfLst, byte[] lvls, byte[] plfLfo, FontTable fonts) {
byte[] table = concat(plfLst, lvls, plfLfo);
long fcPlfLst = 0;
long lcbPlfLst = plfLst.length;
long fcPlfLfo = plfLst.length + lvls.length;
long lcbPlfLfo = plfLfo.length;
return Lists.read(table, fcPlfLst, lcbPlfLst, fcPlfLfo, lcbPlfLfo, fonts);
}
/** PlfLst: заголовок cLst SHORT(2Б, §2.9.201) + LSTF-записи с fc+2. */
private static byte[] plfLst(byte[]... lstfs) {
byte[] head = u16(lstfs.length);
byte[][] all = new byte[lstfs.length + 1][];
all[0] = head;
System.arraycopy(lstfs, 0, all, 1, lstfs.length);
return concat(all);
}
// --- abstractNum -------------------------------------------------------
@Test
void multiLevelList_levelsAndPlaceholders() {
// LSTF lsid=100, 9 уровней: lvl0 decimal «%1.», lvl1 lowerLetter
// «%1-%2)» (плейсхолдеры 0x00/0x01) со startAt=3, остальные плоские
byte[] l0 = lvl(1, 0x00, 0, 0, new byte[0], new byte[0], new int[] {0, '.'});
byte[] l1 = lvl(3, 0x04, 0, 0, new byte[0], new byte[0],
new int[] {0, '-', 1, ')'});
byte[] rest = concat(plainLvl(2), plainLvl(3), plainLvl(4), plainLvl(5),
plainLvl(6), plainLvl(7), plainLvl(8));
Lists lists = lists(plfLst(lstf(100, false)), concat(l0, l1, rest),
new byte[0], fonts());
assertTrue(lists.hasNumbering());
String xml = lists.numberingXml();
assertTrue(xml.contains("<w:abstractNum w:abstractNumId=\"1\">"), xml);
assertTrue(xml.contains("<w:lvl w:ilvl=\"0\"><w:start w:val=\"1\"/>"
+ "<w:numFmt w:val=\"decimal\"/>"), xml);
assertTrue(xml.contains("<w:lvlText w:val=\"%1.\"/>"), xml);
assertTrue(xml.contains("<w:lvl w:ilvl=\"1\"><w:start w:val=\"3\"/>"
+ "<w:numFmt w:val=\"lowerLetter\"/>"), xml);
assertTrue(xml.contains("<w:lvlText w:val=\"%1-%2)\"/>"),
"плейсхолдеры 0x00/0x01 → %1/%2: " + xml);
assertTrue(xml.contains("<w:lvl w:ilvl=\"8\">"), xml);
assertFalse(xml.contains("<w:num "), "PlfLfo нет — w:num быть не должно: " + xml);
}
@Test
void simpleList_getsOneLevel() {
// fSimpleList=1 → ровно 1 LVL; следующий LSTF получает свои 9
byte[] simple = plfLst(lstf(100, true), lstf(200, false));
byte[] lvls = concat(plainLvl(0), plainLvl(0), plainLvl(1), plainLvl(2),
plainLvl(3), plainLvl(4), plainLvl(5), plainLvl(6), plainLvl(7),
plainLvl(8));
Lists lists = lists(simple, lvls, new byte[0], fonts());
String xml = lists.numberingXml();
String abstract1 = xml.substring(xml.indexOf("<w:abstractNum w:abstractNumId=\"1\">"),
xml.indexOf("</w:abstractNum>"));
assertEquals(1, abstract1.split("<w:lvl ", -1).length - 1,
"fSimpleList → один LVL: " + abstract1);
assertTrue(xml.contains("<w:abstractNum w:abstractNumId=\"2\">"), xml);
assertEquals(9, xml.substring(xml.indexOf("<w:abstractNum w:abstractNumId=\"2\">"))
.split("<w:lvl ", -1).length - 1, "многоуровневый → 9 LVL");
}
@Test
void bulletLevel_fontSuffAndText() {
// nfc=0x17 bullet, chpx ftc0=Symbol, xst = PUA 0xF0B7, ixchFollow=1 → space
byte[] chpx = {0x4F, 0x4A, 0, 0}; // sprmCRgFtc0 = 0
byte[] l0 = lvl(1, 0x17, 0, 1, new byte[0], chpx, new int[] {0xF0B7});
Lists lists = lists(plfLst(lstf(100, true)), l0, new byte[0], fonts("Symbol"));
String xml = lists.numberingXml();
assertTrue(xml.contains("<w:numFmt w:val=\"bullet\"/>"), xml);
assertTrue(xml.contains("<w:suff w:val=\"space\"/>"), xml);
assertTrue(xml.contains("<w:rFonts w:ascii=\"Symbol\" w:hAnsi=\"Symbol\"/>"), xml);
assertTrue(xml.contains("<w:lvlText w:val=\"\uF0B7\"/>"),
"PUA-символ дословно (чинит SymbolFontNormalizer): " + xml);
}
@Test
void levelPapx_becomesInd() {
// grpprlPapx: sprmPDxaLeft=720 + sprmPDxaLeft1=−360 (XAS со знаком)
byte[] papx = concat(prl2(0x845E, 720),
new byte[] {0x60, (byte) 0x84, (byte) 0x98, (byte) 0xFE});
byte[] l0 = lvl(1, 0x00, 2, 2, papx, new byte[0], new int[] {0, '.'});
Lists lists = lists(plfLst(lstf(100, true)), l0, new byte[0], fonts());
String xml = lists.numberingXml();
assertTrue(xml.contains("<w:pPr><w:ind w:left=\"720\" w:hanging=\"360\"/></w:pPr>"),
xml);
assertTrue(xml.contains("<w:suff w:val=\"nothing\"/>"), xml);
assertTrue(xml.contains("<w:lvlJc w:val=\"right\"/>"), xml);
}
@Test
void levelPapx80Variants_becomeInd() {
// grpprlPapx 80-вариантами: sprmPDxaLeft80=720 + sprmPDxaLeft180=−360
// → тот же w:ind, что у современного семейства (общий Grpprl.Indents)
byte[] papx = concat(prl2(0x840F, 720),
new byte[] {0x11, (byte) 0x84, (byte) 0x98, (byte) 0xFE});
byte[] l0 = lvl(1, 0x00, 0, 0, papx, new byte[0], new int[] {0, '.'});
Lists lists = lists(plfLst(lstf(100, true)), l0, new byte[0], fonts());
assertTrue(lists.numberingXml().contains(
"<w:pPr><w:ind w:left=\"720\" w:hanging=\"360\"/></w:pPr>"),
lists.numberingXml());
}
@Test
void literalPercent_doubled() {
byte[] l0 = lvl(1, 0x00, 0, 0, new byte[0], new byte[0],
new int[] {'%', '5', '0', '%', 0, '.'});
Lists lists = lists(plfLst(lstf(100, true)), l0, new byte[0], fonts());
// «%50%» + плейсхолдер 1 + «.» → «%%»+«50»+«%%»+«%1»+«.»
assertTrue(lists.numberingXml().contains("<w:lvlText w:val=\"%%50%%%1.\"/>"),
"литеральный % удваивается: " + lists.numberingXml());
}
@Test
void exoticNfc_fallsBackToDecimal() {
byte[] l0 = lvl(1, 0x0A, 0, 0, new byte[0], new byte[0], new int[] {'%', '1'});
Lists lists = lists(plfLst(lstf(100, true)), l0, new byte[0], fonts());
assertTrue(lists.numberingXml().contains("<w:numFmt w:val=\"decimal\"/>"),
"CJK-MSONFC → decimal: " + lists.numberingXml());
}
@Test
void knownNfc_mappedToStNumberFormat() {
int[] nfc = {0x01, 0x02, 0x03, 0x05, 0x06, 0x07, 0x16, 0x39, 0x3A, 0x3B, 0xFF};
String[] st = {"upperRoman", "lowerRoman", "upperLetter", "ordinal",
"cardinalText", "ordinalText",
"decimalZero", "numberInDash", "russianLower", "russianUpper", "none"};
for (int i = 0; i < nfc.length; i++) {
byte[] l0 = lvl(1, nfc[i], 0, 0, new byte[0], new byte[0], new int[] {'%'});
Lists lists = lists(plfLst(lstf(100, true)), l0, new byte[0], fonts());
assertTrue(lists.numberingXml().contains("<w:numFmt w:val=\"" + st[i] + "\"/>"),
"nfc 0x" + Integer.toHexString(nfc[i]) + " → " + st[i]);
}
}
@Test
void levelRich_jcFirstLineBoldSzAndEscapes() {
// papx: left=100 + left1=220 → firstLine; chpx: bold + hps=28 + ftc0=0;
// jc=1 → center; имя семейства с & < " → экранирование в w:rFonts
byte[] papx = concat(prl2(0x845E, 100), prl2(0x8460, 220));
byte[] chpx = concat(new byte[] {0x35, 0x08, 1},
new byte[] {0x43, 0x4A, 28, 0}, new byte[] {0x4F, 0x4A, 0, 0});
byte[] l0 = lvl(1, 0x00, 1, 1, papx, chpx, new int[] {'1', '.', ' '});
Lists lists = lists(plfLst(lstf(100, true)), l0, new byte[0],
fonts("T&imes <New> \"Q\""));
String xml = lists.numberingXml();
assertTrue(xml.contains("<w:lvlJc w:val=\"center\"/>"), xml);
assertTrue(xml.contains("<w:ind w:left=\"100\" w:firstLine=\"220\"/>"), xml);
assertTrue(xml.contains("<w:b/>"), xml);
assertTrue(xml.contains("<w:sz w:val=\"28\"/>"), xml);
assertTrue(xml.contains("w:ascii=\"T&amp;imes &lt;New> &quot;Q&quot;\""),
"«>» в атрибуте легален и не экранируется: " + xml);
}
// --- w:num / LFOLVL ------------------------------------------------------
@Test
void lfo_numWithStartOverrideAndFormatting() {
byte[] l0 = plainLvl(0);
byte[] overrideLvl = lvl(1, 0x01, 0, 0, new byte[0], new byte[0],
new int[] {'%', '2', '.'});
byte[] data = concat(lfoLvl(0, true, 7, false, new byte[0]),
lfoLvl(1, false, 0, true, overrideLvl));
Lists lists = lists(plfLst(lstf(100, false)),
concat(l0, plainLvl(1), plainLvl(2), plainLvl(3), plainLvl(4),
plainLvl(5), plainLvl(6), plainLvl(7), plainLvl(8)),
plfLfo(100, 2, data), fonts());
assertTrue(lists.hasNum(1));
assertFalse(lists.hasNum(2));
String xml = lists.numberingXml();
assertTrue(xml.contains("<w:num w:numId=\"1\"><w:abstractNumId w:val=\"1\"/>"), xml);
assertTrue(xml.contains("<w:lvlOverride w:ilvl=\"0\">"
+ "<w:startOverride w:val=\"7\"/></w:lvlOverride>"), xml);
assertTrue(xml.contains("<w:lvlOverride w:ilvl=\"1\"><w:lvl w:ilvl=\"1\">"
+ "<w:start w:val=\"1\"/><w:numFmt w:val=\"upperRoman\"/>"), xml);
}
@Test
void lfoWithoutMatchingLstf_hasNoNum() {
Lists lists = lists(plfLst(lstf(100, true)), plainLvl(0),
plfLfo(999, 0, new byte[0]), fonts());
assertTrue(lists.hasNumbering());
assertFalse(lists.hasNum(1), "lsid без LSTF — num не эмитится");
assertFalse(lists.numberingXml().contains("<w:num "),
lists.numberingXml());
}
@Test
void zeroMacros_emptyTables() {
// lstfMac=0 / lfoMac=0 — пустые таблицы без падения
byte[] table = concat(u32(0), u32(0));
Lists lists = Lists.read(table, 0, 4, 4, 4, fonts());
assertFalse(lists.hasNumbering());
assertFalse(lists.hasNum(0));
assertFalse(lists.hasNum(1));
}
@Test
void truncatedSecondLstf_staysNull() {
// два многоуровневых LSTF, влезли 3 LVL: второй — null, LFO на него не цепляется
byte[] truncated = concat(plainLvl(0), plainLvl(1), plainLvl(2));
Lists lists = lists(plfLst(lstf(100, false), lstf(200, false)), truncated,
plfLfo(200, 0, new byte[0]), fonts());
assertTrue(lists.hasNumbering(), "первый LSTF валиден");
assertFalse(lists.hasNum(1), "lsid=200 указывает на null-LSTF");
String xml = lists.numberingXml();
assertTrue(xml.contains("w:abstractNumId=\"1\""), xml);
assertFalse(xml.contains("w:abstractNumId=\"2\""), xml);
assertFalse(xml.contains("<w:num "), xml);
}
@Test
void hostileLevelFields_degradeToInvalid() {
// cbPapx за пределами потока
assertFalse(lists(plfLst(lstf(100, false)), rawLvl(200), new byte[0], fonts())
.hasNumbering());
// заголовок xst обрезан: поток кончается сразу после grpprl
byte[] noXst = rawLvl(2, (byte) 0x62, (byte) 0x84);
assertFalse(lists(plfLst(lstf(100, false)), noXst, new byte[0], fonts())
.hasNumbering());
// враждебный cch
byte[] bigCch = concat(rawLvl(0), u16(0xFFFF));
assertFalse(lists(plfLst(lstf(100, false)), bigCch, new byte[0], fonts())
.hasNumbering());
}
@Test
void lfoDataTruncated_keepsLfoWithoutOverrides() {
// clfolvl=1, но LFOData обрывается на cp / первом LFOLVL
assertFalse(lists(plfLst(lstf(100, true)), plainLvl(0),
plfLfo(100, 1, new byte[0]), fonts()).numberingXml()
.contains("lvlOverride"));
assertTrue(lists(plfLst(lstf(100, true)), plainLvl(0),
plfLfo(100, 1, u32(0)), fonts()).hasNum(1));
assertFalse(lists(plfLst(lstf(100, true)), plainLvl(0),
plfLfo(100, 1, u32(0)), fonts()).numberingXml()
.contains("lvlOverride"));
}
@Test
void lfoLvlFormattingTruncated_stopsOverrides() {
// fFormatting, но LVL обрезан — переопределение отброшено, num жив
byte[] data = concat(u32(0), u32(1 << 5), rawLvl(100));
Lists lists = lists(plfLst(lstf(100, true)), plainLvl(0),
plfLfo(100, 1, data), fonts());
assertTrue(lists.hasNum(1));
assertFalse(lists.numberingXml().contains("lvlOverride"),
lists.numberingXml());
}
@Test
void lfoLvlFlags_ilvlCapAndEmptyOverride() {
// ilvl=9 — за пределами уровней (скип); без fStartAt/fFormatting — пустой lvlOverride
byte[] data = concat(u32(0), u32(9), u32(0), u32(1), u32(0));
Lists lists = lists(plfLst(lstf(100, true)), plainLvl(0),
plfLfo(100, 2, data), fonts());
String xml = lists.numberingXml();
assertFalse(xml.contains("w:ilvl=\"9\""), xml);
assertTrue(xml.contains("<w:lvlOverride w:ilvl=\"1\"></w:lvlOverride>"), xml);
}
// --- деградации ----------------------------------------------------------
@Test
void zeroLcb_emptyLists() {
byte[] table = new byte[64];
Lists lists = Lists.read(table, 0, 0, 0, 0, fonts());
assertFalse(lists.hasNumbering());
assertFalse(lists.hasNum(1));
}
@Test
void truncatedLevelArray_keepsParsedLevels() {
// 9 уровней влезает только 3 — abstractNum с ilvl 0..2, без падения
byte[] full = concat(plainLvl(0), plainLvl(1), plainLvl(2), plainLvl(3),
plainLvl(4), plainLvl(5), plainLvl(6), plainLvl(7), plainLvl(8));
byte[] truncated = new byte[plainLvl(0).length * 3];
System.arraycopy(full, 0, truncated, 0, truncated.length);
Lists lists = lists(plfLst(lstf(100, false)), truncated, new byte[0], fonts());
assertTrue(lists.hasNumbering());
String xml = lists.numberingXml();
assertTrue(xml.contains("<w:lvl w:ilvl=\"2\">"), xml);
assertFalse(xml.contains("<w:lvl w:ilvl=\"3\">"), xml);
}
@Test
void garbageTable_emptyLists() {
byte[] table = "не PlfLst вообще".getBytes(StandardCharsets.UTF_8);
Lists lists = Lists.read(table, 2, 100, 2, 100, fonts());
assertFalse(lists.hasNumbering());
assertFalse(lists.hasNum(1));
}
// --- хелперы ---------------------------------------------------------
/** LVLF с заданным cbPapx и байтами grpprl (для guard-тестов). */
private static byte[] rawLvl(int cbPapx, byte... grpprl) {
byte[] b = new byte[28];
b[25] = (byte) cbPapx;
return concat(b, grpprl);
}
private static byte[] u16(int v) {
byte[] b = new byte[2];
put16(b, 0, v);
return b;
}
private static byte[] prl2(int sprm, int v) {
return new byte[] {(byte) sprm, (byte) (sprm >>> 8), (byte) v, (byte) (v >>> 8)};
}
private static byte[] u32(long v) {
byte[] b = new byte[4];
put32(b, 0, (int) v);
return b;
}
private static byte[] concat(byte[]... parts) {
int len = 0;
for (byte[] p : parts) {
len += p.length;
}
byte[] out = new byte[len];
int at = 0;
for (byte[] p : parts) {
System.arraycopy(p, 0, out, at, p.length);
at += p.length;
}
return out;
}
private static void put16(byte[] b, int off, int v) {
b[off] = (byte) v;
b[off + 1] = (byte) (v >>> 8);
}
private static void put32(byte[] b, int off, int v) {
put16(b, off, v & 0xFFFF);
put16(b, off + 2, (v >>> 16) & 0xFFFF);
}
}
@@ -32,6 +32,11 @@ class PapxIndexTest {
*/
private static byte[] wordDocument(int bx, boolean shortForm, int cb,
byte[] grpprl) {
return wordDocument(bx, shortForm, cb, grpprl, 0);
}
private static byte[] wordDocument(int bx, boolean shortForm, int cb,
byte[] grpprl, int istd) {
byte[] wd = new byte[1536];
int page = 2 * 512;
put32(wd, page, 2048);
@@ -42,13 +47,13 @@ class PapxIndexTest {
if (shortForm) { // cb=0: следующий байт — cb'
wd[infkp] = 0;
wd[infkp + 1] = (byte) cb;
wd[infkp + 2] = 0; // istd
wd[infkp + 3] = 0;
wd[infkp + 2] = (byte) istd;
wd[infkp + 3] = (byte) (istd >>> 8);
System.arraycopy(grpprl, 0, wd, infkp + 4, grpprl.length);
} else {
wd[infkp] = (byte) cb;
wd[infkp + 1] = 0; // istd
wd[infkp + 2] = 0;
wd[infkp + 1] = (byte) istd;
wd[infkp + 2] = (byte) (istd >>> 8);
System.arraycopy(grpprl, 0, wd, infkp + 3, grpprl.length);
}
return wd;
@@ -126,6 +131,33 @@ class PapxIndexTest {
assertEquals(0, PapxIndex.read(table(2), 0, 12, wd).countPageBreakBefore());
}
@Test
void istd_extractedBothForms() {
PapxIndex longForm = PapxIndex.read(table(2), 0, 12,
wordDocument(11, false, 3, GRPRL_PB, 10));
assertEquals(10, longForm.istdFor(2048));
PapxIndex shortForm = PapxIndex.read(table(2), 0, 12,
wordDocument(11, true, 3, new byte[] {0x07, 0x24, 0x01, 0}, 11));
assertEquals(11, shortForm.istdFor(2048));
}
@Test
void istdOnly_emptyGrpprlKept() {
// cb=0, cb'=1 → GrpPrlAndIstd = istd(2), Prl'ов нет (§2.9.175):
// grpprl пустой, istd читается — стиль единственное свойство
PapxIndex idx = PapxIndex.read(table(2), 0, 12,
wordDocument(11, true, 1, new byte[0], 12));
assertArrayEquals(new byte[0], idx.grpprlFor(2048));
assertEquals(12, idx.istdFor(2048));
}
@Test
void istdFor_outsideRange_minusOne() {
PapxIndex idx = PapxIndex.read(table(2), 0, 12,
wordDocument(11, false, 3, GRPRL_PB, 10));
assertEquals(-1, idx.istdFor(2200), "вне диапазона — стиля нет");
}
private static void put32(byte[] b, int off, int v) {
b[off] = (byte) v;
b[off + 1] = (byte) (v >>> 8);
@@ -1,23 +1,38 @@
package ru.pjandro.wordpdf.internal.doc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
import ru.pjandro.wordpdf.ValidationException;
/**
* Юниты {@link Sections} ([MS-DOC] §2.6.3, PlcfSed/Sepx): геометрия
* последней секции, continuous-оценки предыдущих, пропуски битых Sepx.
* Юниты {@link Sections} ([MS-DOC] §2.6.3, PlcfSed/Sepx): по-секционная
* геометрия и continuous из {@code list()}, одиночные аксессоры — последней
* секции, guard'ы aCP, пропуски битых Sepx.
*/
class SectionsTest {
/** PlcfSed из n секций; fcSepx[i] — по wordDocument-адресам. */
/** PlcfSed из n секций; aCp = [0, 100, …, n·100], fcSepx[i] — адреса в wordDocument. */
private static byte[] plcfSed(int... fcSepxs) {
int n = fcSepxs.length;
int[] aCp = new int[n + 1];
for (int i = 0; i <= n; i++) {
aCp[i] = i * 100;
}
return plcfSed(aCp, fcSepxs);
}
/** PlcfSed с произвольным aCp (n+1 значений) и fcSepx[i] в wordDocument. */
private static byte[] plcfSed(int[] aCp, int... fcSepxs) {
int n = fcSepxs.length;
byte[] t = new byte[(n + 1) * 4 + n * 12]; // aFc(n+1) + SED(n×12)
for (int i = 0; i <= n; i++) {
put32(t, i * 4, i * 100);
put32(t, i * 4, aCp[i]);
}
int sedBase = (n + 1) * 4;
for (int i = 0; i < n; i++) {
@@ -40,31 +55,38 @@ class SectionsTest {
@Test
void emptySed_defaults() {
Sections s = Sections.read(new byte[0], 0, 0, new byte[0]);
Sections s = Sections.read(new byte[0], 0, 0, new byte[0], 500);
assertEquals(12240, s.pageWidth());
assertEquals(15840, s.pageHeight());
assertEquals(1440, s.marginLeft());
assertEquals(720, s.header());
assertEquals(0, s.continuousSectionEnds());
// одна неявная секция [0, ccpText) с дефолтами
List<Sections.Section> list = s.list();
assertEquals(1, list.size());
assertEquals(0, list.get(0).cpStart());
assertEquals(500, list.get(0).cpEnd());
assertFalse(list.get(0).continuous());
}
@Test
void badSed_rejected() {
byte[] t = plcfSed(0);
assertThrows(ValidationException.class, () -> Sections.read(t, 0, 21, new byte[0]));
assertThrows(ValidationException.class, () -> Sections.read(t, 0, t.length + 1, new byte[0]));
assertThrows(ValidationException.class, () -> Sections.read(t, 0, 21, new byte[0], 1000));
assertThrows(ValidationException.class,
() -> Sections.read(t, 0, t.length + 1, new byte[0], 1000));
}
@Test
void zeroAndBrokenSepx_skipped() {
byte[] wd = new byte[4096];
// fcSepx=0 — нет разрыва; fcSepx у конца wd (4095+2 > 4096) — пропуск
Sections s = Sections.read(plcfSed(0, 4095), 0, plcfSed(0, 4095).length, wd);
Sections s = Sections.read(plcfSed(0, 4095), 0, plcfSed(0, 4095).length, wd, 1000);
assertEquals(12240, s.pageWidth());
// cb=0
byte[] wd2 = new byte[4096];
wd2[64] = 0;
Sections s2 = Sections.read(plcfSed(64), 0, plcfSed(64).length, wd2);
Sections s2 = Sections.read(plcfSed(64), 0, plcfSed(64).length, wd2, 1000);
assertEquals(12240, s2.pageWidth());
}
@@ -81,7 +103,7 @@ class SectionsTest {
prl2(Grpprl.SPRM_S_DYA_HDR_BOTTOM, 992));
sepx(wd, 64, gpr);
byte[] t = plcfSed(64);
Sections s = Sections.read(t, 0, t.length, wd);
Sections s = Sections.read(t, 0, t.length, wd, 1000);
assertEquals(16838, s.pageWidth());
assertEquals(11906, s.pageHeight());
assertEquals(1080, s.marginLeft());
@@ -92,6 +114,47 @@ class SectionsTest {
assertEquals(992, s.footer());
}
/**
* Две секции со своими Sepx: {@code list()} отдаёт CP-диапазон
* [aCP[i], aCP[i+1]) и геометрию КАЖДОЙ секции; continuous — из sprmSBkc
* своей секции (§2.6.3 SBkcOperand — разрыв, ЗАКАНЧИВАЮЩИЙ секцию);
* одиночные аксессоры — последней.
*/
@Test
void multiSection_listPerSection() {
byte[] wd = new byte[4096];
sepx(wd, 64, concat(prl2(Grpprl.SPRM_S_XA_PAGE, 12240),
prl2(Grpprl.SPRM_S_YA_PAGE, 15840),
prl2(Grpprl.SPRM_S_DXA_LEFT, 1440),
new byte[] {0x09, 0x30, 0x00})); // sprmSBkc=bkcContinuous
sepx(wd, 128, concat(prl2(Grpprl.SPRM_S_XA_PAGE, 16838),
prl2(Grpprl.SPRM_S_YA_PAGE, 11906),
prl2(Grpprl.SPRM_S_DXA_LEFT, 720),
new byte[] {0x09, 0x30, 0x02})); // bkcNewPage
byte[] t = plcfSed(new int[] {0, 10, 25}, 64, 128);
Sections s = Sections.read(t, 0, t.length, wd, 25);
List<Sections.Section> list = s.list();
assertEquals(2, list.size());
Sections.Section s0 = list.get(0);
assertEquals(0, s0.cpStart());
assertEquals(10, s0.cpEnd());
assertEquals(12240, s0.pageWidth());
assertEquals(15840, s0.pageHeight());
assertEquals(1440, s0.marginLeft());
assertTrue(s0.continuous(), "sprmSBkc=0 у секции 0");
Sections.Section s1 = list.get(1);
assertEquals(10, s1.cpStart());
assertEquals(25, s1.cpEnd());
assertEquals(16838, s1.pageWidth());
assertEquals(11906, s1.pageHeight());
assertEquals(720, s1.marginLeft());
assertFalse(s1.continuous(), "bkcNewPage у секции 1");
// аксессоры — последней секции (подсчёт страниц не меняется)
assertEquals(16838, s.pageWidth());
assertEquals(720, s.marginLeft());
assertEquals(1, s.continuousSectionEnds());
}
@Test
void continuousEnds_countedForNonLastOnly() {
byte[] wd = new byte[4096];
@@ -101,12 +164,35 @@ class SectionsTest {
sepx(wd, 128, cont);
sepx(wd, 192, newPage);
byte[] t = plcfSed(64, 128, 192);
Sections s = Sections.read(t, 0, t.length, wd);
Sections s = Sections.read(t, 0, t.length, wd, 1000);
// секции 0 и 1 — не последние: обе continuous считаются;
// секция 2 — последняя: bkc в оценку не идёт
assertEquals(2, s.continuousSectionEnds());
}
/** §2.8.26: «MUST NOT contain duplicate CPs» — дубль и спад невозможны. */
@Test
void nonIncreasingAcp_rejected() {
byte[] dup = plcfSed(new int[] {0, 5, 5}, 0, 0);
assertThrows(ValidationException.class, () -> Sections.read(dup, 0, dup.length,
new byte[0], 1000));
byte[] down = plcfSed(new int[] {0, 7, 3}, 0, 0);
assertThrows(ValidationException.class, () -> Sections.read(down, 0, down.length,
new byte[0], 1000));
}
/**
* Финальный aCP реальные файлы Word пишут за ccpText (page-numbers.doc:
* aCp[1]=108 при ccpText=33) — не отбраковка; конец последней секции
* клампится к ccpText.
*/
@Test
void lastAcpBeyondText_clamped() {
byte[] t = plcfSed(new int[] {0, 101}, 0);
Sections s = Sections.read(t, 0, t.length, new byte[0], 100);
assertEquals(100, s.list().get(0).cpEnd());
}
private static byte[] concat(byte[]... parts) {
int len = 0;
for (byte[] p : parts) {
@@ -0,0 +1,257 @@
package ru.pjandro.wordpdf.internal.doc;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
/**
* Юниты {@link Styles} ([MS-DOC] §2.9.271/.272/.260/.308/.309, §2.4.6.5):
* крафтовый STSH — разбор LPStshi/LPStd/Std (stdf + xstzName + LPUpx),
* цепочка base-first, защита от циклов и битого STSH.
*/
class StylesTest {
/** jc=center (sprmPJc 0x2461, 1 байт). */
private static final byte[] JC_CENTER = {0x61, 0x24, 0x01};
/** left 720 (sprmPDxaLeft 0x845E, 2 байта). */
private static final byte[] LEFT_720 = {0x5E, (byte) 0x84, (byte) 0xD0, 0x02};
/** bold (sprmCBold 0x0835, toggle on). */
private static final byte[] BOLD = {0x35, 0x08, 0x01};
/**
* STSH: cstd стилей, rglpstd с istd 10..(9+n); пустые слоты 0..9.
* Каждый стиль — Std(stdf + xstzName + cupx × LPUpx).
*/
private static byte[] stsh(int cstd, byte[]... stylesFrom10) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
put16(out, 18); // cbStshi
put16(out, cstd); // cstd
put16(out, 0x0A); // cbSTDBaseInFile
out.write(new byte[14], 0, 14); // остальное STSHI
for (int i = 0; i < 10; i++) {
put16(out, 0); // пустые фиксированные стили
}
for (byte[] std : stylesFrom10) {
put16(out, std.length);
out.write(std, 0, std.length);
if (((2 + std.length) & 1) != 0) {
out.write(0); // LPStd на чётной границе (padding вне cbStd)
}
}
return out.toByteArray();
}
/** Std: stk=1, istdBase, cupx по числу непустых UPX; xstzName cch=2. */
private static byte[] std(int sti, int stk, int istdBase, byte[] papx, byte[] chpx) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
long base = sti | ((long) stk << 16) | ((long) istdBase << 20);
int cupx = (papx == null ? 0 : 1) + (chpx == null ? 0 : 1);
byte[] stdf = new byte[10];
stdf[0] = (byte) base;
stdf[1] = (byte) (base >>> 8);
stdf[2] = (byte) (base >>> 16);
stdf[3] = (byte) (base >>> 24);
stdf[4] = (byte) cupx;
out.write(stdf, 0, 10);
byte[] name = new byte[8]; // cch=2, "Ab", chTerm=0
put16(name, 0, 2);
name[2] = 'A';
name[4] = 'b';
out.write(name, 0, 8);
if (papx != null) {
byte[] data = new byte[2 + papx.length]; // UpxPapx: istd(2) + grpprl
System.arraycopy(papx, 0, data, 2, papx.length);
upx(out, data);
}
if (chpx != null) {
upx(out, chpx);
}
return out.toByteArray();
}
private static void upx(ByteArrayOutputStream out, byte[] data) {
put16(out, data.length);
out.write(data, 0, data.length);
if ((data.length & 1) != 0) {
out.write(0); // LPUpx на чётной границе
}
}
private static void put16(ByteArrayOutputStream out, int v) {
out.write(v & 0xFF);
out.write((v >>> 8) & 0xFF);
}
private static void put16(byte[] b, int off, int v) {
b[off] = (byte) v;
b[off + 1] = (byte) (v >>> 8);
}
@Test
void chain_baseFirstDerivedOverrides() {
// istd10: jc center + bold; istd11: base 10, + left 720
byte[] table = stsh(12,
std(65, 1, 0x0FFF, JC_CENTER, BOLD),
std(105, 1, 10, LEFT_720, null));
Styles s = Styles.read(table, 0, table.length);
assertEquals(12, s.count());
byte[] chain = s.papxChain(11);
assertArrayEquals(concat(JC_CENTER, LEFT_720), chain,
"base-first: предок раньше потомка");
assertArrayEquals(BOLD, s.chpxChain(11), "CHPX наследуется по той же цепочке");
assertArrayEquals(JC_CENTER, s.papxChain(10));
}
@Test
void unknownAndEmptyStil_emptyChain() {
byte[] table = stsh(12, std(65, 1, 0x0FFF, JC_CENTER, BOLD));
Styles s = Styles.read(table, 0, table.length);
assertArrayEquals(new byte[0], s.papxChain(0), "пустой слот — без свойств");
assertArrayEquals(new byte[0], s.papxChain(99), "istd за таблицей — без свойств");
assertArrayEquals(new byte[0], s.papxChain(-1));
}
@Test
void baseBeyondTable_chainStops() {
// istdBase=99 (несуществующий) — цепочка обрывается на собственном grpprl
byte[] table = stsh(12, std(65, 1, 99, JC_CENTER, null));
Styles s = Styles.read(table, 0, table.length);
assertArrayEquals(JC_CENTER, s.papxChain(10));
}
@Test
void selfBase_cycleTerminated() {
// istdBase=сам на себя — защита MAX_CHAIN: 16 копий, не бесконечность
byte[] table = stsh(12, std(65, 1, 10, JC_CENTER, null));
Styles s = Styles.read(table, 0, table.length);
byte[] chain = s.papxChain(10);
assertEquals(16 * JC_CENTER.length, chain.length,
"цепочка обязана оборваться: " + Arrays.toString(chain));
}
@Test
void characterStyle_noParagraphProps() {
// stk=2 (символьный) — UpxPapx/UpxChpx не читаются (§2.9.267)
byte[] table = stsh(12, std(65, 2, 0x0FFF, JC_CENTER, BOLD));
Styles s = Styles.read(table, 0, table.length);
assertArrayEquals(new byte[0], s.papxChain(10));
assertArrayEquals(new byte[0], s.chpxChain(10));
}
@Test
void brokenStsh_emptyTableNotThrow() {
assertEmptyFor(new byte[0]);
assertEmptyFor(new byte[] {18, 0, 0, 0}); // cstd=0
assertEmptyFor(new byte[] {18, 0, 1, 0, 4, 0}); // cbSTDBaseInFile<5
assertEmptyFor(new byte[] {2, 0, 16, 0, 10, 0, 0}); // cbStshi<4
// Std обрезан по конец потока — слот не заполнен, цепочка пуста
byte[] table = stsh(12, std(65, 1, 0x0FFF, JC_CENTER, BOLD));
byte[] truncated = Arrays.copyOf(table, 60);
Styles s = Styles.read(truncated, 0, truncated.length);
assertArrayEquals(new byte[0], s.papxChain(10));
assertArrayEquals(new byte[0], s.chpxChain(10));
}
private static void assertEmptyFor(byte[] table) {
Styles s = Styles.read(table, 0, table.length);
assertEquals(0, s.count(), "битый STSH — пустая таблица, не исключение");
assertArrayEquals(new byte[0], s.papxChain(10));
}
@Test
void zeroLcb_empty() {
byte[] table = stsh(12, std(65, 1, 0x0FFF, JC_CENTER, BOLD));
assertEquals(0, Styles.read(table, 0, 0).count());
}
@Test
void badFc_empty() {
byte[] table = stsh(12, std(65, 1, 0x0FFF, JC_CENTER, BOLD));
assertEquals(0, Styles.read(table, -1, table.length).count(), "fc<0");
assertEquals(0, Styles.read(table, table.length - 3, 3).count(),
"STSHI-заголовок не влезает в поток");
}
@Test
void hugeCstd_empty() {
// cstd ≥ 0x0FFE — зарезервировано (§2.9.271), таблица пустая
byte[] table = stsh(0x0FFE, std(65, 1, 0x0FFF, JC_CENTER, null));
assertEquals(0, Styles.read(table, 0, table.length).count());
}
@Test
void oddStshi_parsedWithPadding() {
// cbStshi=19 (нечётный) — LPStd-массив начинается со следующего чётного
ByteArrayOutputStream out = new ByteArrayOutputStream();
put16(out, 19); // cbStshi — нечётный
put16(out, 11); // cstd
put16(out, 0x0A); // cbSTDBaseInFile
out.write(new byte[15], 0, 15); // остальное STSHI (19 − 4)
out.write(0); // padding до чётной границы
for (int i = 0; i < 10; i++) {
put16(out, 0); // пустые фиксированные стили
}
byte[] s = std(65, 1, 0x0FFF, JC_CENTER, null);
put16(out, s.length);
out.write(s, 0, s.length);
byte[] table = out.toByteArray();
Styles st = Styles.read(table, 0, table.length);
assertArrayEquals(JC_CENTER, st.papxChain(10), "нечётный cbStshi — padding");
}
@Test
void stdWithoutName_noProps() {
// cbStd = только stdf — xstzName не влезает, стиль без свойств
byte[] table = stsh(12, new byte[10]);
Styles s = Styles.read(table, 0, table.length);
assertArrayEquals(new byte[0], s.papxChain(10));
}
@Test
void upxBeyondStd_stops() {
// cupx=1, LPUpx вылезает за Std — разбор UPX обрывается (§2.9.271)
byte[] stdf = new byte[10];
stdf[4] = 1; // cupx=1
byte[] name = new byte[8];
put16(name, 0, 2);
name[2] = 'A';
name[4] = 'b';
byte[] raw = concat(concat(stdf, name), new byte[] {6, 0, 1, 2});
byte[] table = stsh(12, raw);
Styles s = Styles.read(table, 0, table.length);
assertArrayEquals(new byte[0], s.papxChain(10));
}
@Test
void emptyUpxPapx_noProps() {
// UpxPapx с cbUpx=0 — ни istd, ни grpprl; UpxChpx на месте i=0 не читается
byte[] stdf = new byte[10];
long base = 65 | (1L << 16) | (0xFFFL << 20);
stdf[0] = (byte) base;
stdf[1] = (byte) (base >>> 8);
stdf[2] = (byte) (base >>> 16);
stdf[3] = (byte) (base >>> 24);
stdf[4] = 1; // cupx=1
byte[] name = new byte[8];
put16(name, 0, 2);
name[2] = 'A';
name[4] = 'b';
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(stdf, 0, 10);
out.write(name, 0, 8);
upx(out, new byte[0]); // cbUpx=0
byte[] table = stsh(12, out.toByteArray());
Styles s = Styles.read(table, 0, table.length);
assertArrayEquals(new byte[0], s.papxChain(10));
}
private static byte[] concat(byte[] a, byte[] b) {
byte[] out = new byte[a.length + b.length];
System.arraycopy(a, 0, out, 0, a.length);
System.arraycopy(b, 0, out, a.length, b.length);
return out;
}
}
@@ -0,0 +1,250 @@
package ru.pjandro.wordpdf.internal.doc;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/**
* Юниты {@link Tables} ([MS-DOC] §2.6.3, §2.9.321/.302/.303/.39/.171):
* TAP TTP-абзаца → сетка (ширины из rgdxaCenter, сдвиг от поля) и границы
* w:tblBorders; деградация в {@code null} на битом/отсутствующем
* sprmTDefTable.
*/
class TablesTest {
/** TDefTableOperand: ncols + centers (без rgTc80 — он не читается). */
private static byte[] defTable(int[] centers) {
byte[] op = new byte[3 + 2 * centers.length];
op[0] = (byte) (op.length - 2 + 1 & 0xFF);
op[1] = (byte) ((op.length - 2 + 1) >>> 8);
op[2] = (byte) (centers.length - 1);
for (int i = 0; i < centers.length; i++) {
op[3 + 2 * i] = (byte) centers[i];
op[4 + 2 * i] = (byte) (centers[i] >>> 8);
}
return concat(new byte[] {0x08, (byte) 0xD6}, op);
}
/** TableBordersOperand: 6 × Brc (cv + dptLineWidth + brcType + флаги). */
private static byte[] borders(int[][] brcs) {
byte[] op = new byte[1 + 6 * 8];
op[0] = 0x30;
for (int i = 0; i < brcs.length && i < 6; i++) {
int b = 1 + i * 8;
op[b] = (byte) brcs[i][0]; // R
op[b + 1] = (byte) brcs[i][1]; // G
op[b + 2] = (byte) brcs[i][2]; // B
op[b + 3] = (byte) brcs[i][3]; // fAuto (0xFF — auto)
op[b + 4] = (byte) brcs[i][4]; // dptLineWidth
op[b + 5] = (byte) brcs[i][5]; // brcType
}
return concat(new byte[] {0x13, (byte) 0xD6}, op);
}
/** TableBordersOperand80: 6 × Brc80 (dptLineWidth + brcType + ico + флаги). */
private static byte[] borders80(int[][] brc80s) {
byte[] op = new byte[1 + 6 * 4];
op[0] = 0x18;
for (int i = 0; i < brc80s.length && i < 6; i++) {
int b = 1 + i * 4;
op[b] = (byte) brc80s[i][0]; // dptLineWidth
op[b + 1] = (byte) brc80s[i][1]; // brcType
op[b + 2] = (byte) brc80s[i][2]; // ico
}
return concat(new byte[] {0x05, (byte) 0xD6}, op);
}
/** Prl выравнивания таблицы: sprmTJc (0x548A) / sprmTJc90 (0x5400), u16. */
private static byte[] tblJc(int sprm, int value) {
return concat(new byte[] {(byte) (sprm & 0xFF), (byte) (sprm >>> 8)},
new byte[] {(byte) value, (byte) (value >>> 8)});
}
private static byte[] concat(byte[]... parts) {
int len = 0;
for (byte[] p : parts) {
len += p.length;
}
byte[] out = new byte[len];
int at = 0;
for (byte[] p : parts) {
System.arraycopy(p, 0, out, at, p.length);
at += p.length;
}
return out;
}
@Test
void grid_widthsAndIndent() {
Tables.Grid g = Tables.parse(defTable(new int[] {100, 910, 1995}));
assertEquals(2, g.colWidths().length);
assertEquals(810, g.colWidths()[0]);
assertEquals(1085, g.colWidths()[1]);
assertEquals(100, g.indent(), "первый center — сдвиг от поля");
assertEquals("", g.bordersXml(), "без sprmTTableBorders — границ нет");
}
@Test
void grid_negativeIndent() {
// XAS со знаком (0xFF9C = −100) — таблица залезает на поле
Tables.Grid g = Tables.parse(defTable(new int[] {-100, 810}));
assertEquals(-100, g.indent());
assertEquals(910, g.colWidths()[0]);
}
@Test
void sprmTJc_centerInTap() {
Tables.Grid g = Tables.parse(concat(defTable(new int[] {0, 3000, 6000}),
tblJc(Grpprl.SPRM_T_JC, 1)));
assertEquals("center", g.tblJc());
}
@Test
void sprmTJc90_right_noModern() {
Tables.Grid g = Tables.parse(concat(defTable(new int[] {0, 3000, 6000}),
tblJc(Grpprl.SPRM_T_JC90, 2)));
assertEquals("right", g.tblJc());
}
@Test
void sprmTJc_modernWinsOver90() {
// современный перекрывает 90-вариант в любом порядке (тот же паттерн,
// что у d613 над d605)
assertEquals("center", Tables.parse(concat(defTable(new int[] {0, 3000, 6000}),
tblJc(Grpprl.SPRM_T_JC, 1), tblJc(Grpprl.SPRM_T_JC90, 2))).tblJc());
assertEquals("center", Tables.parse(concat(defTable(new int[] {0, 3000, 6000}),
tblJc(Grpprl.SPRM_T_JC90, 2), tblJc(Grpprl.SPRM_T_JC, 1))).tblJc());
}
@Test
void sprmTJc_left_omitted() {
// 0 = left (дефолт) → элемент не эмитится; валидных значений больше нет (§2.6.3)
assertNull(Tables.parse(concat(defTable(new int[] {0, 3000, 6000}),
tblJc(Grpprl.SPRM_T_JC, 0))).tblJc());
assertNull(Tables.parse(defTable(new int[] {0, 3000, 6000})).tblJc(),
"без sprmTJc — left");
}
@Test
void noDefTable_null() {
assertNull(Tables.parse(borders(new int[][] {{0, 0, 0, 0xFF, 4, 1}})),
"нет sprmTDefTable — сетку построить нельзя");
assertNull(Tables.parse(new byte[0]));
}
@Test
void badDefTable_null() {
assertNull(Tables.parse(defTable(new int[] {0, 0, 100})), "нулевая ширина");
assertNull(Tables.parse(defTable(new int[] {500, 400})), "отрицательная ширина");
byte[] ncolsZero = defTable(new int[] {0, 100});
ncolsZero[4] = 0; // ncols=0 (§2.9.321: 1..63)
assertNull(Tables.parse(ncolsZero));
byte[] truncated = {0x08, (byte) 0xD6, 0x04, 0x00, 0x02, 0x20, 0x03};
assertNull(Tables.parse(truncated), "centers не влезают в operand");
}
@Test
void borders_d613_typesColorsAndSkip() {
Tables.Grid g = Tables.parse(concat(
defTable(new int[] {0, 100}),
borders(new int[][] {
{0xFF, 0, 0, 0, 4, 1}, // top: single, красный 4/8pt
{0, 0, 0, 0, 0, 0}, // left: brcType=0 — не эмитится
{0, 0, 0, 0xFF, 12, 3}, // bottom: double, auto-цвет
{0, 0, 0, 0, 64, 0x40}, // right: brcType≥0x40 → sz×8
})));
String xml = g.bordersXml();
assertTrue(xml.contains("<w:top w:val=\"single\" w:sz=\"4\" w:color=\"FF0000\""), xml);
assertFalse(xml.contains("w:left"), "brcType=0 не эмитится: " + xml);
assertTrue(xml.contains("<w:bottom w:val=\"double\" w:sz=\"12\""), xml);
assertFalse(xml.contains("<w:bottom w:val=\"double\" w:sz=\"12\" w:color"),
"fAuto цвет не пишет: " + xml);
assertTrue(xml.contains("w:sz=\"512\""), "brcType 0x40: ширина в пунктах ×8: " + xml);
}
@Test
void borders80_fallbackAndPrecedence() {
Tables.Grid only80 = Tables.parse(concat(
defTable(new int[] {0, 100}),
borders80(new int[][] {{1, 1, 2}}))); // ico=2 → blue (§2.9.171)
String xml = only80.bordersXml();
assertTrue(xml.contains("<w:top w:val=\"single\" w:sz=\"2\""),
"dptLineWidth<2 → 2 (§2.9.37): " + xml);
assertTrue(xml.contains("w:color=\"0000FF\""), "ico→цвет: " + xml);
Tables.Grid both = Tables.parse(concat(
defTable(new int[] {0, 100}),
borders(new int[][] {{0xFF, 0, 0, 0, 4, 1}}),
borders80(new int[][] {{8, 3, 0}})));
assertTrue(both.bordersXml().contains("<w:top w:val=\"single\""),
"0xD613 приоритетнее 0xD605: " + both.bordersXml());
assertFalse(both.bordersXml().contains("double"), "0xD605 проигнорирован: "
+ both.bordersXml());
}
@Test
void unknownBrcType_fallsBackToSingle() {
Tables.Grid g = Tables.parse(concat(
defTable(new int[] {0, 100}),
borders(new int[][] {{0, 0, 0, 0xFF, 4, 0x7F}})));
assertTrue(g.bordersXml().contains("w:val=\"single\""), g.bordersXml());
}
@Test
void borderVal_fullStBorderTable() {
// ST_Border §2.9.39: каждый brcType — своё имя ST_Border
assertEquals("single", Tables.borderVal(0x01));
assertEquals("double", Tables.borderVal(0x03));
assertEquals("dotted", Tables.borderVal(0x06));
assertEquals("dashed", Tables.borderVal(0x07));
assertEquals("dotDash", Tables.borderVal(0x08));
assertEquals("dotDotDash", Tables.borderVal(0x09));
assertEquals("triple", Tables.borderVal(0x0A));
assertEquals("thinThickSmallGap", Tables.borderVal(0x0B));
assertEquals("thickThinSmallGap", Tables.borderVal(0x0C));
assertEquals("thinThickThinSmallGap", Tables.borderVal(0x0D));
assertEquals("thinThickMediumGap", Tables.borderVal(0x0E));
assertEquals("thickThinMediumGap", Tables.borderVal(0x0F));
assertEquals("thinThickThinMediumGap", Tables.borderVal(0x10));
assertEquals("thinThickLargeGap", Tables.borderVal(0x11));
assertEquals("thickThinLargeGap", Tables.borderVal(0x12));
assertEquals("thinThickThinLargeGap", Tables.borderVal(0x13));
assertEquals("wave", Tables.borderVal(0x14));
assertEquals("doubleWave", Tables.borderVal(0x15));
assertEquals("dashSmallGap", Tables.borderVal(0x16));
assertEquals("dashDotStroked", Tables.borderVal(0x17));
assertEquals("threeDEmboss", Tables.borderVal(0x18));
assertEquals("threeDEngrave", Tables.borderVal(0x19));
assertEquals("outset", Tables.borderVal(0x1A));
assertEquals("outset", Tables.borderVal(0x1B));
assertEquals("single", Tables.borderVal(0x02), "неизвестный тип — single");
}
@Test
void malformedOperands_ignored() {
// sprmTDefTable с operand < 3 байт — пропускается сканером
assertNull(Tables.parse(new byte[] {0x08, (byte) 0xD6, 0x02, 0x00, 0x01}),
"operand<3 — TDefTable игнорируется");
byte[] ncolsWide = defTable(new int[] {0, 100});
ncolsWide[4] = 64; // ncols=64 > 63 (§2.9.321)
assertNull(Tables.parse(ncolsWide));
// границы неверной длины (≠0x31 / ≠0x19) — игнор, сетка без границ
byte[] bad613 = concat(new byte[] {0x13, (byte) 0xD6, 0x10}, new byte[0x10]);
byte[] bad605 = {0x05, (byte) 0xD6, 0x04, 0x01, 0x02, 0x03, 0x04};
Tables.Grid g = Tables.parse(concat(defTable(new int[] {0, 100}), bad613, bad605));
assertEquals("", g.bordersXml(), "длина не по §2.9.302/.303 — границы игнорируются");
}
@Test
void borders80_icoBeyondPalette_noColor() {
// ico за таблицей §2.9.171 — цвет не пишется (FOP возьмёт auto)
Tables.Grid g = Tables.parse(concat(
defTable(new int[] {0, 100}),
borders80(new int[][] {{4, 1, 0xFF}})));
assertTrue(g.bordersXml().contains("<w:top"), g.bordersXml());
assertFalse(g.bordersXml().contains("w:color"), "ico=0xFF — цвета нет: "
+ g.bordersXml());
}
}