Мост .doc: аудит [MS-DOC] — подсветка/затенение, символьные стили, поля ячеек, first-page колонтитуки #86
@@ -39,10 +39,22 @@ import java.util.regex.Pattern;
|
||||
* (sprmSFPgnRestart/sprmSPgnStart97/sprmSNfcPgn → w:pgNumType), многостолбцовость
|
||||
* (sprmSCcolumns/… → w:cols, 0x0E → w:br type="column"), вертикальное
|
||||
* выравнивание ячеек (sprmTVertAlign → w:vAlign), картинки-якоря плавающих
|
||||
* объектов (0x08 — inline-приближение, PlcfSpa не переносится). Не переносятся:
|
||||
* объектов (0x08 — inline-приближение, PlcfSpa не переносится),
|
||||
* текстовыделитель (sprmCHighlight → w:highlight), затенения рана/абзаца
|
||||
* (sprmCShd/sprmCShd80 → rPr, sprmPShd/sprmPShd80 → pPr — w:shd), прямые
|
||||
* символьные стили (sprmCIstd + stk=3 в STSH → цепочка chpx в rPr), поля
|
||||
* ячеек (sprmTCellPadding/sprmTCellPaddingDefault → w:tcMar; по умолчанию
|
||||
* конвейер даёт дефолт Word 108/0), титульная страница секции
|
||||
* (sprmSFTitlePage → w:titlePg + first-колонтитуки Plcfhdd). Не переносятся:
|
||||
* семантика рестартов списков (fNoRestart/ilvlRestartLim), fLegal,
|
||||
* объединённые/вложенные ячейки и бордюры TC80; подсветка/затенения/границы
|
||||
* абзацев (PlfBdx) — конвейер их в FO не потребляет; сноски/комментарии
|
||||
* объединённые/вложенные ячейки и бордюры TC80, границы абзацев
|
||||
* (sprmPBrc* 0xC64E–0xC652 — конвейер не читает w:pBdr) и ячейки
|
||||
* (sprmTSetBrc — не читает w:tcBorders), высота строк (sprmTDyaRowHeight —
|
||||
* не читает w:trHeight),
|
||||
* «шапка-repeat»/cantSplit/widowControl, типы подчёркивания и цвет линии
|
||||
* (sprmCKul/sprmCCvUl — всегда single), эффетки шрифта, отступы Dxc
|
||||
* (hundredths of a character — пайплайн не читает w:*Chars);
|
||||
* сноски/комментарии
|
||||
* (0x02/0x05) и инструкции полей (0x13–0x14) выбрасываются,
|
||||
* результат поля (0x14–0x15) остаётся; поле {@code HYPERLINK} в основном
|
||||
* тексте переносится как {@code w:hyperlink} с внешней rels-связью на URL из
|
||||
@@ -139,12 +151,16 @@ public final class DocToDocx {
|
||||
List<Sections.Section> secs = sections.list();
|
||||
String[] hdrRel = new String[secs.size()];
|
||||
String[] ftrRel = new String[secs.size()];
|
||||
String[] firstHdrRel = new String[secs.size()];
|
||||
String[] firstFtrRel = new String[secs.size()];
|
||||
// Odd header/footer каждой секции → type="default" (FOP не различает
|
||||
// чётные/нечётные); guard-абзац истории отбрасывается. История
|
||||
// cpStart == cpEnd не определена (§2.4.4) — ни части, ни ссылки:
|
||||
// docx4j наследует полосы предыдущей секции. Guard-only история —
|
||||
// часть с единственным <w:p/> (явно пустой колонтитул, обрывающий
|
||||
// наследование; пустой w:hdr невалиден — ≥1 блочный элемент).
|
||||
// First-page истории (4/5) эмитятся только при sprmSFTitlePage —
|
||||
// как type="first" (docx4j+FOP различают first/default).
|
||||
int hdrNo = 0;
|
||||
int ftrNo = 0;
|
||||
for (int i = 0; i < secs.size(); i++) {
|
||||
@@ -168,9 +184,33 @@ public final class DocToDocx {
|
||||
: "<w:p/>")));
|
||||
ftrRel[i] = "rId" + parts.size();
|
||||
}
|
||||
if (secs.get(i).titlePage()) {
|
||||
Headers.Story firstHdr = headers.firstHeader(i);
|
||||
if (!firstHdr.empty()) {
|
||||
hdrNo++;
|
||||
parts.add(new DocxWriter.Part("word/header" + hdrNo + ".xml",
|
||||
HEADER_CONTENT_TYPE, HEADER_REL_TYPE,
|
||||
DocxWriter.storyPart("w:hdr", firstHdr.hasContent()
|
||||
? body.buildRange(firstHdr.cpStart(), firstHdr.contentEnd(),
|
||||
true)
|
||||
: "<w:p/>")));
|
||||
firstHdrRel[i] = "rId" + parts.size();
|
||||
}
|
||||
Headers.Story firstFtr = headers.firstFooter(i);
|
||||
if (!firstFtr.empty()) {
|
||||
ftrNo++;
|
||||
parts.add(new DocxWriter.Part("word/footer" + ftrNo + ".xml",
|
||||
FOOTER_CONTENT_TYPE, FOOTER_REL_TYPE,
|
||||
DocxWriter.storyPart("w:ftr", firstFtr.hasContent()
|
||||
? body.buildRange(firstFtr.cpStart(), firstFtr.contentEnd(),
|
||||
true)
|
||||
: "<w:p/>")));
|
||||
firstFtrRel[i] = "rId" + parts.size();
|
||||
}
|
||||
}
|
||||
}
|
||||
// hyperlinks наполняются внутри build (body-pass); rels пишутся после
|
||||
String bodyXml = body.build(secs, hdrRel, ftrRel);
|
||||
String bodyXml = body.build(secs, hdrRel, ftrRel, firstHdrRel, firstFtrRel);
|
||||
return DocxWriter.write(bodyXml, parts, body.hyperlinks());
|
||||
}
|
||||
|
||||
@@ -193,6 +233,8 @@ public final class DocToDocx {
|
||||
private static final int FMULT_MULTIPLIER = 1;
|
||||
/** w:gridSpan эмитится только при покрытии ≥2 колонок tblGrid (§17.4.65). */
|
||||
private static final int MIN_GRID_SPAN = 2;
|
||||
/** Ipat=ipatSolid (0x01, [MS-DOC] Ipat): непрозрачная заливка цветом cvFore. */
|
||||
private static final int IPAT_SOLID = 1;
|
||||
/** Схема URL в начале строки (RFC 3986 §3.1), lookingAt. */
|
||||
private static final Pattern URL_SCHEME =
|
||||
Pattern.compile("[A-Za-z][A-Za-z0-9+.\\-]*:");
|
||||
@@ -261,7 +303,8 @@ public final class DocToDocx {
|
||||
* (ECMA-376 §17.6.22), поэтому берётся из sprmSBkc ПРЕДЫДУЩЕЙ секции
|
||||
* ([MS-DOC] §2.6.3 SBkcOperand — «break that terminates the section»).
|
||||
*/
|
||||
String build(List<Sections.Section> secs, String[] hdrRel, String[] ftrRel) {
|
||||
String build(List<Sections.Section> secs, String[] hdrRel, String[] ftrRel,
|
||||
String[] firstHdrRel, String[] firstFtrRel) {
|
||||
Map<Integer, String> sectByEndCp = new HashMap<>();
|
||||
int n = secs.size();
|
||||
for (int i = 0; i < n - 1; i++) {
|
||||
@@ -269,12 +312,14 @@ public final class DocToDocx {
|
||||
if (endCp >= 0 && endCp < ccpText
|
||||
&& pieces.charAt(endCp) == PAGE_OR_SECTION_BREAK) {
|
||||
sectByEndCp.put(endCp, sectPrXml(secs.get(i), hdrRel[i], ftrRel[i],
|
||||
firstHdrRel[i], firstFtrRel[i],
|
||||
i > 0 && secs.get(i - 1).continuous()));
|
||||
}
|
||||
}
|
||||
Sections.Section last = secs.get(n - 1);
|
||||
return buildRange(0, ccpText, false, sectByEndCp)
|
||||
+ sectPrXml(last, hdrRel[n - 1], ftrRel[n - 1],
|
||||
firstHdrRel[n - 1], firstFtrRel[n - 1],
|
||||
n > 1 && secs.get(n - 2).continuous());
|
||||
}
|
||||
|
||||
@@ -515,6 +560,11 @@ public final class DocToDocx {
|
||||
tcPr.append("<w:tcW w:w=\"").append(grid.colWidths()[i])
|
||||
.append("\" w:type=\"dxa\"/>");
|
||||
}
|
||||
// sprmTCellPadding/…Default (CT_TcPr, §17.4.72: tcMar до vAlign)
|
||||
String tcMar = tcMarXml(rowGrid, i);
|
||||
if (tcMar != null) {
|
||||
tcPr.append(tcMar);
|
||||
}
|
||||
// sprmTVertAlign (CT_TcPrBase: vAlign после tcW/gridSpan); top — не эмитится
|
||||
int[] va = rowGrid == null ? null : rowGrid.cellVAlign();
|
||||
if (va != null && i < va.length && (va[i] == 1 || va[i] == 2)) {
|
||||
@@ -547,6 +597,47 @@ public final class DocToDocx {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* w:tcMar ячейки i по полям строки (sprmTCellPadding/…Default):
|
||||
* пересечение диапазона [itcFirst, itcLim) с индексом ячейки, позже
|
||||
* заданный операнд перекрывает сторону ранее заданного (порядок
|
||||
* скана TAP = last-wins). Стороны только явные, порядок детей
|
||||
* CT_TcMar (§17.4.66): top → left → bottom → right. Нет явных
|
||||
* полей — null (конвейер даёт дефолт 108/0 — он же дефолт Word).
|
||||
*/
|
||||
private static String tcMarXml(Tables.Grid rowGrid, int i) {
|
||||
if (rowGrid == null) {
|
||||
return null;
|
||||
}
|
||||
int[] side = {-1, -1, -1, -1}; // top, left, bottom, right (dxa; −1 — нет)
|
||||
for (Tables.CellMargin m : rowGrid.cellMargins()) {
|
||||
if (i < m.itcFirst() || i >= m.itcLim()) {
|
||||
continue;
|
||||
}
|
||||
if ((m.sideMask() & 1) != 0) {
|
||||
side[0] = m.width();
|
||||
}
|
||||
if ((m.sideMask() & 2) != 0) {
|
||||
side[1] = m.width();
|
||||
}
|
||||
if ((m.sideMask() & 4) != 0) {
|
||||
side[2] = m.width();
|
||||
}
|
||||
if ((m.sideMask() & 8) != 0) {
|
||||
side[3] = m.width();
|
||||
}
|
||||
}
|
||||
String[] names = {"top", "left", "bottom", "right"};
|
||||
StringBuilder xml = new StringBuilder();
|
||||
for (int s = 0; s < side.length; s++) {
|
||||
if (side[s] >= 0) {
|
||||
xml.append("<w:").append(names[s]).append(" w:w=\"").append(side[s])
|
||||
.append("\" w:type=\"dxa\"/>");
|
||||
}
|
||||
}
|
||||
return xml.length() == 0 ? null : "<w:tcMar>" + xml + "</w:tcMar>";
|
||||
}
|
||||
|
||||
/** istd абзаца: последний прямой sprmPIstd в границах STSH, иначе из PAPX. */
|
||||
private int istdOf(byte[] direct, int fallback) {
|
||||
int[] istd = {fallback};
|
||||
@@ -585,8 +676,7 @@ public final class DocToDocx {
|
||||
/** Один ран свойств CHPX (поверх CHPX-цепочки стиля абзаца); CP после рана. */
|
||||
private int emitRun(StringBuilder runs, int cpStart, int cpEnd, byte[] grpprl,
|
||||
byte[] styleChpx) {
|
||||
RunProps props = runProps(
|
||||
styleChpx.length == 0 ? grpprl : concat(styleChpx, grpprl));
|
||||
RunProps props = runProps(chpxWithCharStyle(grpprl, styleChpx));
|
||||
String rPr = runXml(props);
|
||||
runHidden = props.hidden;
|
||||
runCaps = props.caps || props.smallCaps;
|
||||
@@ -967,6 +1057,11 @@ public final class DocToDocx {
|
||||
case Grpprl.SPRM_C_RG_FTC0 -> p.ftc0 = Grpprl.operandInt(buf, off, len);
|
||||
case Grpprl.SPRM_C_RG_FTC1 -> p.ftc1 = Grpprl.operandInt(buf, off, len);
|
||||
case Grpprl.SPRM_C_CV -> p.color = colorOf(buf, off, len);
|
||||
case Grpprl.SPRM_C_HIGHLIGHT -> p.highlight =
|
||||
highlightName(Grpprl.operandInt(buf, off, len));
|
||||
case Grpprl.SPRM_C_SHD -> p.shd = shdAttrs10(buf, off, len);
|
||||
case Grpprl.SPRM_C_SHD80 -> p.shd =
|
||||
shdAttrs80(Grpprl.operandInt(buf, off, len));
|
||||
case Grpprl.SPRM_C_HPS_POS -> p.pos = signedXas(buf, off, len);
|
||||
case Grpprl.SPRM_C_F_VANISH -> p.hidden = Grpprl.toggleOn(buf, off);
|
||||
case Grpprl.SPRM_C_F_CAPS -> p.caps = Grpprl.toggleOn(buf, off);
|
||||
@@ -979,7 +1074,10 @@ public final class DocToDocx {
|
||||
return p;
|
||||
}
|
||||
|
||||
/** rPr по CT_RPr-порядку: rFonts, b, i, strike, color, position, sz, szCs, u. */
|
||||
/**
|
||||
* rPr по CT_RPr-порядку (§17.3.2.28): rFonts, b, i, strike, color,
|
||||
* position, sz, szCs, highlight, u, shd.
|
||||
*/
|
||||
private String runXml(RunProps p) {
|
||||
StringBuilder xml = new StringBuilder();
|
||||
String ascii = p.ftc0 >= 0 ? fonts.font(p.ftc0) : null;
|
||||
@@ -1018,15 +1116,21 @@ public final class DocToDocx {
|
||||
if (p.szCs > 0) {
|
||||
xml.append("<w:szCs w:val=\"").append(p.szCs).append("\"/>");
|
||||
}
|
||||
if (p.highlight != null) {
|
||||
xml.append("<w:highlight w:val=\"").append(p.highlight).append("\"/>");
|
||||
}
|
||||
if (p.underline) {
|
||||
xml.append("<w:u w:val=\"single\"/>");
|
||||
}
|
||||
if (p.shd != null) {
|
||||
xml.append("<w:shd ").append(p.shd).append("/>");
|
||||
}
|
||||
return xml.length() == 0 ? "" : "<w:rPr>" + xml + "</w:rPr>";
|
||||
}
|
||||
|
||||
/**
|
||||
* Дети pPr по CT_PPr (§17.3.1.26): pageBreakBefore, tabs, spacing, ind,
|
||||
* jc (обёртку {@code <w:pPr>} дописывает {@link #paraXml}).
|
||||
* Дети pPr по CT_PPr (§17.3.1.26): pageBreakBefore, shd, tabs, spacing,
|
||||
* ind, jc (обёртку {@code <w:pPr>} дописывает {@link #paraXml}).
|
||||
* Скан идёт по конкатенации цепочки стиля абзаца (base-first) и
|
||||
* прямых PAPX — порядок сохраняет last-wins: base → derived → direct.
|
||||
* Отступы накапливает общий {@link Grpprl.Indents} (80-варианты
|
||||
@@ -1048,6 +1152,7 @@ public final class DocToDocx {
|
||||
boolean[] keepLines = {false};
|
||||
int[] ilvl = {0};
|
||||
int[] ilfo = {0};
|
||||
String[] pShd = {null};
|
||||
List<int[]> tabs = new ArrayList<>();
|
||||
Grpprl.scan(grpprl, 0, grpprl.length, (sprm, buf, off, len) -> {
|
||||
ind.prl(sprm, buf, off, len);
|
||||
@@ -1080,6 +1185,9 @@ public final class DocToDocx {
|
||||
case Grpprl.SPRM_P_CHG_TABS -> applyTabs(tabs, buf, off, len, true);
|
||||
case Grpprl.SPRM_P_ILVL -> ilvl[0] = Grpprl.operandInt(buf, off, len);
|
||||
case Grpprl.SPRM_P_ILFO -> ilfo[0] = signedXas(buf, off, len);
|
||||
case Grpprl.SPRM_P_SHD -> pShd[0] = shdAttrs10(buf, off, len);
|
||||
case Grpprl.SPRM_P_SHD80 -> pShd[0] =
|
||||
shdAttrs80(Grpprl.operandInt(buf, off, len));
|
||||
default -> { }
|
||||
}
|
||||
});
|
||||
@@ -1096,6 +1204,11 @@ public final class DocToDocx {
|
||||
}
|
||||
// numPr — после pageBreakBefore, до tabs (CT_PPr, §17.3.1.26)
|
||||
xml.append(numPrXml(ilfo[0], ilvl[0]));
|
||||
// w:shd — после numPr, до tabs (CT_PPr §17.3.1.26: pBdr → shd → tabs;
|
||||
// границы абзацев мост не эмитит — w:pBdr конвейер не читает)
|
||||
if (pShd[0] != null) {
|
||||
xml.append("<w:shd ").append(pShd[0]).append("/>");
|
||||
}
|
||||
String tabsEl = tabsXml(tabs);
|
||||
if (!tabsEl.isEmpty()) {
|
||||
xml.append(tabsEl);
|
||||
@@ -1324,6 +1437,95 @@ public final class DocToDocx {
|
||||
buf[off + 2] & 0xFF);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ico (§2.9.171) → член ST_HighlightColor (§17.18.42) — соответствие
|
||||
* 1:1 по RGB палитры (teal 00FFFF = cyan, dark teal 008080 = darkCyan,
|
||||
* gray50 = darkGray, gray25 = lightGray). 0/auto/вне 1..16 → null
|
||||
* (не эмитится).
|
||||
*/
|
||||
private static String highlightName(int ico) {
|
||||
return switch (ico) {
|
||||
case 1 -> "black";
|
||||
case 2 -> "blue";
|
||||
case 3 -> "cyan";
|
||||
case 4 -> "green";
|
||||
case 5 -> "magenta";
|
||||
case 6 -> "red";
|
||||
case 7 -> "yellow";
|
||||
case 8 -> "white";
|
||||
case 9 -> "darkBlue";
|
||||
case 10 -> "darkCyan";
|
||||
case 11 -> "darkGreen";
|
||||
case 12 -> "darkMagenta";
|
||||
case 13 -> "darkRed";
|
||||
case 14 -> "darkYellow";
|
||||
case 15 -> "darkGray";
|
||||
case 16 -> "lightGray";
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* SHDOperand (§2.9.177): cb(1)=10 + Shd(10: cvFore/cvBack COLORREF +
|
||||
* ipat u16, §2.9.178) → атрибуты w:shd; cb≠10/обрезок → null.
|
||||
*/
|
||||
private static String shdAttrs10(byte[] buf, int off, int len) {
|
||||
if (len < 11 || (buf[off] & 0xFF) != 10) {
|
||||
return null;
|
||||
}
|
||||
return shdAttrs(Grpprl.operandInt(buf, off + 9, 2),
|
||||
colorOf(buf, off + 1, 4), colorOf(buf, off + 5, 4));
|
||||
}
|
||||
|
||||
/**
|
||||
* Shd80 (§2.9.176, u16: icoFore(5) icoBack(5) ipat(6)) → атрибуты
|
||||
* w:shd; Shd80Nil (0x1F/0x1F/0x3F) даёт null (цвета вне палитры).
|
||||
*/
|
||||
private static String shdAttrs80(int v) {
|
||||
return shdAttrs((v >>> 10) & 0x3F,
|
||||
Tables.icoColor(v & 0x1F), Tables.icoColor((v >>> 5) & 0x1F));
|
||||
}
|
||||
|
||||
/**
|
||||
* Ipat+цвета → атрибуты w:shd в форме, которую Word сам пишет при
|
||||
* doc→docx: фон в w:fill, w:val="clear". FOP закрашивает только
|
||||
* w:fill (зонд 2026-11: w:val="solid" w:color=RRGGBB w:fill="auto"
|
||||
* не рисует ничего); паттерны Ipat≥2 в FOP неразличимы — деградация
|
||||
* в фон cvBack (MS-DOC Ipat: вне ST_Shd паттерны «lost if converted
|
||||
* to ECMA-376»). ShdAuto/ShdNil (оба цвета auto, §2.9.178) и
|
||||
* нечем-красить (fill auto) → null.
|
||||
*/
|
||||
private static String shdAttrs(int ipat, String fore, String back) {
|
||||
if (fore == null && back == null) {
|
||||
return null;
|
||||
}
|
||||
String fill = ipat == IPAT_SOLID ? (fore != null ? fore : back) : back;
|
||||
return fill == null ? null
|
||||
: "w:val=\"clear\" w:color=\"auto\" w:fill=\"" + fill + "\"";
|
||||
}
|
||||
|
||||
/**
|
||||
* Grpprl рана с учётом sprmCIstd (§2.6.1): цепочка chpx символьного
|
||||
* стиля (stk=3) вставляется между цепочкой стиля абзаца и прямыми
|
||||
* CHPX — §2.4.6.5: символьные свойства сначала возвращаются к
|
||||
* результату стиля абзаца, затем символьный стиль, затем прямые.
|
||||
* Без sprmCIstd — прежняя конкатенация.
|
||||
*/
|
||||
private byte[] chpxWithCharStyle(byte[] grpprl, byte[] styleChpx) {
|
||||
int[] istd = {-1};
|
||||
Grpprl.scan(grpprl, 0, grpprl.length, (sprm, buf, off, len) -> {
|
||||
if (sprm == Grpprl.SPRM_C_ISTD) {
|
||||
int v = Grpprl.operandInt(buf, off, len);
|
||||
istd[0] = v < styles.count() ? v : -1;
|
||||
}
|
||||
});
|
||||
byte[] chStyle = istd[0] >= 0 ? styles.charChain(istd[0]) : new byte[0];
|
||||
if (chStyle.length == 0) {
|
||||
return styleChpx.length == 0 ? grpprl : concat(styleChpx, grpprl);
|
||||
}
|
||||
return concat(concat(styleChpx, chStyle), grpprl);
|
||||
}
|
||||
|
||||
/**
|
||||
* w:sectPr секции: ссылки на части колонтитуков (null — элемент не
|
||||
* пишется, docx4j наследует полосы предыдущей секции), затем w:type,
|
||||
@@ -1336,7 +1538,8 @@ public final class DocToDocx {
|
||||
* предыдущей секции, [MS-DOC] §2.6.3)
|
||||
*/
|
||||
private static String sectPrXml(Sections.Section s, String headerRelId,
|
||||
String footerRelId, boolean typeContinuous) {
|
||||
String footerRelId, String firstHeaderRelId, String firstFooterRelId,
|
||||
boolean typeContinuous) {
|
||||
StringBuilder xml = new StringBuilder("<w:sectPr>");
|
||||
// EG_HdrFtrReferences — до содержимого секции (CT_SectPr, ECMA-376 §17.2.3)
|
||||
if (headerRelId != null) {
|
||||
@@ -1347,6 +1550,14 @@ public final class DocToDocx {
|
||||
xml.append("<w:footerReference w:type=\"default\" r:id=\"")
|
||||
.append(footerRelId).append("\"/>");
|
||||
}
|
||||
if (firstHeaderRelId != null) {
|
||||
xml.append("<w:headerReference w:type=\"first\" r:id=\"")
|
||||
.append(firstHeaderRelId).append("\"/>");
|
||||
}
|
||||
if (firstFooterRelId != null) {
|
||||
xml.append("<w:footerReference w:type=\"first\" r:id=\"")
|
||||
.append(firstFooterRelId).append("\"/>");
|
||||
}
|
||||
if (typeContinuous) {
|
||||
xml.append("<w:type w:val=\"continuous\"/>");
|
||||
}
|
||||
@@ -1372,6 +1583,11 @@ public final class DocToDocx {
|
||||
.append("\" w:gutter=\"0\"/>");
|
||||
appendPgNumType(xml, s);
|
||||
appendCols(xml, s);
|
||||
// w:titlePg — после w:cols (CT_SectPrBase, §17.2.3): первая страница
|
||||
// секции использует first-части (ссылки w:type="first" выше)
|
||||
if (s.titlePage()) {
|
||||
xml.append("<w:titlePg/>");
|
||||
}
|
||||
xml.append("</w:sectPr>");
|
||||
return xml.toString();
|
||||
}
|
||||
@@ -1492,6 +1708,10 @@ public final class DocToDocx {
|
||||
/** sprmCFRMarkDel/sprmCFRMarkIns: непринятая правка → w:del/w:ins. */
|
||||
private boolean del;
|
||||
private boolean ins;
|
||||
/** sprmCHighlight: член ST_HighlightColor (§17.18.42); null — нет. */
|
||||
private String highlight;
|
||||
/** sprmCShd/sprmCShd80: готовые атрибуты w:shd; null — нет затенения. */
|
||||
private String shd;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,6 +52,27 @@ final class Grpprl {
|
||||
static final int SPRM_C_F_VANISH = 0x083C;
|
||||
/** sprmCHpsPos (§2.6.1, 2 байта со знаком): вертикальный сдвиг в hps. */
|
||||
static final int SPRM_C_HPS_POS = 0x4845;
|
||||
/**
|
||||
* sprmCHighlight (§2.6.1, 1 байт Ico): текстовыделитель. Ico (§2.9.171)
|
||||
* → w:highlight в порядке CT_RPr — конвейер рисует фон рана (пинь
|
||||
* WordPdfConverterTest#highlightAndShading_backgroundDrawn).
|
||||
*/
|
||||
static final int SPRM_C_HIGHLIGHT = 0x2A0C;
|
||||
/**
|
||||
* sprmCShd/sprmCShd80 (§2.6.1): затенение рана → w:shd в rPr.
|
||||
* SHDOperand (§2.9.177) = cb(1)=10 + Shd(10): cvFore/cvBack COLORREF
|
||||
* + ipat (§2.9.178); Shd80 (§2.9.176) — 2 байта: icoFore(5) icoBack(5)
|
||||
* ipat(6).
|
||||
*/
|
||||
static final int SPRM_C_SHD = 0xCA71;
|
||||
static final int SPRM_C_SHD80 = 0x4866;
|
||||
/**
|
||||
* sprmCIstd (§2.6.1, u16): istd прямого символьного стиля (stk=3 в STSH).
|
||||
* По §2.4.6.5 символьные свойства возвращаются к результату стиля абзаца,
|
||||
* затем накладывается цепочка chpx символьного стиля, затем прямые CHPX —
|
||||
* порядок конкатенации в {@code DocxBody.chpxWithCharStyle}.
|
||||
*/
|
||||
static final int SPRM_C_ISTD = 0x4A30;
|
||||
|
||||
// Paragraph Properties (§2.6.2, sgc 1)
|
||||
static final int SPRM_P_ISTD = 0x4600;
|
||||
@@ -123,6 +144,13 @@ final class Grpprl {
|
||||
* array that contained the sprmPTableProps»).
|
||||
*/
|
||||
static final int SPRM_P_TABLE_PROPS = 0x646B;
|
||||
/**
|
||||
* sprmPShd/sprmPShd80 (§2.6.2): затенение абзаца (те же Shd/Shd80, что
|
||||
* для рана) → w:shd в pPr между numPr и tabs (CT_PPr §17.3.1.26;
|
||||
* w:pBdr мост не эмитит).
|
||||
*/
|
||||
static final int SPRM_P_SHD = 0xC64D;
|
||||
static final int SPRM_P_SHD80 = 0x442D;
|
||||
|
||||
// Table Properties (§2.6.3, sgc 5)
|
||||
static final int SPRM_T_TABLE_BORDERS_80 = 0xD605;
|
||||
@@ -149,6 +177,28 @@ final class Grpprl {
|
||||
* строки → w:vAlign в tcPr.
|
||||
*/
|
||||
static final int SPRM_T_VERT_ALIGN = 0xD62C;
|
||||
/**
|
||||
* sprmTCellPadding/sprmTCellPaddingDefault (§2.6.3): поля ячеек —
|
||||
* CSSAOperand (§2.9.209): cb(1)=6 + CSSA (§2.9.96): itc(2, ItcFirstLim)
|
||||
* + grfbrc(1: маска сторон top|left|bottom|right = 1|2|4|8) + ftsWidth(1)
|
||||
* + wWidth(2). Поля переносятся только при ftsWidth=ftsDxa(0x03);
|
||||
* ftsNil(0) — сторона не задана. Default-вариант действует на весь ряд
|
||||
* (Word пишет имPLICIT-дефолт 108/0, но пайплайн при отсутствии даёт те
|
||||
* же 108 — замерено), padding-вариант — на диапазон [itcFirst, itcLim)
|
||||
* → w:tcMar.
|
||||
*/
|
||||
static final int SPRM_T_CELL_PADDING = 0xD632;
|
||||
static final int SPRM_T_CELL_PADDING_DEFAULT = 0xD634;
|
||||
/**
|
||||
* sprmTInsert (§2.6.3): вставка определений ячеек ряда — пропускается
|
||||
* правилом spra=3 (4 байта: itcFirst(1)+ctc(1)+dxaCol(2 XAS), §2.9.322;
|
||||
* ECMA-376 Part 4 описывал прежнюю форму rgttte ctc×6 байт, но [MS-DOC]
|
||||
* и реальные файлы Word сходятся на 4 байтах: в TAP образцов
|
||||
* ru-table-image.doc/ru-en-mixed.doc following-sprm выравниваются ровно
|
||||
* при 4). Сетку из sprmTInsert мост не строит (остаток — javadoc Tables);
|
||||
* регрессия выравнивания — GrpprlTest#tInsertOperand_skippedBySpra.
|
||||
*/
|
||||
static final int SPRM_T_INSERT = 0x7621;
|
||||
|
||||
// Section Properties (§2.6.4, sgc 4)
|
||||
static final int SPRM_S_DYA_HDR_TOP = 0xB017;
|
||||
@@ -181,6 +231,12 @@ final class Grpprl {
|
||||
*/
|
||||
static final int SPRM_S_DXA_COL_WIDTH = 0xF203;
|
||||
static final int SPRM_S_DXA_COL_SPACING = 0xF204;
|
||||
/**
|
||||
* sprmSFTitlePage (§2.6.4, Bool8): первая страница секции использует
|
||||
* собственные колонтитуки (истории 4/5 группы секции, §2.4.4) →
|
||||
* w:titlePg + ссылки w:type="first".
|
||||
*/
|
||||
static final int SPRM_S_F_TITLE_PAGE = 0x300A;
|
||||
|
||||
/**
|
||||
* Накопитель абзацных отступов PAPX (§2.6.2) — общий для
|
||||
|
||||
@@ -14,9 +14,11 @@ import ru.pjandro.wordpdf.ValidationException;
|
||||
* в вывод не попадает.</p>
|
||||
*
|
||||
* <p>В перенос идут odd header/footer каждой секции как {@code type="default"}
|
||||
* — FOP не различает чётные/нечётные страницы, а {@code titlePg} (первая
|
||||
* страница) не поддерживается. История с {@code cpStart == cpEnd} не
|
||||
* определена — часть и ссылка не эмитятся, docx4j наследует полосы
|
||||
* — FOP не различает чётные/нечётные страницы. First-page истории (4/5)
|
||||
* переносятся как {@code type="first"} только для секций с
|
||||
* {@code sprmSFTitlePage} (w:titlePg, конвейер различает first/default —
|
||||
* пинь {@code titlePg_firstPageHeader}). История с {@code cpStart == cpEnd}
|
||||
* не определена — часть и ссылка не эмитятся, docx4j наследует полосы
|
||||
* предыдущей секции (§2.4.4 «Same as Previous»).</p>
|
||||
*/
|
||||
final class Headers {
|
||||
@@ -54,6 +56,9 @@ final class Headers {
|
||||
/** Индексы внутри группы секции: 0 even hdr, 1 odd hdr, 2 even ftr, 3 odd ftr… */
|
||||
private static final int ODD_HEADER = 1;
|
||||
private static final int ODD_FOOTER = 3;
|
||||
/** Первая страница (истории 4/5, применяются при sprmSFTitlePage, §2.4.4). */
|
||||
private static final int FIRST_HEADER = 4;
|
||||
private static final int FIRST_FOOTER = 5;
|
||||
|
||||
private final int[] aCp;
|
||||
|
||||
@@ -94,6 +99,16 @@ final class Headers {
|
||||
return story(SEPARATOR_STORIES + section * STORIES_PER_SECTION + ODD_FOOTER);
|
||||
}
|
||||
|
||||
/** Заголовок первой страницы секции {@code section} (titlePg, §2.4.4). */
|
||||
Story firstHeader(int section) {
|
||||
return story(SEPARATOR_STORIES + section * STORIES_PER_SECTION + FIRST_HEADER);
|
||||
}
|
||||
|
||||
/** Колонтитул первой страницы секции {@code section} (titlePg, §2.4.4). */
|
||||
Story firstFooter(int section) {
|
||||
return story(SEPARATOR_STORIES + section * STORIES_PER_SECTION + FIRST_FOOTER);
|
||||
}
|
||||
|
||||
private Story story(int index) {
|
||||
if (index + 1 >= aCp.length) {
|
||||
return new Story(0, 0);
|
||||
|
||||
@@ -40,15 +40,16 @@ final class Sections {
|
||||
* финальный символ — 0x0C, §2.8.26) + геометрия из её Sepx + признак
|
||||
* «разрыв, заканчивающий секцию, не начинает новую страницу» +
|
||||
* ориентация (sprmSBOrientation), нумерация страниц (sprmSFPgnRestart/
|
||||
* sprmSPgnStart97/sprmSNfcPgn — pgNumStart=0 «не задан», nfcPgn — MSONFC)
|
||||
* и колонки (sprmSCcolumns/…; colWidths/colSpacings заполнены только при
|
||||
* evenlySpaced=false, индекс — номер колонки).
|
||||
* sprmSPgnStart97/sprmSNfcPgn — pgNumStart=0 «не задан», nfcPgn — MSONFC),
|
||||
* колонки (sprmSCcolumns/…; colWidths/colSpacings заполнены только при
|
||||
* evenlySpaced=false, индекс — номер колонки) и титульная страница
|
||||
* (sprmSFTitlePage → w:titlePg, §2.6.4).
|
||||
*/
|
||||
record Section(int cpStart, int cpEnd, int pageWidth, int pageHeight,
|
||||
int marginLeft, int marginRight, int marginTop, int marginBottom,
|
||||
int header, int footer, boolean continuous, boolean landscape,
|
||||
int pgNumStart, int nfcPgn, int columnCount, boolean evenlySpaced,
|
||||
int dxaColumns, int[] colWidths, int[] colSpacings) {
|
||||
int dxaColumns, int[] colWidths, int[] colSpacings, boolean titlePage) {
|
||||
}
|
||||
|
||||
/** Дефолты Word 97 (§2.6.3, twips). */
|
||||
@@ -78,6 +79,7 @@ final class Sections {
|
||||
private int footer = DEFAULT_HEADER_FOOTER;
|
||||
private boolean continuous;
|
||||
private boolean landscape;
|
||||
private boolean titlePage;
|
||||
private boolean pgnRestart;
|
||||
private int pgnStart97;
|
||||
private int nfcPgn;
|
||||
@@ -115,6 +117,8 @@ final class Sections {
|
||||
nfcPgn = value; // MSONFC ([MS-OSHARED] §2.2.1.3)
|
||||
} else if (sprm == Grpprl.SPRM_S_F_EVENLY_SPACED) {
|
||||
evenlySpaced = value != 0; // Bool8, дефолт true
|
||||
} else if (sprm == Grpprl.SPRM_S_F_TITLE_PAGE) {
|
||||
titlePage = value != 0; // Bool8 (§2.6.4)
|
||||
} else if (sprm == Grpprl.SPRM_S_C_COLUMNS) {
|
||||
// sprmSCcolumns = число колонок − 1 (§2.6.4)
|
||||
columnCount = Math.min(value + 1, MAX_COLUMNS);
|
||||
@@ -208,7 +212,7 @@ final class Sections {
|
||||
g.pgnRestart ? Math.max(1, g.pgnStart97) : 0,
|
||||
g.nfcPgn, g.columnCount, g.evenlySpaced, g.dxaColumns,
|
||||
Arrays.copyOf(g.colWidths, g.columnCount),
|
||||
Arrays.copyOf(g.colSpacings, g.columnCount)));
|
||||
Arrays.copyOf(g.colSpacings, g.columnCount), g.titlePage));
|
||||
}
|
||||
sections = List.copyOf(list);
|
||||
continuousEnds = cont;
|
||||
@@ -218,7 +222,7 @@ final class Sections {
|
||||
return new Section(cpStart, cpEnd, DEFAULT_PAGE_WIDTH, DEFAULT_PAGE_HEIGHT,
|
||||
DEFAULT_MARGIN, DEFAULT_MARGIN, DEFAULT_MARGIN, DEFAULT_MARGIN,
|
||||
DEFAULT_HEADER_FOOTER, DEFAULT_HEADER_FOOTER, false,
|
||||
false, 0, 0, 1, true, -1, new int[0], new int[0]);
|
||||
false, 0, 0, 1, true, -1, new int[0], new int[0], false);
|
||||
}
|
||||
|
||||
static Sections read(byte[] tableStream, long fcSed, long lcbSed, byte[] wordDocument,
|
||||
|
||||
@@ -12,7 +12,9 @@ package ru.pjandro.wordpdf.internal.doc;
|
||||
* + xstzName (cch(2)+2·cch+терминатор(2), §2.9.348) + cupx × LPUpx
|
||||
* (cbUpx(2) + данные, шаг 2+cbUpx с выравниванием на чёт). Для stk=1
|
||||
* (абзацный стиль) UPX[0] = UpxPapx (istd(2) + grpprlPapx), UPX[1] =
|
||||
* UpxChpx (grpprlChpx целиком), §2.9.267/.308/.309.</p>
|
||||
* UpxChpx (grpprlChpx целиком), §2.9.267/.308/.309; для stk=3 (символьный
|
||||
* стиль) единственный UPX = UpxChpx целиком (§2.9.267) — читается в
|
||||
* {@link #charChain} для sprmCIstd.</p>
|
||||
*
|
||||
* <p>Цепочка свойств стиля — base-first: сначала grpprl предка по
|
||||
* istdBase (0x0FFF — без предка), затем собственный grpprl (шаг 8
|
||||
@@ -29,6 +31,8 @@ final class Styles {
|
||||
|
||||
/** stk абзацного стиля (§2.9.260). */
|
||||
private static final int STK_PARAGRAPH = 1;
|
||||
/** stk символьного стиля (§2.9.260): UPX[0] = UpxChpx целиком. */
|
||||
private static final int STK_CHARACTER = 3;
|
||||
/** Индекс UpxPapx в Std абзацного стиля (§2.9.308). */
|
||||
private static final int UPX_PAPX = 0;
|
||||
/** Индекс UpxChpx в Std абзацного стиля (§2.9.309). */
|
||||
@@ -38,8 +42,8 @@ final class Styles {
|
||||
/** Защита от цикла в istdBase. */
|
||||
private static final int MAX_CHAIN = 16;
|
||||
|
||||
/** Один стиль: предка + собственные grpprl'ы (пустые массивы — нет). */
|
||||
private record Style(int istdBase, byte[] papx, byte[] chpx) {
|
||||
/** Один стиль: stk (§2.9.260), предка + собственные grpprl'ы (пустые — нет). */
|
||||
private record Style(int istdBase, int stk, byte[] papx, byte[] chpx) {
|
||||
}
|
||||
|
||||
private final Style[] styles;
|
||||
@@ -100,7 +104,7 @@ final class Styles {
|
||||
int cupx = table[std + 4] & 0xF;
|
||||
int p = std + cbStdf;
|
||||
if (p + 2 > stdEnd) {
|
||||
return new Style(NO_BASE, new byte[0], new byte[0]);
|
||||
return new Style(NO_BASE, stk, new byte[0], new byte[0]);
|
||||
}
|
||||
int cch = CfbReader.u16(table, p);
|
||||
p += 2 + 2 * cch + 2; // xstzName: cch + строка + chTerm (§2.9.348)
|
||||
@@ -119,13 +123,16 @@ final class Styles {
|
||||
} else if (i == UPX_CHPX) {
|
||||
chpx = slice(table, p, cbUpx); // UpxChpx (§2.9.343)
|
||||
}
|
||||
} else if (stk == STK_CHARACTER && i == UPX_PAPX && cbUpx > 0) {
|
||||
// Символьный стиль: единственный UPX = UpxChpx целиком (§2.9.267)
|
||||
chpx = slice(table, p, cbUpx);
|
||||
}
|
||||
p += cbUpx;
|
||||
if ((p & 1) != 0) {
|
||||
p++; // LPUpx выровнены на чёт, padding в cbUpx не входит
|
||||
}
|
||||
}
|
||||
return new Style(istdBase, papx, chpx);
|
||||
return new Style(istdBase, stk, papx, chpx);
|
||||
}
|
||||
|
||||
private static byte[] slice(byte[] src, int from, int len) {
|
||||
@@ -154,6 +161,19 @@ final class Styles {
|
||||
return chain(istd, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Цепочка chpx символьного стиля для sprmCIstd (§2.6.1): только стили
|
||||
* stk=3, иначе пусто (§2.4.6.5 — символьный стиль применяется к рану,
|
||||
* стиль другого типа игнорируется снисходительно).
|
||||
*/
|
||||
byte[] charChain(int istd) {
|
||||
if (istd < 0 || istd >= styles.length || styles[istd] == null
|
||||
|| styles[istd].stk() != STK_CHARACTER) {
|
||||
return new byte[0];
|
||||
}
|
||||
return chain(istd, false);
|
||||
}
|
||||
|
||||
private byte[] chain(int istd, boolean papx) {
|
||||
byte[] own = new byte[0];
|
||||
int depth = 0;
|
||||
|
||||
@@ -28,7 +28,13 @@ import java.util.List;
|
||||
* <p>Горизонтальное объединение ячеек переносится сеткой <b>самой строки</b>:
|
||||
* у TTP-абзаца каждой строки свой {@code sprmTDefTable} (§2.9.321), и
|
||||
* автомат {@code DocxBody} по нему выдаёт {@code w:gridSpan}+{@code w:tcW}
|
||||
* (сетка первой строки остаётся tblGrid).</p>
|
||||
* (сетка первой строки остаётся tblGrid). Явные поля ячеек
|
||||
* ({@code sprmTCellPadding}/{@code sprmTCellPaddingDefault}, CSSA §2.9.209)
|
||||
* переносятся {@code w:tcMar}; при их отсутствии конвейер даёт дефолт
|
||||
* 108/0 — он же дефолт Word (замер). {@code sprmTDxaGapHalf} не переносится
|
||||
* как поле: §2.6.3 — «not used to layout cell contents», это поправка
|
||||
* начала координат таблицы при {@code sprmTDxaLeft} (позиция уже зашита в
|
||||
* rgdxaCenter).</p>
|
||||
*
|
||||
* <p>Вне контура (деградация {@code null} / молчаливый пропуск): вложенные
|
||||
* таблицы (sprmPFInnerTtp), вертикальное объединение ячеек (vertMerge),
|
||||
@@ -46,15 +52,31 @@ final class Tables {
|
||||
/** Минимум центров в TDefTable: ncols≥1 → centers[ncols+1]≥2 (§2.9.321). */
|
||||
private static final int MIN_CENTERS = 2;
|
||||
|
||||
/** Fts=ftsDxa (0x03): wWidth CSSA задан в twips; прочие Fts сторона не задают (§2.6.3). */
|
||||
private static final int FTS_DXA = 0x03;
|
||||
/** Кап wWidth полей ячеек (31680 = 22″, §2.6.3). */
|
||||
private static final int MAX_CELL_MARGIN = 31680;
|
||||
|
||||
/**
|
||||
* Поля ячеек из одного CSSAOperand (§2.9.209): стороны grfbrc (биты
|
||||
* top|left|bottom|right = 1|2|4|8) с шириной wWidth (dxa, ≥0) для ячеек
|
||||
* ряда с индексами [itcFirst, itcLim). Default-operand (0xD634) — весь
|
||||
* ряд (itcLim = {@link Integer#MAX_VALUE}).
|
||||
*/
|
||||
record CellMargin(int itcFirst, int itcLim, int sideMask, int width) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Сетка строки: ширины колонок, сдвиг от поля, XML границ (может быть
|
||||
* пустым), выравнивание таблицы ("center"/"right"; null = left → элемент
|
||||
* не эмитится), вертикальное выравнивание содержимого ячеек по индексам
|
||||
* строки (sprmTVertAlign → {@code w:vAlign}: 0 top, 1 center, 2 bottom;
|
||||
* {@code null} — ни одного 0xD62C, все top).
|
||||
* {@code null} — ни одного 0xD62C, все top) и явные поля ячеек
|
||||
* (sprmTCellPadding/…Default → {@code w:tcMar}, пустой список — дефолт
|
||||
* конвейера 108/0, он же дефолт Word).
|
||||
*/
|
||||
record Grid(int[] colWidths, int indent, String bordersXml, String tblJc,
|
||||
int[] cellVAlign) {
|
||||
int[] cellVAlign, List<CellMargin> cellMargins) {
|
||||
|
||||
/**
|
||||
* Абсолютные границы колонок: [indent, indent+w0, …] — восстановленный
|
||||
@@ -97,6 +119,15 @@ final class Tables {
|
||||
"C0C0C0", // 16 gray 25%
|
||||
};
|
||||
|
||||
/**
|
||||
* Ico (§2.9.171) → RRGGBB; 0/auto и вне таблицы (в т.ч. 0x1F = nil у
|
||||
* Shd80) — {@code null}. Пользуется {@code DocxBody} для Shd80/
|
||||
* затенений.
|
||||
*/
|
||||
static String icoColor(int ico) {
|
||||
return ico > 0 && ico < ICO_COLORS.length ? ICO_COLORS[ico] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Имена ST_Border по brcType (§2.9.39, колонка Reference); 0 — none.
|
||||
* package-private хук для юнита полного покрытия таблицы.
|
||||
@@ -145,6 +176,7 @@ final class Tables {
|
||||
String[] jc = {null};
|
||||
boolean[] jcSeen = {false};
|
||||
List<int[]> vaRanges = new ArrayList<>();
|
||||
List<CellMargin> margins = new ArrayList<>();
|
||||
Grpprl.scan(tap, 0, tap.length, (sprm, buf, off, len) -> {
|
||||
if (sprm == Grpprl.SPRM_T_DEF_TABLE && len >= 3) {
|
||||
centers[0] = readDefTable(buf, off, len);
|
||||
@@ -165,6 +197,12 @@ final class Tables {
|
||||
// CellRangeVertAlign (§2.9.30): cb=3 + itcFirst + itcLim + VerticalAlign
|
||||
vaRanges.add(new int[] {buf[off + 1] & 0xFF, buf[off + 2] & 0xFF,
|
||||
buf[off + 3] & 0xFF});
|
||||
} else if (sprm == Grpprl.SPRM_T_CELL_PADDING
|
||||
|| sprm == Grpprl.SPRM_T_CELL_PADDING_DEFAULT) {
|
||||
CellMargin m = cssa(sprm, buf, off, len);
|
||||
if (m != null) {
|
||||
margins.add(m);
|
||||
}
|
||||
}
|
||||
});
|
||||
int[] c = centers[0];
|
||||
@@ -188,7 +226,32 @@ final class Tables {
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Grid(colWidths, c[0], borders[0], jc[0], cellVAlign);
|
||||
return new Grid(colWidths, c[0], borders[0], jc[0], cellVAlign, margins);
|
||||
}
|
||||
|
||||
/**
|
||||
* CSSAOperand (§2.9.209) полей ячеек: cb(1)=6 + itc(2, ItcFirstLim) +
|
||||
* grfbrc(1, маска сторон) + ftsWidth(1) + wWidth(2 XAS_nonNeg).
|
||||
* Переносится только ftsDxa (0x03) — ftsNil/percent/auto сторона не
|
||||
* задают (§2.6.3: wWidth ≤ 31680); битый операнд/пустая маска — null.
|
||||
* Default-operand (0xD634) действует на весь ряд: его itc по §2.6.3 —
|
||||
* фиктивные 0/1, диапазон заменяется на [0, ∞).
|
||||
*/
|
||||
private static CellMargin cssa(int sprm, byte[] buf, int off, int len) {
|
||||
if (len != 7 || (buf[off] & 0xFF) != 6 || (buf[off + 4] & 0xFF) != FTS_DXA) {
|
||||
return null;
|
||||
}
|
||||
int mask = buf[off + 3] & 0x0F;
|
||||
int width = CfbReader.u16(buf, off + 5);
|
||||
if (mask == 0 || width > MAX_CELL_MARGIN) {
|
||||
return null;
|
||||
}
|
||||
if (sprm == Grpprl.SPRM_T_CELL_PADDING_DEFAULT) {
|
||||
return new CellMargin(0, Integer.MAX_VALUE, mask, width);
|
||||
}
|
||||
int first = buf[off + 1] & 0xFF;
|
||||
int lim = buf[off + 2] & 0xFF;
|
||||
return lim > first ? new CellMargin(first, lim, mask, width) : null;
|
||||
}
|
||||
|
||||
/** sprmTJc/sprmTJc90 (§2.6.3): 1 → "center", 2 → "right", прочее (0/left) → null. */
|
||||
@@ -245,7 +308,7 @@ final class Tables {
|
||||
continue;
|
||||
}
|
||||
int ico = buf[b + 2] & 0xFF;
|
||||
String color = ico < ICO_COLORS.length ? ICO_COLORS[ico] : null;
|
||||
String color = icoColor(ico);
|
||||
appendBorder(xml, names[i], type, buf[b] & 0xFF, color);
|
||||
}
|
||||
return xml.length() == 0 ? "" : "<w:tblBorders>" + xml + "</w:tblBorders>";
|
||||
|
||||
@@ -2585,4 +2585,118 @@ class WordPdfConverterTest {
|
||||
minimalDocx("<w:p><w:r><w:t>ХАЙЛАЙТЖЕЛТЫЙ</w:t></w:r></w:p>"), true));
|
||||
}
|
||||
|
||||
/**
|
||||
* Поля УРОВНЯ ЯЧЕЙКИ (w:tcMar) рисуются так же, как tblCellMar: текст на
|
||||
* margin+padding (мост переносит sprmTCellPadding именно в w:tcMar).
|
||||
*/
|
||||
@Test
|
||||
void tableTcMar_textInsetLikeWord() throws Exception {
|
||||
byte[] docx = minimalDocx("<w:tbl><w:tblPr/>"
|
||||
+ "<w:tblGrid><w:gridCol w:w=\"4000\"/></w:tblGrid>"
|
||||
+ "<w:tr><w:tc><w:tcPr><w:tcMar><w:left w:w=\"288\" w:type=\"dxa\"/>"
|
||||
+ "</w:tcMar></w:tcPr><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=\"1440\" w:right=\"1800\" w:bottom=\"1440\" w:left=\"1800\""
|
||||
+ " w:header=\"851\" w:footer=\"992\" w:gutter=\"0\"/></w:sectPr>");
|
||||
Path pdf = convertPdf(docx, "t");
|
||||
// margin 1800 twips = 90pt + tcMar left 288 = 14.4pt (та же арифметика,
|
||||
// что у tableCellPadding_textInsetLikeWord)
|
||||
assertEquals(104.4, xOfMarker(pdf, 'Q'), 0.9);
|
||||
}
|
||||
|
||||
/**
|
||||
* .doc-путь: sprmCHighlight → жёлтый фон рана, sprmCShd (ipatSolid,
|
||||
* cvFore жёлтый) — тоже; baseline без свойств — ноль жёлтых px.
|
||||
* Регрессия — аудит [MS-DOC] 2026-11 (Grpprl/DocToDocx, Ico→ST_HighlightColor).
|
||||
*/
|
||||
@Test
|
||||
void docHighlightAndShading_yellowPixels() throws IOException {
|
||||
byte[] shdYellowSolid = {
|
||||
(byte) 0x71, (byte) 0xCA, 10,
|
||||
(byte) 0xFF, (byte) 0xFF, 0, 0, // cvFore = жёлтый (COLORREF R-first)
|
||||
0, 0, 0, (byte) 0xFF, // cvBack = auto
|
||||
1, 0, // ipat = ipatSolid
|
||||
};
|
||||
byte[] doc = classDDoc("ЖЕЛТШД\r", null, null, new int[] {0, 4},
|
||||
new byte[][] {prl(0x2A0C, 7), shdYellowSolid});
|
||||
assertTrue(countPixels(doc, true) > 0, "подсветка/затенение не нарисованы");
|
||||
assertTrue(norm(pdfText(convertPdf(doc, "тест"))).contains("ЖЕЛТШД"),
|
||||
"текст подсвеченного рана потерян");
|
||||
assertEquals(0, countPixels(classDDoc("ЖЕЛТШД\r", null, null,
|
||||
new int[0], new byte[0][]), true), "жёлтый утёк в baseline");
|
||||
}
|
||||
|
||||
/**
|
||||
* sprmSFTitlePage + first-колонтитук Plcfhdd: первая страница — «ПЕРВАЯ!»,
|
||||
* обычная — «ОБЫЧНАЯ» ( slots §2.8.22, w:titlePg §17.13.1.35; FOP
|
||||
* first/default различает — регрессия docx titlePg_firstPageHeader).
|
||||
* Регрессия — аудит [MS-DOC] 2026-11 (Sections/Headers/DocToDocx).
|
||||
*/
|
||||
@Test
|
||||
void docTitlePage_firstHeaderOnlyFirstPage() throws Exception {
|
||||
Path pdf = convertPdf(titlePageDoc(), "doc-titlepage");
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
assertEquals(2, doc.getNumberOfPages(), "разрыв 0x0C не дал страницу");
|
||||
}
|
||||
String p1 = norm(pdfPageText(pdf, 1));
|
||||
String p2 = norm(pdfPageText(pdf, 2));
|
||||
assertTrue(p1.contains("ПЕРВАЯ!"), "first-шапка не на первой странице: " + p1);
|
||||
assertFalse(p1.contains("ОБЫЧНАЯ"), "default-шапка утекла на первую: " + p1);
|
||||
assertTrue(p2.contains("ОБЫЧНАЯ"), "default-шапка пропала: " + p2);
|
||||
assertFalse(p2.contains("ПЕРВАЯ"), "first-шапка утекла на вторую: " + p2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Односекционный .doc с titlePg: body «Текст1⌬Текст2⏎» (0x0C на CP6),
|
||||
* Sepx — sprmSFTitlePage=1; Plcfhdd (13 aCP): odd hdr «ОБЫЧНАЯ»,
|
||||
* first hdr «ПЕРВАЯ!», footers не определены ([x,x), §2.4.4).
|
||||
*/
|
||||
private static byte[] titlePageDoc() throws IOException {
|
||||
String text = "Текст1" + (char) 0x0C + "Текст2\r"
|
||||
+ "\r\r\r\r\r\r" + "ОБЫЧНАЯ\r" + "ПЕРВАЯ!\r" + "\r";
|
||||
byte[] wd = new byte[2048 + 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, 20); // PlcfSed @0 + fcSepx=512
|
||||
pair(wd, 11, 20, 52); // Plcfhdd @20: aCp(13)
|
||||
pair(wd, 33, 72, 21); // Clx @72
|
||||
wd[512] = 3; // Sepx: cb=3, sprmSFTitlePage=1
|
||||
wd[513] = 0;
|
||||
wd[514] = 0x0A;
|
||||
wd[515] = 0x30;
|
||||
wd[516] = 1;
|
||||
byte[] t = text.getBytes(StandardCharsets.UTF_16LE);
|
||||
System.arraycopy(t, 0, wd, 2048, t.length);
|
||||
byte[] tab = new byte[93];
|
||||
put32(tab, 0, 0);
|
||||
put32(tab, 4, 14);
|
||||
put32(tab, 10, 512); // SED[0].fcSepx
|
||||
// aCp относительны header-документа: separators [0,6); odd hdr [6,14),
|
||||
// first hdr [14,22), остальное — [x,x) (не определено), хвост [22,23)
|
||||
int[] hdd = {0, 1, 2, 3, 4, 5, 6, 6, 14, 14, 14, 22, 23};
|
||||
for (int i = 0; i < hdd.length; i++) {
|
||||
put32(tab, 20 + i * 4, hdd[i]);
|
||||
}
|
||||
tab[72] = 0x02; // Clx Pcdt, один несжатый кусок
|
||||
put32(tab, 73, 16);
|
||||
put32(tab, 77, 0);
|
||||
put32(tab, 81, text.length());
|
||||
put32(tab, 87, 2048);
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+170
-1
@@ -1667,6 +1667,12 @@ class DocToDocxFormattingTest {
|
||||
*/
|
||||
private static byte[] craftDoc(String text, byte[] sepxGrpprl, byte[] data,
|
||||
List<ChpxRun> chpxRuns, List<PapxRun> papxRuns) throws IOException {
|
||||
return craftDoc(text, sepxGrpprl, data, chpxRuns, papxRuns, null);
|
||||
}
|
||||
|
||||
private static byte[] craftDoc(String text, byte[] sepxGrpprl, byte[] data,
|
||||
List<ChpxRun> chpxRuns, List<PapxRun> papxRuns, byte[] stsh)
|
||||
throws IOException {
|
||||
// FKP-страницы (1024/1536) обязаны влезать в поток даже без текста
|
||||
byte[] wd = new byte[Math.max(TEXT_FC, 2048) + text.length() * 2];
|
||||
put16(wd, 0, 0xA5EC);
|
||||
@@ -1684,12 +1690,18 @@ class DocToDocxFormattingTest {
|
||||
pair(wd, 13, 48, 12); // PlcfBtePapx @48, pn=3
|
||||
}
|
||||
pair(wd, 33, 60, 21); // Clx @60
|
||||
if (stsh != null) {
|
||||
pair(wd, 1, 82, stsh.length); // Stshf @82 (после Clx 60+21)
|
||||
}
|
||||
if (sepxGrpprl != null) {
|
||||
sepx(wd, 512, sepxGrpprl);
|
||||
}
|
||||
byte[] t = text.getBytes(StandardCharsets.UTF_16LE);
|
||||
System.arraycopy(t, 0, wd, TEXT_FC, t.length);
|
||||
byte[] tab = new byte[81];
|
||||
byte[] tab = new byte[stsh == null ? 81 : 82 + stsh.length];
|
||||
if (stsh != null) {
|
||||
System.arraycopy(stsh, 0, tab, 82, stsh.length);
|
||||
}
|
||||
put32(tab, 0, 0);
|
||||
put32(tab, 4, text.length());
|
||||
if (sepxGrpprl != null) {
|
||||
@@ -1872,6 +1884,163 @@ class DocToDocxFormattingTest {
|
||||
assertFalse(xml.contains("<w:vAlign"), "top и out-of-range не эмитятся: " + xml);
|
||||
}
|
||||
|
||||
/** CSSAOperand (§2.9.209) как Prl: cb=6 + itc(2) + grfbrc + fts + wWidth(2). */
|
||||
private static byte[] cssaOp(int sprm, int itcFirst, int itcLim, int grfbrc,
|
||||
int fts, int wWidth) {
|
||||
return new byte[] {(byte) (sprm & 0xFF), (byte) (sprm >>> 8), 6,
|
||||
(byte) itcFirst, (byte) itcLim, (byte) grfbrc, (byte) fts,
|
||||
(byte) wWidth, (byte) (wWidth >>> 8)};
|
||||
}
|
||||
|
||||
/** SHDOperand (§2.9.177): cb=10 + cvFore(4) + cvBack(4) + ipat(2), COLORREF R-first. */
|
||||
private static byte[] shd10(int sprm, int[] fore, int[] back, int ipat) {
|
||||
byte[] op = new byte[3 + 10];
|
||||
op[0] = (byte) (sprm & 0xFF);
|
||||
op[1] = (byte) (sprm >>> 8);
|
||||
op[2] = 10;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
op[3 + i] = (byte) fore[i];
|
||||
op[7 + i] = (byte) back[i];
|
||||
}
|
||||
op[11] = (byte) ipat;
|
||||
op[12] = (byte) (ipat >>> 8);
|
||||
return op;
|
||||
}
|
||||
|
||||
/**
|
||||
* sprmCHighlight (Ico→ST_HighlightColor) и sprmCShd/sprmCShd80 → rPr:
|
||||
* solid → fill=cvFore, паттерн → fill=cvBack, w:val="clear" (форма Word,
|
||||
* FOP красит только fill); ico=0/auto-оба-цвета не эмитятся.
|
||||
*/
|
||||
@Test
|
||||
void runHighlightAndShading_inRPr() throws IOException {
|
||||
int[] red = {0xFF, 0, 0, 0};
|
||||
int[] auto = {0, 0, 0, 0xFF};
|
||||
String xml = documentXml(craftDoc("HySh8PtAuto\r", null, null,
|
||||
List.of(new ChpxRun(0, prl(0x2A0C, 7)), // yellow
|
||||
new ChpxRun(2, shd10(0xCA71, red, auto, 1)), // solid red
|
||||
new ChpxRun(4, new byte[] {0x66, 0x48, // CShd80: fore
|
||||
(byte) (2 | (4 << 5) | (1 << 10)), // =blue(2),
|
||||
(byte) ((2 | (4 << 5) | (1 << 10)) >>> 8)}), // back=green(4)
|
||||
new ChpxRun(6, shd10(0xCA71, red, auto, 2)), // паттерн: fill=back
|
||||
new ChpxRun(8, concat(prl(0x2A0C, 0),
|
||||
shd10(0xCA71, auto, auto, 1)))), // auto — ничего
|
||||
List.of(new PapxRun(0, null))));
|
||||
assertTrue(xml.contains("<w:highlight w:val=\"yellow\"/>"), "highlight: " + xml);
|
||||
assertTrue(xml.contains("<w:shd w:val=\"clear\" w:color=\"auto\" "
|
||||
+ "w:fill=\"FF0000\"/>"), "CShd solid → fill=cvFore: " + xml);
|
||||
assertTrue(xml.contains("<w:shd w:val=\"clear\" w:color=\"auto\" "
|
||||
+ "w:fill=\"0000FF\"/>"), "CShd80 solid → fill=cvFore (Ico blue): " + xml);
|
||||
assertEquals(1, xml.split("w:fill=\"FF0000\"", -1).length - 1,
|
||||
"паттерн красит cvBack (auto→null), не cvFore: " + xml);
|
||||
assertFalse(xml.contains("w:fill=\"00FF00\""),
|
||||
"паттерн с auto-cvBack не должен брать cvFore: " + xml);
|
||||
assertFalse(xml.contains("w:fill=\"auto\""), xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* sprmCShd паттерна с явным cvBack → деградация в сплошной фон cvBack
|
||||
* (паттернов в FOP нет); w:shd рана идёт в rPr.
|
||||
*/
|
||||
@Test
|
||||
void runShadingPattern_degradesToBackFill() throws IOException {
|
||||
String xml = documentXml(craftDoc("Pat\r", null, null,
|
||||
List.of(new ChpxRun(0, shd10(0xCA71, new int[] {0xFF, 0, 0, 0},
|
||||
new int[] {0, 0xFF, 0, 0}, 2))),
|
||||
List.of(new PapxRun(0, null))));
|
||||
assertTrue(xml.contains("<w:shd w:val=\"clear\" w:color=\"auto\" "
|
||||
+ "w:fill=\"00FF00\"/>"), "паттерн → fill=cvBack: " + xml);
|
||||
}
|
||||
|
||||
/** sprmPShd/sprmPShd80 → w:shd в pPr до jc (CT_PPr: pBdr→shd→tabs→…→jc). */
|
||||
@Test
|
||||
void paraShd_inPPrBeforeJc() throws IOException {
|
||||
String xml = documentXml(craftDoc("Para\r", null, null, List.of(),
|
||||
List.of(new PapxRun(0, concat(prl(0x2461, 2),
|
||||
shd10(0xC64D, new int[] {0xFF, 0, 0, 0},
|
||||
new int[] {0, 0, 0, 0xFF}, 1))))));
|
||||
int shd = xml.indexOf("<w:shd w:val=\"clear\" w:color=\"auto\" "
|
||||
+ "w:fill=\"FF0000\"/>");
|
||||
int jc = xml.indexOf("<w:jc w:val=\"right\"/>");
|
||||
assertTrue(shd > 0 && jc > shd, "w:shd в pPr до w:jc (CT_PPr): " + xml);
|
||||
String p80 = documentXml(craftDoc("P80\r", null, null, List.of(),
|
||||
List.of(new PapxRun(0, new byte[] {0x2D, 0x44,
|
||||
(byte) (2 | (4 << 5) | (1 << 10)), (byte) 0x04}))));
|
||||
assertTrue(p80.contains("<w:shd w:val=\"clear\" w:color=\"auto\" "
|
||||
+ "w:fill=\"0000FF\"/>"), "sprmPShd80: " + p80);
|
||||
}
|
||||
|
||||
/**
|
||||
* sprmCIstd: chpx-цепочка символьного стиля (stk=3) между стилевой
|
||||
* papx-цепочкой и прямыми CHPX; прямые перекрывают стиль (last-wins).
|
||||
*/
|
||||
@Test
|
||||
void charStyle_viaIstd_mergesUnderDirect() throws IOException {
|
||||
// стиль istd=10 (stk=3): синий + underline; ран: istd + прямой cv=red
|
||||
byte[] style = std(65, 3, 0x0FFF, 1, null,
|
||||
concat(new byte[] {0x70, 0x68, 0, 0, (byte) 0xFF, 0}, prl(0x2A3E, 1)));
|
||||
byte[] stsh = new byte[2 + 18 + 10 * 2 + 2 + style.length];
|
||||
put16(stsh, 0, 18); // cbStshi
|
||||
put16(stsh, 2, 11); // cstd
|
||||
put16(stsh, 4, 0x0A); // cbSTDBaseInFile
|
||||
int p = 20;
|
||||
for (int i = 0; i < 10; i++) {
|
||||
put16(stsh, p, 0);
|
||||
p += 2;
|
||||
}
|
||||
lpstd(stsh, p, style);
|
||||
String xml = documentXml(craftDoc("Lnk\r", null, null,
|
||||
List.of(new ChpxRun(0, concat(prl2(0x4A30, 10),
|
||||
new byte[] {0x70, 0x68, (byte) 0xFF, 0, 0, 0}))),
|
||||
List.of(new PapxRun(0, null)), stsh));
|
||||
assertTrue(xml.contains("<w:u w:val=\"single\"/>"),
|
||||
"underline из символьного стиля потерян: " + xml);
|
||||
assertTrue(xml.contains("<w:color w:val=\"FF0000\""),
|
||||
"прямой cv обязан перекрыть стилевой: " + xml);
|
||||
assertFalse(xml.contains("<w:color w:val=\"0000FF\""), xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* sprmTCellPaddingDefault/…CellPadding → w:tcMar ячеек: Default — весь
|
||||
* ряд, диапазонный — свои ячейки; порядок детей CT_TcMar top→left (§17.4.66).
|
||||
*/
|
||||
@Test
|
||||
void cellMargins_becomeTcMar() throws IOException {
|
||||
String xml = documentXml(craftDoc("P" + (char) 7 + "Q" + (char) 7 + (char) 7 + "\r",
|
||||
null, null, List.of(),
|
||||
List.of(new PapxRun(0, prl(0x2416, 1)),
|
||||
new PapxRun(2, prl(0x2416, 1)),
|
||||
new PapxRun(4, concat(prl(0x2416, 1), prl(0x2417, 1),
|
||||
tdefTable(2, new int[] {0, 3000, 6000}),
|
||||
cssaOp(Grpprl.SPRM_T_CELL_PADDING_DEFAULT, 0, 1, 0x0A, 3, 108),
|
||||
cssaOp(Grpprl.SPRM_T_CELL_PADDING, 0, 1, 0x01, 3, 20))))));
|
||||
assertEquals(2, xml.split("<w:tcMar>", -1).length - 1,
|
||||
"обе ячейки получают Default-поля (108 L/R): " + xml);
|
||||
assertEquals(2, xml.split("<w:left w:w=\"108\" w:type=\"dxa\"/>", -1).length - 1, xml);
|
||||
int mar = xml.indexOf("<w:tcMar>");
|
||||
assertTrue(xml.indexOf("<w:top w:w=\"20\" w:type=\"dxa\"/>") > mar
|
||||
&& xml.indexOf("<w:left w:w=\"108\"") > xml.indexOf(
|
||||
"<w:top w:w=\"20\" w:type=\"dxa\"/>"),
|
||||
"диапазонный top=20 только у ячейки 0, top до left (CT_TcMar): " + xml);
|
||||
assertEquals(1, xml.split("<w:top w:w=\"20\"", -1).length - 1,
|
||||
"top=20 обязан быть у одной ячейки: " + xml);
|
||||
}
|
||||
|
||||
/** sprmSFTitlePage → w:titlePg после w:cols (CT_SectPrBase §17.2.3). */
|
||||
@Test
|
||||
void titlePage_emittedAfterCols() throws IOException {
|
||||
String xml = documentXml(craftDoc("x\r",
|
||||
concat(prl(0x300A, 1), prl2(0x500B, 1), prl(0x3005, 1),
|
||||
prl2(0x900C, 720)),
|
||||
null, List.of(), List.of(new PapxRun(0, null))));
|
||||
int cols = xml.indexOf("<w:cols ");
|
||||
int tp = xml.indexOf("<w:titlePg/>");
|
||||
assertTrue(cols > 0 && tp > cols, "w:titlePg после w:cols: " + xml);
|
||||
assertFalse(documentXml(craftDoc("x\r", prl2(0x900C, 720), null, List.of(),
|
||||
List.of(new PapxRun(0, null)))).contains("<w:titlePg/>"),
|
||||
"без sprmSFTitlePage — не эмитится");
|
||||
}
|
||||
|
||||
/** Якорь плавающей картинки 0x08 + sprmCPicLocation → inline-картинка (раньше выбрасывался). */
|
||||
@Test
|
||||
void drawnObject_becomesInlinePicture() throws IOException {
|
||||
|
||||
@@ -169,4 +169,34 @@ class GrpprlTest {
|
||||
assertEquals(300, md.right(), "right — слияние last-wins");
|
||||
assertEquals(120, md.left1(), "left1 — слияние last-wins");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tInsertOperand_skippedBySpra() {
|
||||
// sprmTInsert 0x7621 (§2.9.322): операнд 4 байта (itcFirst+ctc+dxaCol) —
|
||||
// правило spra=3 корректен и для формы ECMA-376 Part 4 (rgtte), и для
|
||||
// формы MS-DOC; в образцах ru-table-image.doc/ru-en-mixed.doc Word
|
||||
// пишет 4-байтовый, following-sprm выравнивается ровно при 4.
|
||||
// Следующий Prl (sprmTJc 0x548A) обязан дойти до sink несъеденным.
|
||||
byte[] buf = {
|
||||
0x21, 0x76, 0x00, 0x02, 0x68, 0x01, // tInsert: itcFirst=0, ctc=2, dxaCol=360
|
||||
(byte) 0x8A, 0x54, 0x01, 0x00, // sprmTJc = center
|
||||
};
|
||||
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(0x7621, 0x548A), seen, "скан не рассинхронизирован");
|
||||
assertEquals(List.of(4, 2), sizes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tInsertOperand_truncated_aborts() {
|
||||
// rgttte-хвост не влезает → обрыв без исключения (контракт scan)
|
||||
byte[] buf = {0x21, 0x76, 0x00, 0x02, 0x68};
|
||||
int[] count = {0};
|
||||
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> count[0]++);
|
||||
assertEquals(0, count[0]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,6 +64,13 @@ class HeadersTest {
|
||||
assertFalse(new Headers.Story(5, 6).hasContent());
|
||||
// секции 1 нет (aCp короче) → пустая история
|
||||
assertEquals(0, h.oddHeader(1).cpEnd());
|
||||
// slots FIRST_HEADER=4/FIRST_FOOTER=5 (§2.8.22): first hdr = [1020, 1022),
|
||||
// first ftr = [1022, 1024)
|
||||
Headers.Story fh = h.firstHeader(0);
|
||||
assertEquals(1020, fh.cpStart());
|
||||
assertEquals(1022, fh.cpEnd());
|
||||
assertTrue(fh.hasContent());
|
||||
assertEquals(1022, h.firstFooter(0).cpStart());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -199,6 +199,21 @@ class SectionsTest {
|
||||
* Spacing (§2.6.4): accessors секции; iCol за массивом — молча; restart
|
||||
* без start97 → старт 1.
|
||||
*/
|
||||
@Test
|
||||
void titlePage_flagFromSepx() {
|
||||
// sprmSFTitlePage Bool8=1 → Section.titlePage()=true; без sprm — false
|
||||
byte[] wd = new byte[4096];
|
||||
sepx(wd, 64, new byte[] {
|
||||
0x0A, 0x30, 1, // titlePage = true
|
||||
(byte) 0x21, (byte) 0xB0, (byte) 0x90, 0x01, // dxaLeft = 400
|
||||
});
|
||||
byte[] t = plcfSed(64);
|
||||
Sections s = Sections.read(t, 0, t.length, wd, 1000);
|
||||
assertTrue(s.list().get(0).titlePage());
|
||||
Sections plain = Sections.read(plcfSed(0), 0, plcfSed(0).length, wd, 1000);
|
||||
assertFalse(plain.list().get(0).titlePage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void orientationPgNumColumns_applied() {
|
||||
byte[] wd = new byte[4096];
|
||||
|
||||
@@ -141,6 +141,31 @@ class StylesTest {
|
||||
assertArrayEquals(new byte[0], s.chpxChain(10));
|
||||
}
|
||||
|
||||
@Test
|
||||
void characterStyle_stk3_chainViaCharChain() {
|
||||
// stk=3 (STCF, Word 97+): единственный UPX = UpxChpx целиком; цепочка
|
||||
// base-first (источник sprmCIstd); papx-цепочка символьного стиля пуста
|
||||
byte[] blue = {0x70, 0x68, 0x00, 0x00, (byte) 0xFF, 0x00}; // sprmCCv blue
|
||||
byte[] table = stsh(13,
|
||||
std(65, 3, 0x0FFF, null, blue),
|
||||
std(105, 3, 10, null, BOLD));
|
||||
Styles s = Styles.read(table, 0, table.length);
|
||||
assertArrayEquals(concat(blue, BOLD), s.charChain(11),
|
||||
"символьная цепочка base-first");
|
||||
assertArrayEquals(blue, s.charChain(10));
|
||||
assertArrayEquals(new byte[0], s.papxChain(11), "papx у символьного нет");
|
||||
}
|
||||
|
||||
@Test
|
||||
void charChain_nonCharacterStk_empty() {
|
||||
// sprmCIstd обязан указывать на символьный стиль; stk=1/2 и промахи — пусто
|
||||
byte[] table = stsh(12, std(65, 1, 0x0FFF, JC_CENTER, BOLD));
|
||||
Styles s = Styles.read(table, 0, table.length);
|
||||
assertArrayEquals(new byte[0], s.charChain(10), "stk=1 через charChain — пусто");
|
||||
assertArrayEquals(new byte[0], s.charChain(99));
|
||||
assertArrayEquals(new byte[0], s.charChain(-1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void brokenStsh_emptyTableNotThrow() {
|
||||
assertEmptyFor(new byte[0]);
|
||||
|
||||
@@ -276,4 +276,55 @@ class TablesTest {
|
||||
byte[] bad = {0x2C, (byte) 0xD6, 9, 0, 1, 2};
|
||||
assertNull(Tables.parse(concat(defTable(new int[] {0, 3000}), bad)).cellVAlign());
|
||||
}
|
||||
|
||||
/** CSSAOperand (§2.9.209): cb(1)=6 + itc(2) + grfbrc(1) + fts(1) + wWidth(2). */
|
||||
private static byte[] cssa(int sprm, int itcFirst, int itcLim, int grfbrc,
|
||||
int fts, int wWidth) {
|
||||
return new byte[] {(byte) (sprm & 0xFF), (byte) (sprm >>> 8), 6,
|
||||
(byte) itcFirst, (byte) itcLim, (byte) grfbrc, (byte) fts,
|
||||
(byte) wWidth, (byte) (wWidth >>> 8)};
|
||||
}
|
||||
|
||||
@Test
|
||||
void cellPadding_defaultAppliesToRowAndSidesParsed() {
|
||||
// Word пишет два …Default: L/R dxa=108 и T/B dxa=0 (образец doc-formats.doc)
|
||||
Tables.Grid g = Tables.parse(concat(defTable(new int[] {0, 3000}),
|
||||
cssa(Grpprl.SPRM_T_CELL_PADDING_DEFAULT, 0, 1, 0x0A, 3, 108),
|
||||
cssa(Grpprl.SPRM_T_CELL_PADDING_DEFAULT, 0, 1, 0x05, 3, 0)));
|
||||
assertEquals(2, g.cellMargins().size());
|
||||
Tables.CellMargin lr = g.cellMargins().get(0);
|
||||
assertEquals(0, lr.itcFirst());
|
||||
assertEquals(Integer.MAX_VALUE, lr.itcLim(), "Default-operand — весь ряд");
|
||||
assertEquals(0x0A, lr.sideMask());
|
||||
assertEquals(108, lr.width());
|
||||
assertEquals(0, g.cellMargins().get(1).width(), "явный 0 — поле переносится");
|
||||
}
|
||||
|
||||
@Test
|
||||
void cellPadding_rangeOperandKeepsItc() {
|
||||
Tables.Grid g = Tables.parse(concat(defTable(new int[] {0, 3000, 6000}),
|
||||
cssa(Grpprl.SPRM_T_CELL_PADDING, 1, 2, 0x02, 3, 25)));
|
||||
assertEquals(1, g.cellMargins().size());
|
||||
assertEquals(1, g.cellMargins().get(0).itcFirst());
|
||||
assertEquals(2, g.cellMargins().get(0).itcLim(), "padding — диапазон [1, 2)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void cellPadding_ftsNilEmptyMaskAndEmptyRangeIgnored() {
|
||||
// ftsNil (0) — сторона не задана (§2.6.3); маска 0 и пустой itc-диапазон — тоже
|
||||
Tables.Grid g = Tables.parse(concat(defTable(new int[] {0, 3000}),
|
||||
cssa(Grpprl.SPRM_T_CELL_PADDING_DEFAULT, 0, 1, 0x0A, 0, 0),
|
||||
cssa(Grpprl.SPRM_T_CELL_PADDING, 2, 2, 0x0A, 3, 108),
|
||||
cssa(Grpprl.SPRM_T_CELL_PADDING, 0, 3, 0x00, 3, 108)));
|
||||
assertTrue(g.cellMargins().isEmpty(), "ни одного переносимого поля");
|
||||
}
|
||||
|
||||
@Test
|
||||
void cellPadding_truncatedOperandIgnoredGridSurvives() {
|
||||
// cb=6, но операнд обрезан (len=5 ≠ 7) — молчаливый пропуск, сетка жива
|
||||
Tables.Grid g = Tables.parse(concat(defTable(new int[] {0, 3000}),
|
||||
new byte[] {0x34, (byte) 0xD6, 0x06, 0x00, 0x01, 0x0A, 0x03}));
|
||||
assertEquals(1, g.colWidths().length);
|
||||
assertTrue(g.cellMargins().isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user