Мост .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
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:
@@ -29,6 +29,9 @@ Thumbs.db
|
||||
# Рабочие материалы и эталоны разработки (вне git)
|
||||
/develop/
|
||||
|
||||
# Исходный dated-.docx [MS-DOC] — скачивается по команде из docs/standards/doc/README.md
|
||||
docs/standards/doc/ms-doc.docx
|
||||
|
||||
# Секреты деплоя
|
||||
.env
|
||||
|
||||
|
||||
+4
-1
@@ -1,7 +1,10 @@
|
||||
# Dev-стенд без ключа доступа: WORDPDF_API_KEY не задан → wordpdf.api-key пуст
|
||||
# → ApiKeyFilter прозрачен, springdoc включён. Проект wordpdf-dev — собственные
|
||||
# образы/контейнеры, с прод-запуском (wordpdf-prod, :9010) не конфликтует.
|
||||
# Запуск: podman-compose -f compose.dev.yml up -d --build
|
||||
# Запуск: podman-compose -f compose.dev.yml up -d --build --force-recreate
|
||||
# (--force-recreate обязателен: без него podman-compose пересоберёт
|
||||
# образ, но контейнеры оставит на старом — будет крутиться jar
|
||||
# прошлой сборки)
|
||||
# Вход: http://<LAN-IP хоста>:9011 (доступен из локальной сети; hostname -I на хосте)
|
||||
name: wordpdf-dev
|
||||
# podman-compose по умолчанию разделяет имя проекта/сервиса/номера подчёркиванием
|
||||
|
||||
@@ -11,6 +11,7 @@ SHA-256 `.md`-файлов — справочные: они производны
|
||||
|Файл|Документ|Редакция/дата|URL|SHA-256|
|
||||
|---|---|---|---|---|
|
||||
|`ms-doc.md`|[MS-DOC] «Word (.doc) Binary File Format» — бинарный формат .doc Word 97–2003 (WordDocument/1Table-потоки, FIB, CHPX/PAPX, Clx/PlcPcd/Pcd — «piece table»)|12.5 (260217, февраль 2026)|https://officeprotocoldocs-f5hpbjgea6b8gneq.b02.azurefd.net/files/MS-DOC/%5bMS-DOC%5d-260217.docx|`c2886120e92aa2790a5603156fb0ca8b23151d58476592fef3ede7fb6841ee7d`|
|
||||
|`ms-doc-full.md`|Тот же [MS-DOC] 12.5, полный конверт **с** HTML-packet-diagram'ами (`-t gfm`, raw_html включён): битовые макеты §2.4/§2.6/§2.9 и таблицы sprm §2.6.1–2.6.3 — то, что в `ms-doc.md` свёрнуто в `[TABLE]`|12.5 (260217, февраль 2026)|тот же dated-.docx, что `ms-doc.md`|`35cbcd5b5228cf02200008c2145d941e66dbf8a9e296305745d2bdc099c8a5ad`|
|
||||
|`ms-cfb.md`|[MS-CFB] «Compound File Binary File Format» — OLE2-контейнер .doc (заголовок, FAT/MiniFAT, directory entries, потоки)|13.0 (261026, октябрь 2026)|https://winprotocoldocs-bhdugrdyduf5h2e4.b02.azurefd.net/MS-CFB/%5bMS-CFB%5d-261026.docx|`84d0f9f282aa00dac631a575514264b6bc1f3cec1b9c8fed095e12f7cc042913`|
|
||||
|`ms-oshared.md`|[MS-OSHARED] «Office Common Data Types and Objects Structures» — общие типы MS-DOC/MS-PPT/MS-XLS (MSONFC/FilePointer/FixedPoint, тулбары TBC, property sets, RefEdit, VBA-подпись)|11.1 (251113, ноябрь 2025)|https://officeprotocoldocs-f5hpbjgea6b8gneq.b02.azurefd.net/files/MS-OSHARED/%5bMS-OSHARED%5d-251113.docx|`ccac510af0266a0804f6a242b08bc4df2f6d1f5b27935c113609b4faf198cb57`|
|
||||
|`ms-odraw.md`|[MS-ODRAW] «Office Drawing Binary File Format» — бинарные рисунки OfficeArt (картинки/фигуры внутри .doc)|12.4 (250819, август 2025)|https://officeprotocoldocs-f5hpbjgea6b8gneq.b02.azurefd.net/files/MS-ODRAW/%5bMS-ODRAW%5d-250819.docx|`f7b9b19222ca8b22ab773846a0c7ff4fa1898e391fff1b3ce41ca3b528f36cf6`|
|
||||
@@ -39,6 +40,10 @@ SHA-256 `.md`-файлов — справочные: они производны
|
||||
curl -sSL -o /tmp/msdoc.docx "https://officeprotocoldocs-f5hpbjgea6b8gneq.b02.azurefd.net/files/MS-DOC/%5bMS-DOC%5d-260217.docx"
|
||||
pandoc /tmp/msdoc.docx -t gfm-raw_html --wrap=none -o docs/standards/doc/ms-doc.md
|
||||
|
||||
# ms-doc-full.md — тот же dated-.docx, но raw_html ВКЛЮЧЁН: packet diagram'ы и
|
||||
# таблицы sprm (§2.6.1–2.6.3) остаются HTML-таблицами вместо [TABLE]-плейсхолдеров.
|
||||
pandoc /tmp/msdoc.docx -t gfm --wrap=none -o docs/standards/doc/ms-doc-full.md
|
||||
|
||||
# Окружение MS-DOC — те же dated-.docx (при 404 — самый свежий с лендингов ниже).
|
||||
# Два CDN: у windows_protocols-документов (CFB, OLEPS, WMF, EMF) путь БЕЗ сегмента /files/.
|
||||
O="https://officeprotocoldocs-f5hpbjgea6b8gneq.b02.azurefd.net/files"
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -20,7 +20,11 @@ import org.apache.commons.compress.utils.SeekableInMemoryByteChannel;
|
||||
* (TableIndent читает transitional-атрибуты {@code w:}); GlyphCoverage
|
||||
* режет раны по финальному тексту рана (после Symbol/Invisible). Каждый
|
||||
* рерайт работает только содержимым одной части, поэтому по-частная
|
||||
* цепочка эквивалентна последовательным полным проходам.
|
||||
* цепочка эквивалентна последовательным полным проходам. Правило 7
|
||||
* (TableIndent) — исключение из «по-частности»: у header/footer-частей
|
||||
* своей sectPr нет, ширина полосы передаётся из document.xml (один
|
||||
* дополнительный inflate до цикла; многосекционный документ — полоса
|
||||
* неоднозначна, header/footer пропускаются).
|
||||
*
|
||||
* <p>Неизменённые записи (медиа, rels, прочее) переносятся raw-копией
|
||||
* сжатых байтов — без inflate/deflate; прочие (редкие методы сжатия,
|
||||
@@ -55,6 +59,19 @@ public final class DocxRewritePipeline {
|
||||
boolean changed = false;
|
||||
try (ZipFile zf = new ZipFile(new SeekableInMemoryByteChannel(docx));
|
||||
ZipArchiveOutputStream zos = new ZipArchiveOutputStream(out)) {
|
||||
// Ширина полосы набора для правила 7 (таблицы в header/footer-
|
||||
// частях своей sectPr не содержат): из сырого document.xml —
|
||||
// геометрия инвариантна к рерайтам цепочки (Strict не трогает
|
||||
// w:pgSz/@w:w, а pgMar-чередование left|start покрывает strict).
|
||||
// Записи нет/несколько секций → −1, header/footer консервативно
|
||||
// пропускаются (та же неоднозначность полосы, что для body).
|
||||
int band = -1;
|
||||
ZipArchiveEntry docEntry = zf.getEntry("word/document.xml");
|
||||
if (docEntry != null) {
|
||||
band = TableIndentNormalizer.bandOf(
|
||||
new String(zf.getInputStream(docEntry).readAllBytes(),
|
||||
StandardCharsets.UTF_8));
|
||||
}
|
||||
for (ZipArchiveEntry entry : Collections.list(zf.getEntries())) {
|
||||
String name = entry.getName();
|
||||
byte[] rewritten = null;
|
||||
@@ -86,7 +103,7 @@ public final class DocxRewritePipeline {
|
||||
if (next != null) {
|
||||
cur = next;
|
||||
}
|
||||
next = TableIndentNormalizer.rewrite(cur);
|
||||
next = TableIndentNormalizer.rewritePart(name, cur, band);
|
||||
if (next != null) {
|
||||
cur = next;
|
||||
}
|
||||
|
||||
@@ -20,20 +20,31 @@ import java.util.zip.ZipOutputStream;
|
||||
* (аудит раскладки ECMA-376, матрица B3) — таблица рендерилась без учёта
|
||||
* tblInd. Нормализатор вычисляет итоговый отступ сам и записывает его в
|
||||
* {@code w:tblInd}, удалив {@code w:jc}: center → (W−T)/2+X, right → (W−T)+X,
|
||||
* где W — ширина полосы набора (pgSz−pgMar left/right), T — Σ gridCol.
|
||||
* где W — ширина полосы набора (pgSz−pgMar left/right), T — Σ gridCol,
|
||||
* X — прямой {@code w:tblInd} (отсутствующий или нулевой — 0). Свёртка
|
||||
* обязательна и при X=0: docx4j пишет центрированию абсолютный
|
||||
* {@code start-indent=(W−T)/2} БЕЗ вычета левого cellMar, а padding-
|
||||
* компенсация {@code LayoutPostRenderer} (шаг 4.25, рассчитана на tblInd-ветку,
|
||||
* где docx4j padding вычитает) прибавляет padding поверх — текст уезжает на
|
||||
* +padding от Word (замер: 165.57pt вместо 160.15pt).
|
||||
*
|
||||
* <p>Пропускается (не ломая существующее поведение): документы без
|
||||
* единственного body-level {@code w:sectPr} (несколько секций — полоса
|
||||
* неоднозначна), таблицы без {@code w:tblInd} (jc docx4j обрабатывает
|
||||
* корректно — аудит PASS), {@code w:tblW type="pct"} и таблицы с gridCol без
|
||||
* целого {@code w:w} (фактическая ширина неизвестна). Дефолты при отсутствии
|
||||
* неоднозначна), {@code w:tblW type="pct"} и таблицы с gridCol без целого
|
||||
* {@code w:w} (фактическая ширина неизвестна), {@code w:tblInd} не-dxa и
|
||||
* {@code w:tblPr} с {@code w:tblCellSpacing} без {@code w:tblInd} (вставить
|
||||
* тег в корректную позицию CT_TblPrBase некуда). Дефолты при отсутствии
|
||||
* pgSz/pgMar — 11906 и 1440/1440: измеренное поведение docx4j при отсутствующем
|
||||
* {@code w:pgMar} (левый край текста = 72pt = 1440 twips), а не ECMA-дефолт
|
||||
* 1800 — нормализатор обязан считать ту же полосу, что рендерит стек.
|
||||
*
|
||||
* <p>Трогает только {@code word/document.xml} (признак — {@code <w:body});
|
||||
* нечего менять → тот же массив. Регрессия —
|
||||
* WordPdfConverterTest#tableIndentCentered_shiftedLikeWord.
|
||||
* <p>{@link #normalize} трогает только {@code word/document.xml} (признак —
|
||||
* {@code <w:body}); нечего менять → тот же массив. {@link #rewritePart} —
|
||||
* хук общего прохода {@code DocxRewritePipeline}: сворачивает и таблицы в
|
||||
* {@code word/headerN.xml}/{@code word/footerN.xml} (полоса — из
|
||||
* document.xml, своей sectPr у частей нет). Регрессии —
|
||||
* WordPdfConverterTest#tableIndentCentered_shiftedLikeWord,
|
||||
* #headerTableIndent_centeredInHeader.
|
||||
*/
|
||||
public final class TableIndentNormalizer {
|
||||
|
||||
@@ -46,8 +57,13 @@ public final class TableIndentNormalizer {
|
||||
private static final String DOCUMENT_ENTRY = "word/document.xml";
|
||||
|
||||
private static final Pattern PG_SZ_W = Pattern.compile("<w:pgSz\\b[^>]*w:w=\"(\\d+)\"");
|
||||
private static final Pattern PG_MAR_LEFT = Pattern.compile("<w:pgMar\\b[^>]*w:left=\"(\\d+)\"");
|
||||
private static final Pattern PG_MAR_RIGHT = Pattern.compile("<w:pgMar\\b[^>]*w:right=\"(\\d+)\"");
|
||||
// strict-OOXML пишет поля как w:start/w:end; band считается из СЫРОГО
|
||||
// document.xml (до rule 1, которая их переименует) — чередование
|
||||
// обязательно, иначе полоса строгого документа молча возьмётся из дефолтов
|
||||
private static final Pattern PG_MAR_LEFT =
|
||||
Pattern.compile("<w:pgMar\\b[^>]*w:(?:left|start)=\"(\\d+)\"");
|
||||
private static final Pattern PG_MAR_RIGHT =
|
||||
Pattern.compile("<w:pgMar\\b[^>]*w:(?:right|end)=\"(\\d+)\"");
|
||||
private static final Pattern JC =
|
||||
Pattern.compile("<w:jc\\b[^>]*w:val=\"(center|right)\"[^>]*/>");
|
||||
private static final Pattern TBL_IND = Pattern.compile("<w:tblInd\\b[^>]*/>");
|
||||
@@ -91,6 +107,9 @@ public final class TableIndentNormalizer {
|
||||
}
|
||||
|
||||
/**
|
||||
* Переписывает jc+tblInd в абсолютный tblInd в {@code word/document.xml}
|
||||
* (полоса — из его единственной body-level sectPr).
|
||||
*
|
||||
* @return новая строка либо null, если менять нечего
|
||||
*/
|
||||
static String rewrite(String xml) {
|
||||
@@ -101,6 +120,47 @@ public final class TableIndentNormalizer {
|
||||
if (band < 0) {
|
||||
return null;
|
||||
}
|
||||
return rewriteBand(xml, band);
|
||||
}
|
||||
|
||||
/**
|
||||
* Рерайт одной zip-записи с известной шириной полосы набора: части
|
||||
* {@code word/headerN.xml}/{@code word/footerN.xml} не содержат своей
|
||||
* sectPr — полосу передаёт вызывающий из {@code word/document.xml}
|
||||
* (геометрия инвариантна к рерайтам цепочки: Strict не трогает
|
||||
* {@code w:pgSz/@w:w} и {@code w:pgMar/@w:left|right}). Многосекционный
|
||||
* документ ({@code band < 0} — полоса неоднозначна) консервативно
|
||||
* пропускается, как и body. Хук общего прохода DocxRewritePipeline.
|
||||
*
|
||||
* @param name имя zip-записи (правятся только document/header/footer-части)
|
||||
* @param band ширина полосы в twips, <0 — неоднозначна
|
||||
* @return новая строка либо null, если менять нечего
|
||||
*/
|
||||
static String rewritePart(String name, String xml, int band) {
|
||||
if (DOCUMENT_ENTRY.equals(name)) {
|
||||
return rewrite(xml);
|
||||
}
|
||||
if (!name.startsWith("word/header") && !name.startsWith("word/footer")) {
|
||||
return null;
|
||||
}
|
||||
if (xml.indexOf("<w:tbl") < 0 || band < 0) {
|
||||
return null;
|
||||
}
|
||||
return rewriteBand(xml, band);
|
||||
}
|
||||
|
||||
/** Ширина полосы по единственному body-level sectPr (хук DocxRewritePipeline). */
|
||||
static int bandOf(String xml) {
|
||||
return bandWidth(xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ядро свёртки: jc(center/right)+tblInd → абсолютный tblInd при заданной
|
||||
* полосе {@code band}.
|
||||
*
|
||||
* @return новая строка либо null, если менять нечего
|
||||
*/
|
||||
private static String rewriteBand(String xml, int band) {
|
||||
StringBuilder sb = null;
|
||||
int mark = 0;
|
||||
int scan = 0;
|
||||
@@ -121,13 +181,18 @@ public final class TableIndentNormalizer {
|
||||
continue;
|
||||
}
|
||||
Matcher ind = TBL_IND.matcher(pr);
|
||||
if (!ind.find()) {
|
||||
continue;
|
||||
}
|
||||
String indTag = ind.group();
|
||||
Matcher indW = TBL_IND_W.matcher(indTag);
|
||||
if (!indW.find() || "0".equals(indW.group(1))
|
||||
|| !indTag.contains("w:type=\"dxa\"")) {
|
||||
boolean hasInd = ind.find();
|
||||
int x = 0;
|
||||
if (hasInd) {
|
||||
String indTag = ind.group();
|
||||
Matcher indW = TBL_IND_W.matcher(indTag);
|
||||
if (!indW.find() || !indTag.contains("w:type=\"dxa\"")) {
|
||||
continue; // не-dxa — величина сдвига неизвестна
|
||||
}
|
||||
x = Integer.parseInt(indW.group(1));
|
||||
} else if (pr.contains("<w:tblCellSpacing")) {
|
||||
// tblInd по CT_TblPrBase идёт ПОСЛЕ tblCellSpacing — вставить
|
||||
// тег в корректную позицию некуда, консервативно пропускаем
|
||||
continue;
|
||||
}
|
||||
if (pr.contains("<w:tblW") && pr.contains("w:type=\"pct\"")) {
|
||||
@@ -137,18 +202,27 @@ public final class TableIndentNormalizer {
|
||||
if (width < 0) {
|
||||
continue;
|
||||
}
|
||||
int x = Integer.parseInt(indW.group(1));
|
||||
int newInd = "center".equals(jc.group(1))
|
||||
? (int) Math.round((band - width) / 2.0) + x
|
||||
: band - width + x;
|
||||
String fixedPr = pr.substring(0, jc.start()) + pr.substring(jc.end());
|
||||
Matcher indInFixed = TBL_IND.matcher(fixedPr);
|
||||
indInFixed.find();
|
||||
String indTagFixed = indInFixed.group();
|
||||
String newTag = indTagFixed.replaceFirst("w:w=\"-?\\d+\"",
|
||||
Matcher.quoteReplacement("w:w=\"" + newInd + "\""));
|
||||
fixedPr = fixedPr.substring(0, indInFixed.start()) + newTag
|
||||
+ fixedPr.substring(indInFixed.end());
|
||||
if (hasInd) {
|
||||
Matcher indInFixed = TBL_IND.matcher(fixedPr);
|
||||
indInFixed.find();
|
||||
String indTagFixed = indInFixed.group();
|
||||
String newTag = indTagFixed.replaceFirst("w:w=\"-?\\d+\"",
|
||||
Matcher.quoteReplacement("w:w=\"" + newInd + "\""));
|
||||
fixedPr = fixedPr.substring(0, indInFixed.start()) + newTag
|
||||
+ fixedPr.substring(indInFixed.end());
|
||||
} else {
|
||||
// X=0: tblInd на место удалённого jc — правый сосед либо
|
||||
// tblBorders, либо конец tblPr (tblCellSpacing отсеян выше),
|
||||
// порядок CT_TblPrBase (tblW → jc → tblCellSpacing → tblInd →
|
||||
// tblBorders, wml.xsd) сохранён
|
||||
fixedPr = fixedPr.substring(0, jc.start())
|
||||
+ "<w:tblInd w:w=\"" + newInd + "\" w:type=\"dxa\"/>"
|
||||
+ fixedPr.substring(jc.start());
|
||||
}
|
||||
if (sb == null) {
|
||||
sb = new StringBuilder(xml.length());
|
||||
}
|
||||
|
||||
@@ -320,7 +320,7 @@ public final class CfbReader {
|
||||
return new String(cfb, entryBase, nameLen - 2, StandardCharsets.UTF_16LE);
|
||||
}
|
||||
|
||||
private static int u16(byte[] b, int off) {
|
||||
static int u16(byte[] b, int off) {
|
||||
return (b[off] & 0xFF) | ((b[off + 1] & 0xFF) << 8);
|
||||
}
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ final class DocFile {
|
||||
PapxIndex papx = PapxIndex.read(table, fib.fcPlcfBtePapx(), fib.lcbPlcfBtePapx(),
|
||||
wordDocument);
|
||||
Sections sections = Sections.read(table, fib.fcPlcfSed(), fib.lcbPlcfSed(),
|
||||
wordDocument);
|
||||
wordDocument, fib.ccpText());
|
||||
return Math.max(cached, 1 + countPageBreaks() - sections.continuousSectionEnds()
|
||||
+ papx.countPageBreakBefore());
|
||||
}
|
||||
|
||||
@@ -2,11 +2,14 @@ package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Deque;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Мост бинарного .doc (Word 97–2003) → минимальный transitional-.docx.
|
||||
@@ -16,12 +19,20 @@ import java.util.Locale;
|
||||
* Разбор строго по [MS-DOC]/[MS-CFB]/[MS-OLEPS]: контейнер — {@link CfbReader},
|
||||
* общий разбор — {@link DocFile}, заголовок — {@link FibHeader}, текст —
|
||||
* {@link PieceTable} (§2.4.1), прямые
|
||||
* свойства — {@link ChpxIndex}/{@link PapxIndex} (§2.4.6.1/.2), полоса набора —
|
||||
* {@link Sections} (§2.8.26). Стили STSH, списки, таблицы-как-таблицы,
|
||||
* картинки и колонтитуки в первом инкременте не переносятся: содержимое ячеек
|
||||
* становится абзацами, объекты/сноски/комментарии (0x01/0x02/0x05/0x08) и
|
||||
* инструкции полей (0x13–0x14) выбрасываются, результат поля (0x14–0x15)
|
||||
* остаётся; прочие управляющие символы не эмитятся.</p>
|
||||
* свойства — {@link ChpxIndex}/{@link PapxIndex} (§2.4.6.1/.2), стили —
|
||||
* {@link Styles} (STSH, цепочка по istd, §2.4.6.5), списки — {@link Lists}
|
||||
* (PlfLst/PlfLfo → numbering.xml + w:numPr, §2.4.6.5 «Determining List
|
||||
* Formatting»), сетка таблиц — {@link Tables} (TAP, §2.6.3), полоса набора —
|
||||
* {@link Sections} (§2.8.26), колонтитуки — {@link Headers} (§2.4.1,
|
||||
* нечётные полосы каждой секции → свой {@code w:sectPr} с
|
||||
* {@code headerReference}/{@code footerReference} в pPr абзаца с
|
||||
* межсекционным разрывом + body-level sectPr последней секции),
|
||||
* картинки/OLE-fallback — {@link OfficeArt} ([MS-ODRAW]). Не переносятся:
|
||||
* семантика рестартов списков (fNoRestart/ilvlRestartLim), fLegal,
|
||||
* объединённые/вложенные ячейки и бордюры TC80; объекты/сноски/комментарии
|
||||
* (0x01/0x02/0x05/0x08) и инструкции полей (0x13–0x14) выбрасываются,
|
||||
* результат поля (0x14–0x15) остаётся; прочие управляющие символы не
|
||||
* эмитятся.</p>
|
||||
*
|
||||
* <p>Контракт ошибок: любой некорректный вход (не CFB, не Word, шифрование,
|
||||
* Word 6/95, обрезка, цикл в цепочках, страницы сверх лимита) —
|
||||
@@ -59,6 +70,10 @@ public final class DocToDocx {
|
||||
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer";
|
||||
private static final String IMAGE_REL_TYPE =
|
||||
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
|
||||
private static final String NUMBERING_CONTENT_TYPE =
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml";
|
||||
private static final String NUMBERING_REL_TYPE =
|
||||
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering";
|
||||
|
||||
private DocToDocx() {
|
||||
}
|
||||
@@ -77,38 +92,61 @@ public final class DocToDocx {
|
||||
DocFile file = DocFile.open(docBytes);
|
||||
FibHeader fib = file.fib();
|
||||
FontTable fonts = FontTable.read(file.table(), fib.fcSttbfFfn(), fib.lcbSttbfFfn());
|
||||
Styles styles = Styles.read(file.table(), fib.fcStshf(), fib.lcbStshf());
|
||||
Lists lists = Lists.read(file.table(), fib.fcPlfLst(), fib.lcbPlfLst(),
|
||||
fib.fcPlfLfo(), fib.lcbPlfLfo(), fonts);
|
||||
PapxIndex papx = PapxIndex.read(file.table(), fib.fcPlcfBtePapx(), fib.lcbPlcfBtePapx(),
|
||||
file.wordDocument());
|
||||
Sections sections = Sections.read(file.table(), fib.fcPlcfSed(), fib.lcbPlcfSed(),
|
||||
file.wordDocument());
|
||||
file.wordDocument(), fib.ccpText());
|
||||
ChpxIndex chpx = ChpxIndex.read(file.table(), fib.fcPlcfBteChpx(), fib.lcbPlcfBteChpx(),
|
||||
file.wordDocument());
|
||||
Headers headers = Headers.read(file.table(), fib.fcPlcfHdd(), fib.lcbPlcfHdd(),
|
||||
fib.ccpText() + fib.ccpFtn());
|
||||
List<DocxWriter.Part> parts = new ArrayList<>();
|
||||
DocxBody body = new DocxBody(file.pieces(), chpx, papx, fonts, fib.ccpText(),
|
||||
CfbReader.stream(file.streams(), "Data"), parts);
|
||||
String headerRelId = null;
|
||||
String footerRelId = null;
|
||||
// Odd header/footer секции 0 → type="default" (FOP не различает
|
||||
// чётные/нечётные); guard-абзац истории отбрасывается
|
||||
Headers.Story hdr = headers.oddHeader(0);
|
||||
if (hdr.hasContent()) {
|
||||
parts.add(new DocxWriter.Part("word/header1.xml", HEADER_CONTENT_TYPE,
|
||||
HEADER_REL_TYPE,
|
||||
DocxWriter.storyPart("w:hdr",
|
||||
body.buildRange(hdr.cpStart(), hdr.contentEnd(), true))));
|
||||
headerRelId = "rId" + parts.size();
|
||||
if (lists.hasNumbering()) {
|
||||
// relId этой части из XML не нужен — docx4j находит numbering по типу
|
||||
// связи; id колонтитулов считаются после своего add, не сдвигаются
|
||||
parts.add(new DocxWriter.Part("word/numbering.xml", NUMBERING_CONTENT_TYPE,
|
||||
NUMBERING_REL_TYPE,
|
||||
lists.numberingXml().getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
Headers.Story ftr = headers.oddFooter(0);
|
||||
if (ftr.hasContent()) {
|
||||
parts.add(new DocxWriter.Part("word/footer1.xml", FOOTER_CONTENT_TYPE,
|
||||
FOOTER_REL_TYPE,
|
||||
DocxWriter.storyPart("w:ftr",
|
||||
body.buildRange(ftr.cpStart(), ftr.contentEnd(), true))));
|
||||
footerRelId = "rId" + parts.size();
|
||||
DocxBody body = new DocxBody(file.pieces(), chpx, papx, fonts, styles, lists,
|
||||
fib.ccpText(), CfbReader.stream(file.streams(), "Data"), parts);
|
||||
List<Sections.Section> secs = sections.list();
|
||||
String[] hdrRel = new String[secs.size()];
|
||||
String[] ftrRel = new String[secs.size()];
|
||||
// Odd header/footer каждой секции → type="default" (FOP не различает
|
||||
// чётные/нечётные); guard-абзац истории отбрасывается. История
|
||||
// cpStart == cpEnd не определена (§2.4.4) — ни части, ни ссылки:
|
||||
// docx4j наследует полосы предыдущей секции. Guard-only история —
|
||||
// часть с единственным <w:p/> (явно пустой колонтитул, обрывающий
|
||||
// наследование; пустой w:hdr невалиден — ≥1 блочный элемент).
|
||||
int hdrNo = 0;
|
||||
int ftrNo = 0;
|
||||
for (int i = 0; i < secs.size(); i++) {
|
||||
Headers.Story hdr = headers.oddHeader(i);
|
||||
if (!hdr.empty()) {
|
||||
hdrNo++;
|
||||
parts.add(new DocxWriter.Part("word/header" + hdrNo + ".xml",
|
||||
HEADER_CONTENT_TYPE, HEADER_REL_TYPE,
|
||||
DocxWriter.storyPart("w:hdr", hdr.hasContent()
|
||||
? body.buildRange(hdr.cpStart(), hdr.contentEnd(), true)
|
||||
: "<w:p/>")));
|
||||
hdrRel[i] = "rId" + parts.size();
|
||||
}
|
||||
Headers.Story ftr = headers.oddFooter(i);
|
||||
if (!ftr.empty()) {
|
||||
ftrNo++;
|
||||
parts.add(new DocxWriter.Part("word/footer" + ftrNo + ".xml",
|
||||
FOOTER_CONTENT_TYPE, FOOTER_REL_TYPE,
|
||||
DocxWriter.storyPart("w:ftr", ftr.hasContent()
|
||||
? body.buildRange(ftr.cpStart(), ftr.contentEnd(), true)
|
||||
: "<w:p/>")));
|
||||
ftrRel[i] = "rId" + parts.size();
|
||||
}
|
||||
}
|
||||
return DocxWriter.write(body.build(sections, headerRelId, footerRelId), parts);
|
||||
return DocxWriter.write(body.build(secs, hdrRel, ftrRel), parts);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -124,10 +162,19 @@ public final class DocToDocx {
|
||||
/** Текст CP 0..ccpText → XML-тело {@code <w:body>}. */
|
||||
private static final class DocxBody {
|
||||
|
||||
/** Длина операнда LSPD: dyaLine (i16) + fMultLinespace (i16), §2.9.181. */
|
||||
private static final int LSPD_OPERAND_LEN = 4;
|
||||
/** fMultLinespace=1: dyaLine — множитель интервала в 240-х долях. */
|
||||
private static final int FMULT_MULTIPLIER = 1;
|
||||
|
||||
private final PieceTable pieces;
|
||||
private final ChpxIndex chpx;
|
||||
private final PapxIndex papx;
|
||||
private final FontTable fonts;
|
||||
/** Стили STSH — цепочки grpprl по istd абзаца (§2.4.6.5). */
|
||||
private final Styles styles;
|
||||
/** Списки PlfLst/PlfLfo — нумерация абзацев через w:numPr (§2.4.6.5). */
|
||||
private final Lists lists;
|
||||
private final int ccpText;
|
||||
/** Data-поток (.doc) для BLIP по sprmCPicLocation. */
|
||||
private final byte[] dataStream;
|
||||
@@ -139,40 +186,87 @@ public final class DocToDocx {
|
||||
private final StringBuilder instr = new StringBuilder();
|
||||
private boolean capturing;
|
||||
private int fldSimpleOpen;
|
||||
/** Карта «CP разрыва, заканчивающего секцию → его sectPr» (только body). */
|
||||
private Map<Integer, String> sectByEndCp = Map.of();
|
||||
/** sectPr разрыва, потреблённого в текущем абзаце (прикрепляется к Para). */
|
||||
private String pendingSectPr;
|
||||
|
||||
DocxBody(PieceTable pieces, ChpxIndex chpx, PapxIndex papx, FontTable fonts,
|
||||
int ccpText, byte[] dataStream, List<DocxWriter.Part> parts) {
|
||||
Styles styles, Lists lists, int ccpText, byte[] dataStream,
|
||||
List<DocxWriter.Part> parts) {
|
||||
this.pieces = pieces;
|
||||
this.chpx = chpx;
|
||||
this.papx = papx;
|
||||
this.fonts = fonts;
|
||||
this.styles = styles;
|
||||
this.lists = lists;
|
||||
this.ccpText = ccpText;
|
||||
this.dataStream = dataStream;
|
||||
this.parts = parts;
|
||||
}
|
||||
|
||||
String build(Sections sections, String headerRelId, String footerRelId) {
|
||||
return buildRange(0, ccpText, false)
|
||||
+ sectPr(sections, headerRelId, footerRelId);
|
||||
/**
|
||||
* Текст CP 0..ccpText → XML-тело {@code <w:body>}: абзацы + межсекционные
|
||||
* {@code w:sectPr} в pPr абзаца с разрывом 0x0C + body-level sectPr
|
||||
* последней секции. {@code w:type} секции описывает разрыв ПЕРЕД ней
|
||||
* (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) {
|
||||
Map<Integer, String> sectByEndCp = new HashMap<>();
|
||||
int n = secs.size();
|
||||
for (int i = 0; i < n - 1; i++) {
|
||||
int endCp = secs.get(i).cpEnd() - 1;
|
||||
if (endCp >= 0 && endCp < ccpText
|
||||
&& pieces.charAt(endCp) == PAGE_OR_SECTION_BREAK) {
|
||||
sectByEndCp.put(endCp, sectPrXml(secs.get(i), hdrRel[i], ftrRel[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],
|
||||
n > 1 && secs.get(n - 2).continuous());
|
||||
}
|
||||
|
||||
/**
|
||||
* Абзацы CP-диапазона [from, to) без sectPr — основной текст или
|
||||
* история колонтитука. {@code fieldsAsSimple}: поля PAGE/NUMPAGES/
|
||||
* SECTIONPAGES (первый токен инструкции, §2.9.133) → {@code w:fldSimple}
|
||||
* (FOP пере-вычисляет их, кэш результата отбрасывается); прочие поля —
|
||||
* как в теле: инструкция скрыта, кэш-результат сохранён.
|
||||
* Абзац CP-диапазона: терминатор, накопленные раны, прямой PAPX, istd,
|
||||
* sectPr межсекционного разрыва (nullable).
|
||||
*/
|
||||
private record Para(char termMark, StringBuilder runs, byte[] direct, int istd,
|
||||
String sectPr) {
|
||||
}
|
||||
|
||||
/** Абзацы CP-диапазона без межсекционных разрывов (история колонтитука). */
|
||||
String buildRange(int from, int to, boolean fieldsAsSimple) {
|
||||
return buildRange(from, to, fieldsAsSimple, Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Абзацы CP-диапазона [from, to) — основной текст (с картой
|
||||
* межсекционных разрывов) или история колонтитука (пустая карта).
|
||||
* {@code fieldsAsSimple}: поля PAGE/NUMPAGES/SECTIONPAGES (первый
|
||||
* токен инструкции, §2.9.133) → {@code w:fldSimple} (FOP пере-вычисляет
|
||||
* их, кэш результата отбрасывается); прочие поля — как в теле:
|
||||
* инструкция скрыта, кэш-результат сохранён.
|
||||
*/
|
||||
String buildRange(int from, int to, boolean fieldsAsSimple,
|
||||
Map<Integer, String> sectByEndCp) {
|
||||
this.fieldsAsSimple = fieldsAsSimple;
|
||||
this.sectByEndCp = sectByEndCp;
|
||||
this.pendingSectPr = null;
|
||||
fieldStack.clear();
|
||||
instr.setLength(0);
|
||||
capturing = false;
|
||||
fldSimpleOpen = 0;
|
||||
StringBuilder body = new StringBuilder();
|
||||
List<Para> paras = new ArrayList<>();
|
||||
int cp = from;
|
||||
while (cp < to) {
|
||||
int paraStart = cp;
|
||||
long paraFc = pieces.fcOf(paraStart);
|
||||
byte[] direct = papx.grpprlFor(paraFc);
|
||||
int istd = istdOf(direct, papx.istdFor(paraFc));
|
||||
byte[] styleChpx = styles.chpxChain(istd);
|
||||
StringBuilder runs = new StringBuilder();
|
||||
char termMark = 0;
|
||||
while (cp < to) {
|
||||
@@ -189,16 +283,185 @@ public final class DocToDocx {
|
||||
int runEnd = (int) Math.max(cp + 1L, Math.min(
|
||||
pieces.nextPieceBoundary(cp, to),
|
||||
cp + (rangeEnd - fc) / step));
|
||||
cp = emitRun(runs, cp, runEnd, grpprl);
|
||||
cp = emitRun(runs, cp, runEnd, grpprl, styleChpx);
|
||||
if (pendingSectPr != null) {
|
||||
// разрыв, заканчивающий секцию, потреблён в emitRun —
|
||||
// абзац обрывается на нём (0x0C и есть его ¶-маркер)
|
||||
termMark = PAGE_OR_SECTION_BREAK;
|
||||
break;
|
||||
}
|
||||
}
|
||||
emitPara(body, paraStart, runs, termMark);
|
||||
String sect = pendingSectPr;
|
||||
pendingSectPr = null;
|
||||
if (sect != null && inTable(direct)) {
|
||||
// Word не допускает разрыв секции в таблице (w:sectPr в
|
||||
// w:pPr внутри w:tc невалиден) — деградация в обычный
|
||||
// разрыв страницы (прежнее поведение)
|
||||
runs.append("<w:r><w:br w:type=\"page\"/></w:r>");
|
||||
sect = null;
|
||||
}
|
||||
paras.add(new Para(termMark, runs, direct, istd, sect));
|
||||
}
|
||||
return emitParas(paras);
|
||||
}
|
||||
|
||||
/**
|
||||
* Абзацы → тело с табличным автоматом ([MS-DOC] §2.4.3): абзац,
|
||||
* оканчивающийся 0x07 без TTP, закрывает ячейку; 0x07 с sprmPFTtp —
|
||||
* конец строки (TAP в его grpprl → сетка/границы, сам абзац не
|
||||
* эмитится); абзацы с 0x0D внутри открытой ячейки (или с
|
||||
* sprmPFInTable) — продолжение/начало ячейки; прочие — обычные w:p.
|
||||
* Без корректного sprmTDefTable строка деградирует в плоские абзацы
|
||||
* (прежнее поведение). Сетка первой строки действует на всю таблицу.
|
||||
*/
|
||||
private String emitParas(List<Para> paras) {
|
||||
StringBuilder body = new StringBuilder();
|
||||
List<List<Para>> rowCells = new ArrayList<>();
|
||||
List<Para> cell = null;
|
||||
boolean rowOpen = false;
|
||||
boolean tableOpen = false;
|
||||
Tables.Grid grid = null;
|
||||
for (Para p : paras) {
|
||||
if (p.termMark == CELL_MARK && hasTtp(p.direct)) {
|
||||
if (rowOpen) {
|
||||
Tables.Grid g = Tables.parse(p.direct);
|
||||
if (g != null) {
|
||||
if (!tableOpen) {
|
||||
body.append(openTable(g));
|
||||
tableOpen = true;
|
||||
grid = g;
|
||||
}
|
||||
body.append(rowXml(rowCells, grid));
|
||||
} else {
|
||||
if (tableOpen) {
|
||||
body.append("</w:tbl>");
|
||||
tableOpen = false;
|
||||
grid = null;
|
||||
}
|
||||
appendCellsFlat(body, rowCells);
|
||||
}
|
||||
}
|
||||
rowCells = new ArrayList<>();
|
||||
rowOpen = false;
|
||||
cell = null;
|
||||
continue;
|
||||
}
|
||||
if (p.termMark == CELL_MARK) {
|
||||
if (cell == null) {
|
||||
cell = new ArrayList<>();
|
||||
rowCells.add(cell);
|
||||
}
|
||||
cell.add(p);
|
||||
rowOpen = true;
|
||||
cell = null;
|
||||
} else if (cell != null) {
|
||||
cell.add(p); // продолжение многострочной ячейки
|
||||
} else if (rowOpen || inTable(p.direct)) {
|
||||
cell = new ArrayList<>();
|
||||
cell.add(p); // первый абзац следующей ячейки
|
||||
rowCells.add(cell);
|
||||
} else {
|
||||
if (tableOpen) {
|
||||
body.append("</w:tbl>");
|
||||
tableOpen = false;
|
||||
grid = null;
|
||||
}
|
||||
body.append(paraXml(p));
|
||||
}
|
||||
}
|
||||
if (!rowCells.isEmpty()) { // оборванная строка — деградация
|
||||
if (tableOpen) {
|
||||
body.append("</w:tbl>");
|
||||
}
|
||||
appendCellsFlat(body, rowCells);
|
||||
} else if (tableOpen) {
|
||||
body.append("</w:tbl>");
|
||||
}
|
||||
return body.toString();
|
||||
}
|
||||
|
||||
/** Один ран свойств CHPX; возвращает CP после рана. */
|
||||
private int emitRun(StringBuilder runs, int cpStart, int cpEnd, byte[] grpprl) {
|
||||
String rPr = runProps(grpprl);
|
||||
private void appendCellsFlat(StringBuilder body, List<List<Para>> cells) {
|
||||
for (List<Para> cell : cells) {
|
||||
for (Para p : cell) {
|
||||
body.append(paraXml(p));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Открытие w:tbl: tblPr (tblW → jc → tblInd → tblBorders) + tblGrid (§17.4.49). */
|
||||
private static String openTable(Tables.Grid g) {
|
||||
StringBuilder xml = new StringBuilder("<w:tbl><w:tblPr>");
|
||||
int total = 0;
|
||||
for (int w : g.colWidths()) {
|
||||
total += w;
|
||||
}
|
||||
xml.append("<w:tblW w:w=\"").append(total).append("\" w:type=\"dxa\"/>");
|
||||
if (g.tblJc() != null) {
|
||||
xml.append("<w:jc w:val=\"").append(g.tblJc()).append("\"/>");
|
||||
}
|
||||
if (g.indent() != 0) {
|
||||
xml.append("<w:tblInd w:w=\"").append(g.indent()).append("\" w:type=\"dxa\"/>");
|
||||
}
|
||||
xml.append(g.bordersXml());
|
||||
xml.append("</w:tblPr><w:tblGrid>");
|
||||
for (int w : g.colWidths()) {
|
||||
xml.append("<w:gridCol w:w=\"").append(w).append("\"/>");
|
||||
}
|
||||
return xml.append("</w:tblGrid>").toString();
|
||||
}
|
||||
|
||||
/** w:tr: ячейка i получает tcW i-й колонки; лишние ячейки — без tcW. */
|
||||
private String rowXml(List<List<Para>> cells, Tables.Grid grid) {
|
||||
StringBuilder xml = new StringBuilder("<w:tr>");
|
||||
int i = 0;
|
||||
for (List<Para> cell : cells) {
|
||||
xml.append("<w:tc>");
|
||||
if (i < grid.colWidths().length) {
|
||||
xml.append("<w:tcPr><w:tcW w:w=\"").append(grid.colWidths()[i])
|
||||
.append("\" w:type=\"dxa\"/></w:tcPr>");
|
||||
}
|
||||
if (cell.isEmpty()) {
|
||||
xml.append("<w:p/>"); // ≥1 абзац в ячейке обязательно (§17.4.42)
|
||||
} else {
|
||||
for (Para p : cell) {
|
||||
xml.append(paraXml(p));
|
||||
}
|
||||
}
|
||||
xml.append("</w:tc>");
|
||||
i++;
|
||||
}
|
||||
return xml.append("</w:tr>").toString();
|
||||
}
|
||||
|
||||
/** istd абзаца: последний прямой sprmPIstd в границах STSH, иначе из PAPX. */
|
||||
private int istdOf(byte[] direct, int fallback) {
|
||||
int[] istd = {fallback};
|
||||
Grpprl.scan(direct, 0, direct.length, (sprm, buf, off, len) -> {
|
||||
if (sprm == Grpprl.SPRM_P_ISTD) {
|
||||
int v = Grpprl.operandInt(buf, off, len);
|
||||
if (v >= 0 && v < styles.count()) {
|
||||
istd[0] = v;
|
||||
}
|
||||
}
|
||||
});
|
||||
return istd[0];
|
||||
}
|
||||
|
||||
/** sprmPFInTable в прямом grpprl абзаца (§2.6.2). */
|
||||
private static boolean inTable(byte[] grpprl) {
|
||||
boolean[] in = {false};
|
||||
Grpprl.scan(grpprl, 0, grpprl.length, (sprm, buf, off, len) -> {
|
||||
if (sprm == Grpprl.SPRM_P_F_IN_TABLE) {
|
||||
in[0] = Grpprl.toggleOn(buf, off);
|
||||
}
|
||||
});
|
||||
return in[0];
|
||||
}
|
||||
|
||||
/** Один ран свойств CHPX (поверх CHPX-цепочки стиля абзаца); CP после рана. */
|
||||
private int emitRun(StringBuilder runs, int cpStart, int cpEnd, byte[] grpprl,
|
||||
byte[] styleChpx) {
|
||||
String rPr = runProps(styleChpx.length == 0 ? grpprl : concat(styleChpx, grpprl));
|
||||
StringBuilder content = new StringBuilder();
|
||||
StringBuilder text = new StringBuilder();
|
||||
int cp = cpStart;
|
||||
@@ -226,6 +489,15 @@ public final class DocToDocx {
|
||||
break;
|
||||
case PAGE_OR_SECTION_BREAK:
|
||||
flushText(text, content);
|
||||
String sect = sectByEndCp.get(cp);
|
||||
if (sect != null) {
|
||||
// разрыв, заканчивающий секцию: символ потребляется,
|
||||
// w:br не эмитится — sectPr прикрепится к абзацу
|
||||
pendingSectPr = sect;
|
||||
cp++;
|
||||
closeRun(runs, rPr, content, text);
|
||||
return cp;
|
||||
}
|
||||
if (visible()) {
|
||||
content.append("<w:br w:type=\"page\"/>");
|
||||
}
|
||||
@@ -395,19 +667,23 @@ public final class DocToDocx {
|
||||
}
|
||||
}
|
||||
|
||||
private void emitPara(StringBuilder body, int paraStart, StringBuilder runs, char termMark) {
|
||||
byte[] grpprl = papx.grpprlFor(pieces.fcOf(paraStart));
|
||||
// Конец строки таблицы — пустой абзац с 0x07 и sprmPFTtp (§2.2):
|
||||
// это не ячейка, в вывод не попадает
|
||||
if (runs.length() == 0 && termMark == CELL_MARK && hasTtp(grpprl)) {
|
||||
return;
|
||||
/**
|
||||
* w:p абзаца: pPr из цепочки стиля + прямых PAPX (+ sectPr последним
|
||||
* ребёнком CT_PPr, §17.3.1.26), раны, пустой → {@code <w:p/>}.
|
||||
*/
|
||||
private String paraXml(Para p) {
|
||||
String props = paraProps(p.istd(), p.direct());
|
||||
if (p.sectPr() != null) {
|
||||
// sectPr обязывает pPr существовать; абзац без ранов с sectPr —
|
||||
// не <w:p/>, а <w:p><w:pPr>…</w:pPr></w:p>
|
||||
return "<w:p><w:pPr>" + props + p.sectPr() + "</w:pPr>"
|
||||
+ p.runs() + "</w:p>";
|
||||
}
|
||||
String pPr = paraProps(grpprl);
|
||||
if (runs.length() == 0 && pPr.isEmpty()) {
|
||||
body.append("<w:p/>");
|
||||
return;
|
||||
if (p.runs().length() == 0 && props.isEmpty()) {
|
||||
return "<w:p/>";
|
||||
}
|
||||
body.append("<w:p>").append(pPr).append(runs).append("</w:p>");
|
||||
return "<w:p>" + (props.isEmpty() ? "" : "<w:pPr>" + props + "</w:pPr>")
|
||||
+ p.runs() + "</w:p>";
|
||||
}
|
||||
|
||||
private static boolean hasTtp(byte[] grpprl) {
|
||||
@@ -475,22 +751,56 @@ public final class DocToDocx {
|
||||
return xml.length() == 0 ? "" : "<w:rPr>" + xml + "</w:rPr>";
|
||||
}
|
||||
|
||||
/** pPr по CT_PPr: pageBreakBefore, ind, jc. */
|
||||
private String paraProps(byte[] grpprl) {
|
||||
/**
|
||||
* Дети pPr по CT_PPr (§17.3.1.26): pageBreakBefore, tabs, spacing, ind,
|
||||
* jc (обёртку {@code <w:pPr>} дописывает {@link #paraXml}).
|
||||
* Скан идёт по конкатенации цепочки стиля абзаца (base-first) и
|
||||
* прямых PAPX — порядок сохраняет last-wins: base → derived → direct.
|
||||
* Отступы накапливает общий {@link Grpprl.Indents} (80-варианты
|
||||
* dxaLeft/nest/right/left1 включительно; современное семейство
|
||||
* вытесняет 80-е — защитный tie-break, см. javadoc Indents).
|
||||
*/
|
||||
private String paraProps(int istd, byte[] direct) {
|
||||
byte[] grpprl = styles.papxChain(istd);
|
||||
grpprl = grpprl.length == 0 ? direct : concat(grpprl, direct);
|
||||
int[] jc = {-1};
|
||||
int[] left = {-1};
|
||||
int[] right = {-1};
|
||||
int[] left1 = {Integer.MIN_VALUE};
|
||||
boolean[] jc80 = {false};
|
||||
Grpprl.Indents ind = new Grpprl.Indents();
|
||||
int[] before = {-1};
|
||||
int[] after = {-1};
|
||||
int[] dyaLine = {Integer.MIN_VALUE};
|
||||
int[] fMult = {0};
|
||||
boolean[] pageBreak = {false};
|
||||
int[] ilvl = {0};
|
||||
int[] ilfo = {0};
|
||||
List<int[]> tabs = new ArrayList<>();
|
||||
Grpprl.scan(grpprl, 0, grpprl.length, (sprm, buf, off, len) -> {
|
||||
ind.prl(sprm, buf, off, len);
|
||||
switch (sprm) {
|
||||
case Grpprl.SPRM_P_JC80, Grpprl.SPRM_P_JC -> jc[0] =
|
||||
Grpprl.operandInt(buf, off, len);
|
||||
case Grpprl.SPRM_P_JC80 -> {
|
||||
jc[0] = Grpprl.operandInt(buf, off, len);
|
||||
jc80[0] = true;
|
||||
}
|
||||
case Grpprl.SPRM_P_JC -> {
|
||||
jc[0] = Grpprl.operandInt(buf, off, len);
|
||||
jc80[0] = false;
|
||||
}
|
||||
case Grpprl.SPRM_P_F_PAGE_BREAK_BEFORE -> pageBreak[0] =
|
||||
Grpprl.toggleOn(buf, off);
|
||||
case Grpprl.SPRM_P_DXA_LEFT -> left[0] = Grpprl.operandInt(buf, off, len);
|
||||
case Grpprl.SPRM_P_DXA_RIGHT -> right[0] = Grpprl.operandInt(buf, off, len);
|
||||
case Grpprl.SPRM_P_DXA_LEFT1 -> left1[0] = signedXas(buf, off, len);
|
||||
case Grpprl.SPRM_P_DYA_BEFORE -> before[0] =
|
||||
Grpprl.operandInt(buf, off, len);
|
||||
case Grpprl.SPRM_P_DYA_AFTER -> after[0] = Grpprl.operandInt(buf, off, len);
|
||||
case Grpprl.SPRM_P_DYA_LINE -> {
|
||||
if (len >= LSPD_OPERAND_LEN) {
|
||||
// LSPD (§2.9.181): dyaLine (i16) + fMultLinespace (i16)
|
||||
dyaLine[0] = signedXas(buf, off, 2);
|
||||
fMult[0] = Grpprl.operandInt(buf, off + 2, 2);
|
||||
}
|
||||
}
|
||||
case Grpprl.SPRM_P_CHG_TABS_PAPX -> applyTabs(tabs, buf, off, len, false);
|
||||
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);
|
||||
default -> { }
|
||||
}
|
||||
});
|
||||
@@ -498,38 +808,215 @@ public final class DocToDocx {
|
||||
if (pageBreak[0]) {
|
||||
xml.append("<w:pageBreakBefore/>");
|
||||
}
|
||||
boolean hasInd = left[0] > 0 || right[0] > 0
|
||||
|| (left1[0] != Integer.MIN_VALUE && left1[0] != 0);
|
||||
// numPr — после pageBreakBefore, до tabs (CT_PPr, §17.3.1.26)
|
||||
xml.append(numPrXml(ilfo[0], ilvl[0]));
|
||||
String tabsEl = tabsXml(tabs);
|
||||
if (!tabsEl.isEmpty()) {
|
||||
xml.append(tabsEl);
|
||||
}
|
||||
StringBuilder spacing = new StringBuilder();
|
||||
if (before[0] > 0) {
|
||||
spacing.append(" w:before=\"").append(before[0]).append('"');
|
||||
}
|
||||
if (after[0] > 0) {
|
||||
spacing.append(" w:after=\"").append(after[0]).append('"');
|
||||
}
|
||||
if (dyaLine[0] != Integer.MIN_VALUE && dyaLine[0] != 0) {
|
||||
// LSPD → w:spacing (§2.9.181): fMult=1 — множитель в 240-х
|
||||
// (lineRule="auto"); fMult=0, dyaLine>0 — «не меньше» (atLeast,
|
||||
// max(dyaLine, одиночный интервал)); dyaLine<0 — точная высота
|
||||
// (exact, |dyaLine|). См. grfhicPapx.fSuppressTopSpacingMac5 /
|
||||
// fExactOnTop ([MS-DOC] §2.4.6, отсылки к lineRule).
|
||||
if (fMult[0] == FMULT_MULTIPLIER) {
|
||||
spacing.append(" w:line=\"").append(dyaLine[0])
|
||||
.append("\" w:lineRule=\"auto\"");
|
||||
} else if (dyaLine[0] > 0) {
|
||||
spacing.append(" w:line=\"").append(dyaLine[0])
|
||||
.append("\" w:lineRule=\"atLeast\"");
|
||||
} else {
|
||||
spacing.append(" w:line=\"").append(-dyaLine[0])
|
||||
.append("\" w:lineRule=\"exact\"");
|
||||
}
|
||||
}
|
||||
if (spacing.length() > 0) {
|
||||
xml.append("<w:spacing").append(spacing).append("/>");
|
||||
}
|
||||
int left = ind.left();
|
||||
int right = ind.right();
|
||||
int left1 = ind.left1();
|
||||
boolean hasInd = left > 0 || right > 0
|
||||
|| (left1 != Integer.MIN_VALUE && left1 != 0);
|
||||
if (hasInd) {
|
||||
xml.append("<w:ind");
|
||||
if (left[0] > 0) {
|
||||
xml.append(" w:left=\"").append(left[0]).append('"');
|
||||
if (left > 0) {
|
||||
xml.append(" w:left=\"").append(left).append('"');
|
||||
}
|
||||
if (right[0] > 0) {
|
||||
xml.append(" w:right=\"").append(right[0]).append('"');
|
||||
if (right > 0) {
|
||||
xml.append(" w:right=\"").append(right).append('"');
|
||||
}
|
||||
if (left1[0] != Integer.MIN_VALUE && left1[0] != 0) {
|
||||
// sprmPDxaLeft1 — отступ первой строки ОТНОСИТЕЛЬНО остального
|
||||
if (left1 != Integer.MIN_VALUE && left1 != 0) {
|
||||
// sprmPDxaLeft1/…80 — отступ первой строки ОТНОСИТЕЛЬНО остального
|
||||
// абзаца (XAS со знаком): >0 выступ (firstLine), <0 висющий
|
||||
if (left1[0] > 0) {
|
||||
xml.append(" w:firstLine=\"").append(left1[0]).append('"');
|
||||
if (left1 > 0) {
|
||||
xml.append(" w:firstLine=\"").append(left1).append('"');
|
||||
} else {
|
||||
xml.append(" w:hanging=\"").append(-left1[0]).append('"');
|
||||
xml.append(" w:hanging=\"").append(-left1).append('"');
|
||||
}
|
||||
}
|
||||
xml.append("/>");
|
||||
}
|
||||
String jcVal = switch (jc[0]) {
|
||||
case 1 -> "center";
|
||||
case 2 -> "right";
|
||||
case 3 -> "both";
|
||||
case 4 -> "distribute";
|
||||
default -> null;
|
||||
};
|
||||
// sprmPJc80 (§2.6.2): 3/4/5 — все «justify to both right and
|
||||
// left», разница только в компрессии → both (distribute у jc80
|
||||
// нет; FOP и так рендерит distribute как left — терять нечего)
|
||||
String jcVal = jc80[0]
|
||||
? switch (jc[0]) {
|
||||
case 1 -> "center";
|
||||
case 2 -> "right";
|
||||
case 3, 4, 5 -> "both";
|
||||
default -> null; // 0 — left
|
||||
}
|
||||
: switch (jc[0]) {
|
||||
case 1 -> "center";
|
||||
case 2 -> "right";
|
||||
case 3 -> "both";
|
||||
case 4 -> "distribute"; // ST_Jc §17.18.44
|
||||
// 5/7/8/9 — неарабская семантика (§2.6.2) → both;
|
||||
// 6 (тайский distribute) — игнор
|
||||
case 5, 7, 8, 9 -> "both";
|
||||
default -> null; // 0 — left
|
||||
};
|
||||
if (jcVal != null) {
|
||||
xml.append("<w:jc w:val=\"").append(jcVal).append("\"/>");
|
||||
}
|
||||
return xml.length() == 0 ? "" : "<w:pPr>" + xml + "</w:pPr>";
|
||||
return xml.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* w:numPr по sprmPIlfo/sprmPIlvl (§2.6.2): ilfo 1..0x07FE — 1-базированный
|
||||
* индекс в rgLfo; отрицательный (0xF802..0xFFFF) — тот же список с
|
||||
* сохранением отступов абзаца (numId = −ilfo, прямой w:ind абзаца делает
|
||||
* это сам); 0/0xF801 — списока нет (в т.ч. снятие списочного стиля
|
||||
* прямым свойством — last-wins скана); ilvl 0x0C — «пропустить, не
|
||||
* нумеровать»; ilvl вне 0..8 — деградация без numPr. numId обязан
|
||||
* разрешаться в валидный abstractNum ({@link Lists#hasNum}).
|
||||
*/
|
||||
private String numPrXml(int ilfo, int ilvl) {
|
||||
int numId = 0;
|
||||
if (ilfo >= 1 && ilfo <= 0x07FE) {
|
||||
numId = ilfo;
|
||||
} else if (ilfo < 0 && ilfo >= -0x07FE) {
|
||||
numId = -ilfo;
|
||||
}
|
||||
if (numId == 0 || ilvl == 0x0C || ilvl > 8 || !lists.hasNum(numId)) {
|
||||
return "";
|
||||
}
|
||||
return "<w:numPr><w:ilvl w:val=\"" + ilvl + "\"/><w:numId w:val=\""
|
||||
+ numId + "\"/></w:numPr>";
|
||||
}
|
||||
|
||||
/**
|
||||
* Операнд смены табуляций. Две раскладки (§2.6.2):
|
||||
* {@code close == false} — PChgTabsPapxOperand (§2.9.183,
|
||||
* sprmPChgTabsPapx 0xC60D): cb(1) + PChgTabsDel{cTabs(1)+n×XAS}
|
||||
* + PChgTabsAdd{cTabs(1)+m×XAS+m×TBD};
|
||||
* {@code close == true} — PChgTabsOperand (§2.9.182, sprmPChgTabs
|
||||
* 0xC615): после rgdxaDel идёт ещё rgdxaClose{n×XAS_plusOne} —
|
||||
* радиус удаления каждого таба (XAS_plusOne: расстояние =
|
||||
* хранимое − 1, меньше 0x19 трактуется как 0x19 = 25).
|
||||
* Добавленные табы накапливаются в порядке скана (цепочка стиля →
|
||||
* direct); позиция из Del вырезает ранее накопленный таб в пределах
|
||||
* радиуса (§2.9.183 «within 25 twips» для Papx-варианта). Битый
|
||||
* операнд — молчаливый пропуск (контракт сканеров).
|
||||
* Регрессия — DocToDocxFormattingTest#styleTabsChg_reachesFooterPart,
|
||||
* #styleTabsChgDel_removesStop; длина 0xFF-операнда —
|
||||
* GrpprlTest#scan_pChgTabsSentinel_lengthByFormula.
|
||||
*/
|
||||
private static void applyTabs(List<int[]> tabs, byte[] buf, int off, int len,
|
||||
boolean close) {
|
||||
int p = off + 1;
|
||||
int end = off + len;
|
||||
if (p >= end) {
|
||||
return;
|
||||
}
|
||||
int del = buf[p++] & 0xFF;
|
||||
int closeStart = p + 2 * del;
|
||||
if (closeStart > end || (close && closeStart + 2 * del > end)) {
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < del; i++) {
|
||||
int pos = signedXas(buf, p, 2);
|
||||
p += 2;
|
||||
int radius = 25;
|
||||
if (close) {
|
||||
// XAS_plusOne (§2.9.182): фактическое расстояние =stored − 1
|
||||
int stored = signedXas(buf, closeStart + 2 * i, 2) - 1;
|
||||
radius = Math.max(25, stored);
|
||||
}
|
||||
final int r = radius;
|
||||
tabs.removeIf(t -> Math.abs(t[0] - pos) <= r);
|
||||
}
|
||||
// Papx-вариант (§2.9.183) идёт сразу к cTabsAdd; close-вариант
|
||||
// (§2.9.182) пропускает массив rgdxaClose
|
||||
p = close ? closeStart + 2 * del : closeStart;
|
||||
if (p >= end) {
|
||||
return;
|
||||
}
|
||||
int add = buf[p++] & 0xFF;
|
||||
if (add > (end - p) / 3) {
|
||||
return;
|
||||
}
|
||||
int[] pos = new int[add];
|
||||
for (int i = 0; i < add; i++) {
|
||||
pos[i] = signedXas(buf, p, 2);
|
||||
p += 2;
|
||||
}
|
||||
for (int i = 0; i < add; i++) {
|
||||
int tbd = buf[p++] & 0xFF;
|
||||
tabs.add(new int[] {pos[i], tbd & 0x7, (tbd >>> 3) & 0x7});
|
||||
}
|
||||
}
|
||||
|
||||
/** w:tabs: TBD.jc → ST_TabVal (§17.18.78), TBD.tlc → ST_Leader (§17.18.57). */
|
||||
private static String tabsXml(List<int[]> tabs) {
|
||||
StringBuilder inner = new StringBuilder();
|
||||
for (int[] t : tabs) {
|
||||
String val = switch (t[1]) {
|
||||
case 0 -> "left";
|
||||
case 1 -> "center";
|
||||
case 2 -> "right";
|
||||
case 3 -> "decimal";
|
||||
case 4 -> "bar";
|
||||
default -> null; // jcList/bar-прочее — вне контура
|
||||
};
|
||||
if (val == null) {
|
||||
continue;
|
||||
}
|
||||
inner.append("<w:tab w:val=\"").append(val).append('"');
|
||||
String leader = switch (t[2]) {
|
||||
case 1 -> "dot";
|
||||
case 2 -> "hyphen";
|
||||
case 3 -> "underscore";
|
||||
default -> null;
|
||||
};
|
||||
if (leader != null) {
|
||||
inner.append(" w:leader=\"").append(leader).append('"');
|
||||
}
|
||||
inner.append(" w:pos=\"").append(t[0]).append("\"/>");
|
||||
}
|
||||
return inner.length() == 0 ? "" : "<w:tabs>" + inner + "</w:tabs>";
|
||||
}
|
||||
|
||||
private static byte[] concat(byte[] a, byte[] b) {
|
||||
if (a.length == 0) {
|
||||
return b;
|
||||
}
|
||||
if (b.length == 0) {
|
||||
return a;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/** XAS-операнд со знаком (§2.6.2): 2-байтовый отрицательный — старший бит. */
|
||||
@@ -551,7 +1038,19 @@ public final class DocToDocx {
|
||||
buf[off + 2] & 0xFF);
|
||||
}
|
||||
|
||||
private static String sectPr(Sections s, String headerRelId, String footerRelId) {
|
||||
/**
|
||||
* w:sectPr секции: ссылки на части колонтитуков (null — элемент не
|
||||
* пишется, docx4j наследует полосы предыдущей секции), затем w:type,
|
||||
* затем pgSz/pgMar её геометрии. Порядок детей — CT_SectPr:
|
||||
* EG_HdrFtrReferences → type → pgSz → pgMar (ECMA-376 §17.2.3).
|
||||
*
|
||||
* @param typeContinuous разрыв ПЕРЕД секцией не начинает новую
|
||||
* страницу (§17.6.22 — w:type описывает
|
||||
* предыдущий разрыв; источник — sprmSBkc
|
||||
* предыдущей секции, [MS-DOC] §2.6.3)
|
||||
*/
|
||||
private static String sectPrXml(Sections.Section s, String headerRelId,
|
||||
String footerRelId, boolean typeContinuous) {
|
||||
StringBuilder xml = new StringBuilder("<w:sectPr>");
|
||||
// EG_HdrFtrReferences — до содержимого секции (CT_SectPr, ECMA-376 §17.2.3)
|
||||
if (headerRelId != null) {
|
||||
@@ -562,6 +1061,9 @@ public final class DocToDocx {
|
||||
xml.append("<w:footerReference w:type=\"default\" r:id=\"")
|
||||
.append(footerRelId).append("\"/>");
|
||||
}
|
||||
if (typeContinuous) {
|
||||
xml.append("<w:type w:val=\"continuous\"/>");
|
||||
}
|
||||
xml.append("<w:pgSz w:w=\"").append(s.pageWidth()).append("\" w:h=\"")
|
||||
.append(s.pageHeight())
|
||||
.append("\"/><w:pgMar w:top=\"").append(s.marginTop())
|
||||
|
||||
@@ -43,18 +43,23 @@ final class FibHeader {
|
||||
private static final int OFF_BLOB = 154;
|
||||
|
||||
/** Индексы пар (fc,lcb) в FibRgFcLcb97 (§2.5.6, порядок полей). */
|
||||
private static final int PAIR_STSHF = 1;
|
||||
private static final int PAIR_PLCF_SED = 6;
|
||||
private static final int PAIR_PLCF_HDD = 11;
|
||||
private static final int PAIR_PLCF_BTE_CHPX = 12;
|
||||
private static final int PAIR_PLCF_BTE_PAPX = 13;
|
||||
private static final int PAIR_STTBF_FFN = 15;
|
||||
private static final int PAIR_CLX = 33;
|
||||
private static final int PAIR_PLF_LST = 73;
|
||||
private static final int PAIR_PLF_LFO = 74;
|
||||
|
||||
private final int ccpText;
|
||||
private final int ccpFtn;
|
||||
private final int ccpHdd;
|
||||
private final int cbMac;
|
||||
private final boolean use1Table;
|
||||
private final long fcStshf;
|
||||
private final long lcbStshf;
|
||||
private final long fcPlcfSed;
|
||||
private final long lcbPlcfSed;
|
||||
private final long fcPlcfHdd;
|
||||
@@ -67,6 +72,10 @@ final class FibHeader {
|
||||
private final long lcbSttbfFfn;
|
||||
private final long fcClx;
|
||||
private final long lcbClx;
|
||||
private final long fcPlfLst;
|
||||
private final long lcbPlfLst;
|
||||
private final long fcPlfLfo;
|
||||
private final long lcbPlfLfo;
|
||||
|
||||
private FibHeader(byte[] wd) {
|
||||
int wIdent = (int) CfbReader.u32(wd, OFF_W_IDENT) & 0xFFFF;
|
||||
@@ -97,6 +106,9 @@ final class FibHeader {
|
||||
if (cbRgFcLcb <= PAIR_CLX) {
|
||||
throw new ValidationException("Устаревшая структура FIB в .doc");
|
||||
}
|
||||
long[] stshf = pair(wd, PAIR_STSHF);
|
||||
fcStshf = stshf[0];
|
||||
lcbStshf = stshf[1];
|
||||
long[] sed = pair(wd, PAIR_PLCF_SED);
|
||||
fcPlcfSed = sed[0];
|
||||
lcbPlcfSed = sed[1];
|
||||
@@ -115,6 +127,12 @@ final class FibHeader {
|
||||
long[] clx = pair(wd, PAIR_CLX);
|
||||
fcClx = clx[0];
|
||||
lcbClx = clx[1];
|
||||
long[] lst = pair(wd, PAIR_PLF_LST);
|
||||
fcPlfLst = lst[0];
|
||||
lcbPlfLst = lst[1];
|
||||
long[] lfo = pair(wd, PAIR_PLF_LFO);
|
||||
fcPlfLfo = lfo[0];
|
||||
lcbPlfLfo = lfo[1];
|
||||
}
|
||||
|
||||
/** Точка входа: разбор WordDocument-потока. */
|
||||
@@ -158,6 +176,15 @@ final class FibHeader {
|
||||
return use1Table;
|
||||
}
|
||||
|
||||
/** Смещение STSH в табличном потоке (§2.5.6 fcStshf); lcb=0 — стилей нет. */
|
||||
long fcStshf() {
|
||||
return fcStshf;
|
||||
}
|
||||
|
||||
long lcbStshf() {
|
||||
return lcbStshf;
|
||||
}
|
||||
|
||||
long fcPlcfSed() {
|
||||
return fcPlcfSed;
|
||||
}
|
||||
@@ -205,4 +232,22 @@ final class FibHeader {
|
||||
long lcbClx() {
|
||||
return lcbClx;
|
||||
}
|
||||
|
||||
/** Смещение PlfLst в табличном потоке (§2.5.6 fcPlfLst); lcb=0 — списков нет. */
|
||||
long fcPlfLst() {
|
||||
return fcPlfLst;
|
||||
}
|
||||
|
||||
long lcbPlfLst() {
|
||||
return lcbPlfLst;
|
||||
}
|
||||
|
||||
/** Смещение PlfLfo (§2.5.6 fcPlfLfo); lcb=0 — fcPlfLfo не определён (§2.5.6). */
|
||||
long fcPlfLfo() {
|
||||
return fcPlfLfo;
|
||||
}
|
||||
|
||||
long lcbPlfLfo() {
|
||||
return lcbPlfLfo;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,15 +36,74 @@ final class Grpprl {
|
||||
static final int SPRM_C_PIC_LOCATION = 0x6A03;
|
||||
|
||||
// Paragraph Properties (§2.6.2, sgc 1)
|
||||
static final int SPRM_P_ISTD = 0x4600;
|
||||
static final int SPRM_P_JC80 = 0x2403;
|
||||
static final int SPRM_P_F_PAGE_BREAK_BEFORE = 0x2407;
|
||||
static final int SPRM_P_F_IN_TABLE = 0x2416;
|
||||
static final int SPRM_P_F_TTP = 0x2417;
|
||||
static final int SPRM_P_DYA_LINE = 0x6412;
|
||||
static final int SPRM_P_DYA_BEFORE = 0xA413;
|
||||
static final int SPRM_P_DYA_AFTER = 0xA414;
|
||||
static final int SPRM_P_JC = 0x2461;
|
||||
static final int SPRM_P_DXA_RIGHT = 0x845D;
|
||||
static final int SPRM_P_DXA_LEFT = 0x845E;
|
||||
static final int SPRM_P_DXA_LEFT1 = 0x8460;
|
||||
/**
|
||||
* 80-варианты отступов (§2.6.2, все XAS 2 Б): sprmPDxaRight80,
|
||||
* sprmPDxaLeft80, sprmPNest80, sprmPDxaLeft180 и современный sprmPNest —
|
||||
* документы со старым происхождением несут только их; накопление —
|
||||
* {@link Indents}.
|
||||
*/
|
||||
static final int SPRM_P_DXA_RIGHT80 = 0x840E;
|
||||
static final int SPRM_P_DXA_LEFT80 = 0x840F;
|
||||
static final int SPRM_P_NEST80 = 0x4610;
|
||||
static final int SPRM_P_DXA_LEFT180 = 0x8411;
|
||||
static final int SPRM_P_NEST = 0x465F;
|
||||
/**
|
||||
* sprmPChgTabsPapx (§2.6.2, переменный): PChgTabsPapxOperand (§2.9.183) —
|
||||
* кастомные табы абзаца. Значение 0xC60D — по таблице §2.6.2
|
||||
* (sgc 1 = PAP); 0xD60D был бы sgc 5.
|
||||
*/
|
||||
static final int SPRM_P_CHG_TABS_PAPX = 0xC60D;
|
||||
/**
|
||||
* sprmPChgTabs (§2.6.2, переменный): PChgTabsOperand (§2.9.182) — тот же
|
||||
* смысл, но с спец-семантикой cb=0xFF; в PAPX Word пишет 0xC60D, здесь
|
||||
* только корректный пропуск (в §2.9.182 длина при cb=0xFF считается по
|
||||
* формуле — операнд помечен как «MAY be ignored», разбор обрывается).
|
||||
*/
|
||||
static final int SPRM_P_CHG_TABS = 0xC615;
|
||||
/**
|
||||
* sprmPIlvl (§2.6.2, 1 байт): уровень списка 0..8; 0x0C — «пропустить,
|
||||
* не нумеровать». Игнорируется, если абзац не в списке (sprmPIlfo=0).
|
||||
*/
|
||||
static final int SPRM_P_ILVL = 0x260A;
|
||||
/**
|
||||
* sprmPIlfo (§2.6.2, 2 байта, i16): 0/0xF801 — абзац не в списке;
|
||||
* 1..0x07FE — 1-базированный индекс в PlfLfo.rgLfo; 0xF802..0xFFFF —
|
||||
* отрицание индекса (список тот же, отступы абзаца сохраняются).
|
||||
*/
|
||||
static final int SPRM_P_ILFO = 0x460B;
|
||||
|
||||
// Section Properties (§2.6.3, sgc 4)
|
||||
// Table Properties (§2.6.3, sgc 5)
|
||||
static final int SPRM_T_TABLE_BORDERS_80 = 0xD605;
|
||||
static final int SPRM_T_DEF_TABLE = 0xD608;
|
||||
static final int SPRM_T_TABLE_BORDERS = 0xD613;
|
||||
/**
|
||||
* sprmTJc (§2.6.3, 2 байта, u16): логическое выравнивание таблицы
|
||||
* 0 = logical left, 1 = center, 2 = logical right (по умолчанию left).
|
||||
* В LTR совпадает с физическим sprmTJc90; FOP complex-script не
|
||||
* поддерживает (RTL вне контура репозитория) → единый маппинг.
|
||||
*/
|
||||
static final int SPRM_T_JC = 0x548A;
|
||||
/**
|
||||
* sprmTJc90 (§2.6.3, 2 байта, u16): физическое выравнивание таблицы
|
||||
* (Word 6/95): 0 = physical left, 1 = center, 2 = physical right.
|
||||
* Отличается от логического sprmTJc только в RTL/bidi (вне контура) →
|
||||
* единый маппинг.
|
||||
*/
|
||||
static final int SPRM_T_JC90 = 0x5400;
|
||||
|
||||
// Section Properties (§2.6.4, sgc 4)
|
||||
static final int SPRM_S_DYA_HDR_TOP = 0xB017;
|
||||
static final int SPRM_S_DYA_HDR_BOTTOM = 0xB018;
|
||||
static final int SPRM_S_XA_PAGE = 0xB01F;
|
||||
@@ -55,6 +114,74 @@ final class Grpprl {
|
||||
static final int SPRM_S_DYA_BOTTOM = 0x9024;
|
||||
static final int SPRM_S_BKC = 0x3009;
|
||||
|
||||
/**
|
||||
* Накопитель абзацных отступов PAPX (§2.6.2) — общий для
|
||||
* {@code DocxBody.paraProps} и {@code Lists.indXml} (grpprlPapx уровня).
|
||||
*
|
||||
* <p>Два семейства: современное (sprmPDxaLeft + sprmPNest) и 80-е
|
||||
* (sprmPDxaLeft80 + sprmPNest80); nest прибавляется к СВОЕМУ dxaLeft.
|
||||
* Если в grpprl встретился хоть один современный sprm левого отступа,
|
||||
* 80-е семейство вытесняется целиком (защитный tie-break для смешанных
|
||||
* PAPX: реальные документы несут одно семейство, sprmPNest supersede'ит
|
||||
* sprmPNest80 внутри этого правила). right и left1 — слияние last-wins:
|
||||
* 80-й и современный варианты имеют одинаковый смысл (правое поле;
|
||||
* отступ первой строки относительно абзаца), побеждает последний Prl.</p>
|
||||
*/
|
||||
static final class Indents {
|
||||
private int left;
|
||||
private int nest;
|
||||
private boolean modern;
|
||||
private int left80;
|
||||
private int nest80;
|
||||
private int right = -1;
|
||||
private int left1 = Integer.MIN_VALUE;
|
||||
|
||||
/** Кормить каждым Prl скана PAPX; не-отступные sprm игнорируются. */
|
||||
void prl(int sprm, byte[] buf, int off, int len) {
|
||||
switch (sprm) {
|
||||
case SPRM_P_DXA_LEFT -> {
|
||||
modern = true;
|
||||
left = operandInt(buf, off, len);
|
||||
}
|
||||
case SPRM_P_NEST -> {
|
||||
modern = true;
|
||||
nest = operandInt(buf, off, len);
|
||||
}
|
||||
case SPRM_P_DXA_LEFT80 -> left80 = operandInt(buf, off, len);
|
||||
case SPRM_P_NEST80 -> nest80 = operandInt(buf, off, len);
|
||||
case SPRM_P_DXA_RIGHT, SPRM_P_DXA_RIGHT80 ->
|
||||
right = operandInt(buf, off, len);
|
||||
case SPRM_P_DXA_LEFT1, SPRM_P_DXA_LEFT180 ->
|
||||
left1 = signedXas(buf, off, len);
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
|
||||
/** Итоговый w:left: dxaLeft + nest победившего семейства. */
|
||||
int left() {
|
||||
return modern ? left + nest : left80 + nest80;
|
||||
}
|
||||
|
||||
/** w:right; −1 — не задан. */
|
||||
int right() {
|
||||
return right;
|
||||
}
|
||||
|
||||
/** XAS со знаком; {@code Integer.MIN_VALUE} — не задан. */
|
||||
int left1() {
|
||||
return left1;
|
||||
}
|
||||
|
||||
/** XAS-операнд со знаком (§2.6.2), приём DocxBody/Tables. */
|
||||
private static int signedXas(byte[] buf, int off, int len) {
|
||||
int v = operandInt(buf, off, len);
|
||||
if (len == 2 && (v & 0x8000) != 0) {
|
||||
v -= 0x10000;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
||||
/** Вызывается на каждый Prl в порядке следования (last-wins у вызывающего). */
|
||||
interface PrlSink {
|
||||
/**
|
||||
@@ -108,6 +235,35 @@ final class Grpprl {
|
||||
if (p >= end) {
|
||||
return -1;
|
||||
}
|
||||
if (sprm == SPRM_T_DEF_TABLE) {
|
||||
// TDefTableOperand (§2.9.321): cb (2 байта) = «размер
|
||||
// остатка + 1» → весь операнд = cb + 1. Формула
|
||||
// «1 + первый байт» совпадает только при cb < 256.
|
||||
if (p + 2 > end) {
|
||||
return -1;
|
||||
}
|
||||
int cb = (buf[p] & 0xFF) | ((buf[p + 1] & 0xFF) << 8);
|
||||
if (cb < 2 || p + cb + 1 > end) {
|
||||
return -1;
|
||||
}
|
||||
return cb + 1;
|
||||
}
|
||||
if (sprm == SPRM_P_CHG_TABS && (buf[p] & 0xFF) == 0xFF) {
|
||||
// PChgTabsOperand (§2.9.182): cb=0xFF — длина по раскладке
|
||||
// cb(1) + cTabsDel(1) + rgdxaDel(2n) + rgdxaClose(2n)
|
||||
// + cTabsAdd(1) + rgdxaAdd(2m) + rgtbdAdd(m) = 3 + 4n + 3m.
|
||||
// Обрыв (−1) — только если cTabsAdd не читается: иначе
|
||||
// смещение разбора съедало бы следующие Prl.
|
||||
if (p + 2 > end) {
|
||||
return -1;
|
||||
}
|
||||
int n = buf[p + 1] & 0xFF;
|
||||
if (p + 2 + 4 * n + 1 > end) {
|
||||
return -1;
|
||||
}
|
||||
int m = buf[p + 2 + 4 * n] & 0xFF;
|
||||
return 3 + 4 * n + 3 * m;
|
||||
}
|
||||
return 1 + (buf[p] & 0xFF);
|
||||
}
|
||||
default:
|
||||
|
||||
@@ -13,15 +13,29 @@ import ru.pjandro.wordpdf.ValidationException;
|
||||
* расчёт не входит. Каждая история заканчивается guard-абзацем (¶), который
|
||||
* в вывод не попадает.</p>
|
||||
*
|
||||
* <p>В перенос идут odd header/footer секции 0 как {@code type="default"} —
|
||||
* FOP не различает чётные/нечётные страницы, а {@code titlePg} (первая
|
||||
* страница) в первом инкременте не поддерживается.</p>
|
||||
* <p>В перенос идут odd header/footer каждой секции как {@code type="default"}
|
||||
* — FOP не различает чётные/нечётные страницы, а {@code titlePg} (первая
|
||||
* страница) не поддерживается. История с {@code cpStart == cpEnd} не
|
||||
* определена — часть и ссылка не эмитятся, docx4j наследует полосы
|
||||
* предыдущей секции (§2.4.4 «Same as Previous»).</p>
|
||||
*/
|
||||
final class Headers {
|
||||
|
||||
/** CP-диапазон одной истории [cpStart, cpEnd); последний ¶ — guard-абзац. */
|
||||
record Story(int cpStart, int cpEnd) {
|
||||
|
||||
/**
|
||||
* История НЕ определена (§2.4.4: «Stories are considered empty if
|
||||
* they have no contents and no guard paragraph mark … the beginning
|
||||
* CP being the same as the next CP») — Word показывает полосы
|
||||
* предыдущей секции (Same as Previous). Пустая часть с guard-¶ при
|
||||
* этом НЕ empty(): это явно пустой колонтитул, обрывающий
|
||||
* наследование.
|
||||
*/
|
||||
boolean empty() {
|
||||
return cpStart == cpEnd;
|
||||
}
|
||||
|
||||
/** Есть ли содержимое за пределами guard-абзаца. */
|
||||
boolean hasContent() {
|
||||
return cpEnd - cpStart > 1;
|
||||
|
||||
@@ -0,0 +1,437 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Списки [MS-DOC]: PlfLst (§2.9.201) с приложенным массивом LVL (§2.9.149) →
|
||||
* {@code w:abstractNum}, PlfLfo (§2.9.200) с LFO (§2.9.131)/LFOData
|
||||
* (§2.9.132)/LFOLVL (§2.9.133) → {@code w:num} с {@code w:lvlOverride}.
|
||||
* Результат — {@code word/numbering.xml} формы Word (эталон —
|
||||
* samples/symbol-bullets.docx); порядок дочерних {@code w:lvl} — CT_Lvl
|
||||
* (ECMA-376 Part 1, wml.xsd): start, numFmt, suff, lvlText, lvlJc, pPr, rPr.
|
||||
*
|
||||
* <p>Раскладки (выверены по §3 «Example of a List»): PlfLst — cLst SHORT
|
||||
* (2 Б) при {@code fcPlfLst}, rgLstf начинается с {@code fcPlfLst+2}
|
||||
* (§2.9.201, Figure 56); LSTF (28 Б, §2.9.147) —
|
||||
* lsid(4)+tplc(4)+rgistdPara(18)+флаги(1: bit0 fSimpleList)+grfhic(1);
|
||||
* LVL = LVLF (28 Б, §2.9.150: iStartAt u32, nfc u8, jc 2 бита+флаги,
|
||||
* rgbxchNums 9, ixchFollow u8@15, cbGrpprlChpx u8@24, cbGrpprlPapx u8@25) +
|
||||
* grpprlPapx + grpprlChpx + Xst (§2.9.353: cch u16 + cch×u16, символы
|
||||
* 0x0000–0x0008 — плейсхолдеры уровней 0–8). Массив LVL приложен прямо за
|
||||
* {@code fcPlfLst+lcbPlfLst} (lcb его НЕ включает); каждому LSTF достаётся
|
||||
* 1 LVL при fSimpleList=1, иначе 9, порядок LSTF. LFO (16 Б) —
|
||||
* lsid(4)+unused(8)+clfolvl u8@12+…; rgLfoData — параллельный массив
|
||||
* LFOData{cp(4)+clfolvl×LFOLVL}; LFOLVL = iStartAt(4) + битполе (iLvl
|
||||
* биты 0–3, fStartAt бит 4, fFormatting бит 5) + LVL при fFormatting=1.</p>
|
||||
*
|
||||
* <p>MSONFC (§2.9.150 nfc) → ST_NumberFormat (§17.18.59) по [MS-OSHARED]
|
||||
* §2.2.1.3; экзотика (CJK, тайские и т.п.) → {@code decimal}: в бандле нет
|
||||
* шрифтов с такими глифами, формат всё равно не отрисовать. Семантика
|
||||
* рестартов (fNoRestart/ilvlRestartLim → {@code w:lvlRestart}), fLegal,
|
||||
* dxaIndentSav и LfoData.cp не переносятся — осознанный остаток моста.</p>
|
||||
*
|
||||
* <p>Разбор снисходительный (образец {@link Styles}): битая/отсутствующая
|
||||
* таблица или обрыв LVL — пустой/неполный результат без
|
||||
* {@link ru.pjandro.wordpdf.ValidationException}; абзацы со ссылкой на
|
||||
* несуществующий список деградируют в плоские.</p>
|
||||
*/
|
||||
final class Lists {
|
||||
|
||||
/** LSTF: lsid(4)+tplc(4)+rgistdPara(18)+флаги(1)+grfhic(1), §2.9.147. */
|
||||
private static final int LSTF_SIZE = 28;
|
||||
/** LVLF, §2.9.150. */
|
||||
private static final int LVLF_SIZE = 28;
|
||||
/** LFO, §2.9.131. */
|
||||
private static final int LFO_SIZE = 16;
|
||||
/** Число LVL у многоуровневого LSTF (§2.5.6 fcPlfLst). */
|
||||
private static final int LEVEL_COUNT = 9;
|
||||
/** Защита от враждебного cch в Xst (реальные xst — единицы символов). */
|
||||
private static final int MAX_XST_CHARS = 1024;
|
||||
/** Верхняя граница значения плейсхолдера уровня в xst (уровни 0–8, §2.9.149). */
|
||||
private static final char PLACEHOLDER_MAX = 0x08;
|
||||
/** Литеральный «%» в lvlText удваивается (lvlText, §17.9.11). */
|
||||
private static final char PERCENT = '%';
|
||||
/** Защита от враждебного lstfMac/lfoMac. */
|
||||
private static final int MAX_ENTRIES = 65536;
|
||||
|
||||
/** Один LVL (§2.9.149): поля LVLF + сырые grpprl + строка xst. */
|
||||
private record Level(int startAt, int nfc, int jc, int follow, byte[] papx, byte[] chpx,
|
||||
String xst) {
|
||||
}
|
||||
|
||||
/** LSTF (§2.9.147) с его LVL (1 или 9; null-элемент — обрыв разбора). */
|
||||
private record Lstf(int lsid, Level[] levels) {
|
||||
}
|
||||
|
||||
/** LFOLVL (§2.9.133): переопределение start-at и/или полный LVL. */
|
||||
private record LfoLvl(int ilvl, int startAt, boolean startAtOverride, Level formatting) {
|
||||
}
|
||||
|
||||
/** LFO (§2.9.131) + rgLfoLvl параллельного LFOData (§2.9.132). */
|
||||
private record Lfo(int lsid, LfoLvl[] overrides) {
|
||||
}
|
||||
|
||||
private final Lstf[] lstfs;
|
||||
/** Индекс = ilfo−1 (sprmPIlfo — 1-базированный индекс в rgLfo). */
|
||||
private final Lfo[] lfos;
|
||||
/** lsid → индекс ПЕРВОГО LSTF с таким lsid. */
|
||||
private final Map<Integer, Integer> lstfByLsid = new HashMap<>();
|
||||
private final FontTable fonts;
|
||||
|
||||
private Lists(Lstf[] lstfs, Lfo[] lfos, FontTable fonts) {
|
||||
this.lstfs = lstfs;
|
||||
this.lfos = lfos;
|
||||
this.fonts = fonts;
|
||||
for (int i = 0; i < lstfs.length; i++) {
|
||||
if (lstfs[i] != null) {
|
||||
lstfByLsid.putIfAbsent(lstfs[i].lsid(), i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Таблицы списков из табличного потока; битые/нулевые lcb → пустой результат. */
|
||||
static Lists read(byte[] table, long fcPlfLst, long lcbPlfLst, long fcPlfLfo,
|
||||
long lcbPlfLfo, FontTable fonts) {
|
||||
return new Lists(readPlfLst(table, fcPlfLst, lcbPlfLst),
|
||||
readPlfLfo(table, fcPlfLfo, lcbPlfLfo), fonts);
|
||||
}
|
||||
|
||||
/** Есть ≥1 валидный abstractNum → есть смысл писать numbering-часть. */
|
||||
boolean hasNumbering() {
|
||||
for (Lstf lstf : lstfs) {
|
||||
if (isValid(lstf)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** numId (1-базированный ilfo) разрешается в валидный abstractNum. */
|
||||
boolean hasNum(int numId) {
|
||||
return numId >= 1 && numId <= lfos.length && abstractIdOf(numId - 1) >= 0;
|
||||
}
|
||||
|
||||
/** numbering.xml целиком (с XML-декларацией), форма Word. */
|
||||
String numberingXml() {
|
||||
StringBuilder xml = new StringBuilder(
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>")
|
||||
.append("<w:numbering xmlns:w=\"http://schemas.openxmlformats.org")
|
||||
.append("/wordprocessingml/2006/main\">");
|
||||
for (int i = 0; i < lstfs.length; i++) {
|
||||
if (!isValid(lstfs[i])) {
|
||||
continue;
|
||||
}
|
||||
xml.append("<w:abstractNum w:abstractNumId=\"").append(i + 1).append("\">");
|
||||
Level[] levels = lstfs[i].levels();
|
||||
for (int j = 0; j < levels.length; j++) {
|
||||
if (levels[j] != null) {
|
||||
xml.append(lvlXml(j, levels[j]));
|
||||
}
|
||||
}
|
||||
xml.append("</w:abstractNum>");
|
||||
}
|
||||
for (int i = 0; i < lfos.length; i++) {
|
||||
int abstractId = abstractIdOf(i);
|
||||
if (abstractId < 0) {
|
||||
continue;
|
||||
}
|
||||
xml.append("<w:num w:numId=\"").append(i + 1).append("\">")
|
||||
.append("<w:abstractNumId w:val=\"").append(abstractId).append("\"/>");
|
||||
for (LfoLvl o : lfos[i].overrides()) {
|
||||
if (o == null || o.ilvl() > 8) {
|
||||
continue;
|
||||
}
|
||||
xml.append("<w:lvlOverride w:ilvl=\"").append(o.ilvl()).append("\">");
|
||||
if (o.formatting() != null) {
|
||||
xml.append(lvlXml(o.ilvl(), o.formatting()));
|
||||
} else if (o.startAtOverride()) {
|
||||
xml.append("<w:startOverride w:val=\"").append(o.startAt()).append("\"/>");
|
||||
}
|
||||
xml.append("</w:lvlOverride>");
|
||||
}
|
||||
xml.append("</w:num>");
|
||||
}
|
||||
return xml.append("</w:numbering>").toString();
|
||||
}
|
||||
|
||||
/** abstractNumId (1-базированный индекс LSTF) для LFO; −1 — нет валидного. */
|
||||
private int abstractIdOf(int lfoIndex) {
|
||||
// lfos[·] всегда непустой: readPlfLfo присваивает out[i] до обхода LFOData
|
||||
Integer lstfIndex = lstfByLsid.get(lfos[lfoIndex].lsid());
|
||||
if (lstfIndex == null || !isValid(lstfs[lstfIndex])) {
|
||||
return -1;
|
||||
}
|
||||
return lstfIndex + 1;
|
||||
}
|
||||
|
||||
private static boolean isValid(Lstf lstf) {
|
||||
return lstf != null && lstf.levels().length > 0 && lstf.levels()[0] != null;
|
||||
}
|
||||
|
||||
// --- разбор PlfLst ---------------------------------------------------
|
||||
|
||||
private static Lstf[] readPlfLst(byte[] table, long fc, long lcb) {
|
||||
if (lcb <= 0 || fc < 0 || fc + 4 > table.length) {
|
||||
return new Lstf[0];
|
||||
}
|
||||
long end = Math.min(fc + lcb, table.length);
|
||||
// cLst — SHORT (§2.9.201): знаковое прочтение; ≥ 0x8000 → отрицательное
|
||||
// (битое) → ветка mac <= 0
|
||||
int mac = (short) CfbReader.u16(table, (int) fc);
|
||||
if (mac <= 0) {
|
||||
return new Lstf[0];
|
||||
}
|
||||
int fit = (int) ((end - fc - 2) / LSTF_SIZE);
|
||||
mac = Math.min(Math.min(mac, fit), MAX_ENTRIES);
|
||||
Lstf[] out = new Lstf[mac];
|
||||
// массив LVL приложен за PlfLst (lcb его не включает, §2.5.6)
|
||||
int cursor = (int) Math.min(fc + lcb, (long) table.length);
|
||||
for (int i = 0; i < mac; i++) {
|
||||
int rec = (int) fc + 2 + i * LSTF_SIZE;
|
||||
int lsid = (int) CfbReader.u32(table, rec);
|
||||
boolean simple = (table[rec + 26] & 1) != 0;
|
||||
Level[] levels = new Level[simple ? 1 : LEVEL_COUNT];
|
||||
for (int j = 0; j < levels.length; j++) {
|
||||
Level lv = readLevel(table, cursor);
|
||||
if (lv == null) {
|
||||
// обрыв: этот LSTF — с разобранными уровнями, остальные — без
|
||||
out[i] = new Lstf(lsid, levels);
|
||||
return out;
|
||||
}
|
||||
levels[j] = lv;
|
||||
cursor += levelSize(lv);
|
||||
}
|
||||
out[i] = new Lstf(lsid, levels);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** LVL по {@code at}; null — поля за пределами потока. */
|
||||
private static Level readLevel(byte[] table, int at) {
|
||||
if (at < 0 || at + LVLF_SIZE > table.length) {
|
||||
return null;
|
||||
}
|
||||
int startAt = (int) CfbReader.u32(table, at);
|
||||
int nfc = table[at + 4] & 0xFF;
|
||||
int jc = table[at + 5] & 0x03;
|
||||
int follow = table[at + 15] & 0xFF;
|
||||
int cbChpx = table[at + 24] & 0xFF;
|
||||
int cbPapx = table[at + 25] & 0xFF;
|
||||
int p = at + LVLF_SIZE;
|
||||
if (p + cbPapx + cbChpx > table.length) {
|
||||
return null;
|
||||
}
|
||||
byte[] papx = slice(table, p, cbPapx);
|
||||
p += cbPapx;
|
||||
byte[] chpx = slice(table, p, cbChpx);
|
||||
p += cbChpx;
|
||||
if (p + 2 > table.length) {
|
||||
return null;
|
||||
}
|
||||
int cch = CfbReader.u16(table, p);
|
||||
p += 2;
|
||||
if (cch > MAX_XST_CHARS || p + 2 * cch > table.length) {
|
||||
return null;
|
||||
}
|
||||
String xst = new String(table, p, 2 * cch, StandardCharsets.UTF_16LE);
|
||||
return new Level(startAt, nfc, jc, follow, papx, chpx, xst);
|
||||
}
|
||||
|
||||
/** Полный размер LVL: LVLF + grpprl'ы + Xst (cch + символы). */
|
||||
private static int levelSize(Level lv) {
|
||||
return LVLF_SIZE + lv.papx().length + lv.chpx().length + 2 + lv.xst().length() * 2;
|
||||
}
|
||||
|
||||
// --- разбор PlfLfo ---------------------------------------------------
|
||||
|
||||
private static Lfo[] readPlfLfo(byte[] table, long fc, long lcb) {
|
||||
// lcbPlfLfo=0 → fcPlfLfo не определён и MUST быть проигнорирован (§2.5.6)
|
||||
if (lcb <= 0 || fc < 0 || fc + 4 > table.length) {
|
||||
return new Lfo[0];
|
||||
}
|
||||
long end = Math.min(fc + lcb, table.length);
|
||||
int mac = (int) CfbReader.u32(table, (int) fc);
|
||||
if (mac <= 0) {
|
||||
return new Lfo[0];
|
||||
}
|
||||
int fit = (int) ((end - fc - 4) / LFO_SIZE);
|
||||
mac = Math.min(Math.min(mac, fit), MAX_ENTRIES);
|
||||
Lfo[] out = new Lfo[mac];
|
||||
int cursor = (int) (fc + 4) + mac * LFO_SIZE;
|
||||
for (int i = 0; i < mac; i++) {
|
||||
int rec = (int) fc + 4 + i * LFO_SIZE;
|
||||
int lsid = (int) CfbReader.u32(table, rec);
|
||||
int clfolvl = table[rec + 12] & 0xFF;
|
||||
LfoLvl[] overrides = new LfoLvl[clfolvl];
|
||||
out[i] = new Lfo(lsid, overrides);
|
||||
if (cursor + 4 > table.length) {
|
||||
return out; // обрыв LFOData — остаток без переопределений
|
||||
}
|
||||
cursor += 4; // cp — не переносится (осознанный остаток)
|
||||
for (int j = 0; j < clfolvl; j++) {
|
||||
if (cursor + 8 > table.length) {
|
||||
return out;
|
||||
}
|
||||
int startAt = (int) CfbReader.u32(table, cursor);
|
||||
int bits = (int) CfbReader.u32(table, cursor + 4);
|
||||
cursor += 8;
|
||||
int ilvl = bits & 0xF;
|
||||
boolean fStartAt = (bits >>> 4 & 1) != 0;
|
||||
boolean fFormatting = (bits >>> 5 & 1) != 0;
|
||||
Level formatting = null;
|
||||
if (fFormatting) {
|
||||
formatting = readLevel(table, cursor);
|
||||
if (formatting == null) {
|
||||
return out;
|
||||
}
|
||||
cursor += levelSize(formatting);
|
||||
}
|
||||
overrides[j] = new LfoLvl(ilvl, startAt, fStartAt, formatting);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// --- эмит numbering.xml ------------------------------------------------
|
||||
|
||||
/** w:lvl по CT_Lvl: start, numFmt, suff, lvlText, lvlJc, pPr, rPr. */
|
||||
private String lvlXml(int ilvl, Level lv) {
|
||||
StringBuilder xml = new StringBuilder("<w:lvl w:ilvl=\"").append(ilvl).append("\">");
|
||||
xml.append("<w:start w:val=\"").append(Math.max(lv.startAt(), 0)).append("\"/>");
|
||||
xml.append("<w:numFmt w:val=\"").append(numFmt(lv.nfc())).append("\"/>");
|
||||
String suff = switch (lv.follow()) {
|
||||
case 1 -> "space";
|
||||
case 2 -> "nothing";
|
||||
default -> null; // 0 = tab — дефолт ST_LvlSuff, не эмитится
|
||||
};
|
||||
if (suff != null) {
|
||||
xml.append("<w:suff w:val=\"").append(suff).append("\"/>");
|
||||
}
|
||||
xml.append("<w:lvlText w:val=\"").append(escapeAttr(lvlText(lv.xst()))).append("\"/>");
|
||||
String jc = switch (lv.jc()) {
|
||||
case 1 -> "center";
|
||||
case 2 -> "right";
|
||||
default -> "left";
|
||||
};
|
||||
xml.append("<w:lvlJc w:val=\"").append(jc).append("\"/>");
|
||||
String ind = indXml(lv.papx());
|
||||
if (!ind.isEmpty()) {
|
||||
xml.append("<w:pPr>").append(ind).append("</w:pPr>");
|
||||
}
|
||||
String rPr = rPrXml(lv.chpx());
|
||||
if (!rPr.isEmpty()) {
|
||||
xml.append("<w:rPr>").append(rPr).append("</w:rPr>");
|
||||
}
|
||||
return xml.append("</w:lvl>").toString();
|
||||
}
|
||||
|
||||
/** xst → ST_NumberText: плейсхолдеры 0x00–0x08 → %{n+1}, «%» → «%%». */
|
||||
private static String lvlText(String xst) {
|
||||
StringBuilder out = new StringBuilder(xst.length() + 8);
|
||||
for (int i = 0; i < xst.length(); i++) {
|
||||
char ch = xst.charAt(i);
|
||||
if (ch <= PLACEHOLDER_MAX) {
|
||||
out.append(PERCENT).append(ch + 1);
|
||||
} else if (ch == PERCENT) {
|
||||
out.append("%%");
|
||||
} else {
|
||||
out.append(ch);
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/** MSONFC ([MS-OSHARED] §2.2.1.3) → ST_NumberFormat (§17.18.59). */
|
||||
private static String numFmt(int nfc) {
|
||||
return switch (nfc) {
|
||||
case 0x00 -> "decimal";
|
||||
case 0x01 -> "upperRoman";
|
||||
case 0x02 -> "lowerRoman";
|
||||
case 0x03 -> "upperLetter";
|
||||
case 0x04 -> "lowerLetter";
|
||||
case 0x05 -> "ordinal";
|
||||
case 0x06 -> "cardinalText";
|
||||
case 0x07 -> "ordinalText";
|
||||
case 0x16 -> "decimalZero";
|
||||
case 0x17 -> "bullet";
|
||||
case 0x39 -> "numberInDash";
|
||||
case 0x3A -> "russianLower";
|
||||
case 0x3B -> "russianUpper";
|
||||
case 0xFF -> "none";
|
||||
// экзотика (CJK/тайские/индийские…): в бандле нет шрифтов с такими
|
||||
// глифами — decimal хотя бы читается
|
||||
default -> "decimal";
|
||||
};
|
||||
}
|
||||
|
||||
/** w:ind уровня из grpprlPapx (общий накопитель {@link Grpprl.Indents},
|
||||
* те же XAS-семантики и 80-варианты, что paraProps). */
|
||||
private static String indXml(byte[] papx) {
|
||||
Grpprl.Indents ind = new Grpprl.Indents();
|
||||
Grpprl.scan(papx, 0, papx.length, ind::prl);
|
||||
int left = ind.left();
|
||||
int left1 = ind.left1();
|
||||
StringBuilder xml = new StringBuilder();
|
||||
if (left > 0) {
|
||||
xml.append(" w:left=\"").append(left).append('"');
|
||||
}
|
||||
if (left1 != Integer.MIN_VALUE && left1 != 0) {
|
||||
if (left1 > 0) {
|
||||
xml.append(" w:firstLine=\"").append(left1).append('"');
|
||||
} else {
|
||||
xml.append(" w:hanging=\"").append(-left1).append('"');
|
||||
}
|
||||
}
|
||||
return xml.length() == 0 ? "" : "<w:ind" + xml + "/>";
|
||||
}
|
||||
|
||||
/** w:rPr метки уровня из grpprlChpx: rFonts (Symbol/Wingdings-буллеты), b, sz. */
|
||||
private String rPrXml(byte[] chpx) {
|
||||
int[] ftc0 = {-1};
|
||||
boolean[] bold = {false};
|
||||
int[] hps = {0};
|
||||
Grpprl.scan(chpx, 0, chpx.length, (sprm, buf, off, len) -> {
|
||||
switch (sprm) {
|
||||
case Grpprl.SPRM_C_RG_FTC0 -> ftc0[0] = Grpprl.operandInt(buf, off, len);
|
||||
case Grpprl.SPRM_C_F_BOLD -> bold[0] = Grpprl.toggleOn(buf, off);
|
||||
case Grpprl.SPRM_C_HPS -> hps[0] = Grpprl.operandInt(buf, off, len);
|
||||
default -> { }
|
||||
}
|
||||
});
|
||||
StringBuilder xml = new StringBuilder();
|
||||
String family = ftc0[0] >= 0 ? fonts.font(ftc0[0]) : null;
|
||||
if (family != null) {
|
||||
xml.append("<w:rFonts w:ascii=\"").append(escapeAttr(family))
|
||||
.append("\" w:hAnsi=\"").append(escapeAttr(family)).append("\"/>");
|
||||
}
|
||||
if (bold[0]) {
|
||||
xml.append("<w:b/>");
|
||||
}
|
||||
if (hps[0] > 0) {
|
||||
xml.append("<w:sz w:val=\"").append(hps[0]).append("\"/>");
|
||||
}
|
||||
return xml.toString();
|
||||
}
|
||||
|
||||
private static String escapeAttr(String value) {
|
||||
StringBuilder out = new StringBuilder(value.length() + 8);
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
char ch = value.charAt(i);
|
||||
switch (ch) {
|
||||
case '&' -> out.append("&");
|
||||
case '<' -> out.append("<");
|
||||
case '"' -> out.append(""");
|
||||
default -> out.append(ch);
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static byte[] slice(byte[] src, int from, int len) {
|
||||
byte[] out = new byte[len];
|
||||
System.arraycopy(src, from, out, 0, len);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -16,13 +16,14 @@ import java.util.List;
|
||||
* умолчанию (ms-doc.md:5635). PapxInFkp (§2.9.175):
|
||||
* cb (1 байт); при cb≠0 GrpPrlAndIstd занимает 2×cb−1 байт, при cb=0 —
|
||||
* следующий байт cb' и 2×cb' байт; GrpPrlAndIstd = istd(2) + grpprl.
|
||||
* istd игнорируется (стили — вне контура первого инкремента).</p>
|
||||
* istd сохраняется ({@link #istdFor}) — по нему {@link DocxBody} применяет
|
||||
* цепочку стилей {@link Styles}.</p>
|
||||
*/
|
||||
final class PapxIndex {
|
||||
|
||||
private static final int FKP_PAGE_SIZE = 512;
|
||||
|
||||
private record Range(long fcStart, long fcEnd, byte[] grpprl) {
|
||||
private record Range(long fcStart, long fcEnd, byte[] grpprl, int istd) {
|
||||
}
|
||||
|
||||
private final List<Range> ranges = new ArrayList<>();
|
||||
@@ -62,12 +63,15 @@ final class PapxIndex {
|
||||
int stdStart = cb != 0 ? infkp + 1 : infkp + 2;
|
||||
int stdSize = cb != 0 ? 2 * cb - 1 : 2 * (wordDocument[infkp + 1] & 0xFF);
|
||||
int grpprlLen = stdSize - 2;
|
||||
if (grpprlLen <= 0 || stdStart + 2 + grpprlLen > pageOff + FKP_PAGE_SIZE) {
|
||||
// grpprlLen==0 допустим: istd без прямых Prl (стиль — единственное свойство)
|
||||
if (grpprlLen < 0 || stdStart + 2 + grpprlLen > pageOff + FKP_PAGE_SIZE) {
|
||||
continue;
|
||||
}
|
||||
byte[] grpprl = new byte[grpprlLen];
|
||||
System.arraycopy(wordDocument, stdStart + 2, grpprl, 0, grpprlLen);
|
||||
ranges.add(new Range(Math.max(rgfcStart, fcStart), Math.min(rgfcEnd, fcEnd), grpprl));
|
||||
int istd = CfbReader.u16(wordDocument, stdStart);
|
||||
ranges.add(new Range(Math.max(rgfcStart, fcStart), Math.min(rgfcEnd, fcEnd),
|
||||
grpprl, istd));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,6 +90,16 @@ final class PapxIndex {
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
/** istd абзаца, содержащего FC (§2.9.175 GrpPrlAndIstd); -1 — диапазона нет. */
|
||||
int istdFor(long fc) {
|
||||
for (Range r : ranges) {
|
||||
if (fc >= r.fcStart() && fc < r.fcEnd()) {
|
||||
return r.istd();
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Число абзацев с sprmPFPageBreakBefore=1 (для lightweight-подсчёта страниц). */
|
||||
int countPageBreakBefore() {
|
||||
int[] count = {0};
|
||||
|
||||
@@ -1,25 +1,49 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Свойства секций (.doc) → параметры полосы набора и поправка подсчёта страниц.
|
||||
* Свойства секций (.doc) → по-секционная полоса набора и поправка подсчёта
|
||||
* страниц.
|
||||
*
|
||||
* <p>[MS-DOC] §2.8.26 PlcfSed: PLC (aCP n+1, Sed n по 12 байт); Sed =
|
||||
* fn(2) + fcSepx(4) + fnMpr(2) + fcMpr(4); fcSepx — указатель на Sepx
|
||||
* (§2.9.245) в WordDocument-потоке: cb (2 байта) + grpprl секционных sprm;
|
||||
* Sepx секции i описывает секцию от aCP[i] до aCP[i+1] (§3, Figure 13).
|
||||
* Выходной документ односекционный: геометрию берёт последняя секция
|
||||
* (как {@code w:sectPr} уровня документа). Свойств нет — дефолты Word 97:
|
||||
* Letter 12240×15840, поля 1440, колонтитуки 720 (значения §2.6.3
|
||||
* «By default» для sprmSXaPage/sprmSYaPage).</p>
|
||||
* Sed секции i описывает секцию от aCP[i] до aCP[i+1] (§3, Figure 13: «The
|
||||
* last character in the first section is at position 10, and has a value of
|
||||
* 0x0C»). Дубликаты aCP запрещены (§2.8.26 «MUST NOT contain duplicate
|
||||
* CPs»); финальный aCP в реальных файлах Word лежит за ccpText (PLC
|
||||
* покрывает весь текстовый поток), поэтому конец последней секции
|
||||
* клампится к ccpText. Свойств в Sepx нет (или Sepx битый) — дефолты
|
||||
* Word 97: Letter 12240×15840, поля 1440, колонтитуки
|
||||
* 720 (значения §2.6.3 «By default» для sprmSXaPage/sprmSYaPage).</p>
|
||||
*
|
||||
* <p>{@link Section#continuous()} — sprmSBkc секции со значением
|
||||
* bkcContinuous/bkcNewColumn (§2.6.3, SBkcOperand: «the type of the section
|
||||
* break that terminates the section»), т.е. разрыв, ЗАКАНЧИВАЮЩИЙ эту
|
||||
* секцию. В OOXML {@code w:type} описывает разрыв ПЕРЕД секцией (§17.6.22),
|
||||
* поэтому {@code w:type} секции i берётся из {@code continuous()} секции
|
||||
* i−1 — см. {@code DocxBody#sectPrXml}.</p>
|
||||
*
|
||||
* <p>{@link #continuousSectionEnds()} — число межсекционных разрывов, не
|
||||
* начинающих новую страницу (sprmSBkc = bkcContinuous/bkcNewColumn, §2.6.3;
|
||||
* дефолт — bkcNewPage, поэтому отсутствие sprmSBkc не вычитается).</p>
|
||||
* начинающих новую страницу (дефолт — bkcNewPage, поэтому отсутствие
|
||||
* sprmSBkc не вычитается).</p>
|
||||
*/
|
||||
final class Sections {
|
||||
|
||||
/**
|
||||
* Одна секция: CP-диапазон [cpStart, cpEnd) (у всех, кроме последней,
|
||||
* финальный символ — 0x0C, §2.8.26) + геометрия из её Sepx + признак
|
||||
* «разрыв, заканчивающий секцию, не начинает новую страницу».
|
||||
*/
|
||||
record Section(int cpStart, int cpEnd, int pageWidth, int pageHeight,
|
||||
int marginLeft, int marginRight, int marginTop, int marginBottom,
|
||||
int header, int footer, boolean continuous) {
|
||||
}
|
||||
|
||||
/** Дефолты Word 97 (§2.6.3, twips). */
|
||||
private static final int DEFAULT_PAGE_WIDTH = 12240;
|
||||
private static final int DEFAULT_PAGE_HEIGHT = 15840;
|
||||
@@ -29,105 +53,158 @@ final class Sections {
|
||||
private static final int SED_SIZE = 12;
|
||||
private static final int SED_OFF_FC_SEPX = 2;
|
||||
|
||||
private int pageWidth = DEFAULT_PAGE_WIDTH;
|
||||
private int pageHeight = DEFAULT_PAGE_HEIGHT;
|
||||
private int marginLeft = DEFAULT_MARGIN;
|
||||
private int marginRight = DEFAULT_MARGIN;
|
||||
private int marginTop = DEFAULT_MARGIN;
|
||||
private int marginBottom = DEFAULT_MARGIN;
|
||||
private int header = DEFAULT_HEADER_FOOTER;
|
||||
private int footer = DEFAULT_HEADER_FOOTER;
|
||||
private int continuousEnds;
|
||||
private final List<Section> sections;
|
||||
private final int continuousEnds;
|
||||
|
||||
private Sections(byte[] tableStream, long fcSed, long lcbSed, byte[] wordDocument) {
|
||||
/** Геометрия одной секции в процессе разбора Sepx (дефолты Word 97). */
|
||||
private static final class SedGeom {
|
||||
private int pageWidth = DEFAULT_PAGE_WIDTH;
|
||||
private int pageHeight = DEFAULT_PAGE_HEIGHT;
|
||||
private int marginLeft = DEFAULT_MARGIN;
|
||||
private int marginRight = DEFAULT_MARGIN;
|
||||
private int marginTop = DEFAULT_MARGIN;
|
||||
private int marginBottom = DEFAULT_MARGIN;
|
||||
private int header = DEFAULT_HEADER_FOOTER;
|
||||
private int footer = DEFAULT_HEADER_FOOTER;
|
||||
private boolean continuous;
|
||||
|
||||
private void apply(int sprm, int value) {
|
||||
if (sprm == Grpprl.SPRM_S_XA_PAGE) {
|
||||
pageWidth = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_YA_PAGE) {
|
||||
pageHeight = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DXA_LEFT) {
|
||||
marginLeft = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DXA_RIGHT) {
|
||||
marginRight = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DYA_TOP) {
|
||||
marginTop = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DYA_BOTTOM) {
|
||||
marginBottom = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DYA_HDR_TOP) {
|
||||
header = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DYA_HDR_BOTTOM) {
|
||||
footer = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Sections(byte[] tableStream, long fcSed, long lcbSed, byte[] wordDocument,
|
||||
int ccpText) {
|
||||
if (lcbSed <= 0) {
|
||||
// нет PlcfSed — одна неявная секция [0, ccpText) с дефолтами
|
||||
sections = List.of(defaultSection(0, ccpText));
|
||||
continuousEnds = 0;
|
||||
return;
|
||||
}
|
||||
if (fcSed < 0 || fcSed + lcbSed > tableStream.length || (lcbSed - 4) % (4 + SED_SIZE) != 0) {
|
||||
if (fcSed < 0 || fcSed + lcbSed > tableStream.length
|
||||
|| (lcbSed - 4) % (4 + SED_SIZE) != 0) {
|
||||
throw new ValidationException("Битый PlcfSed в .doc");
|
||||
}
|
||||
int n = (int) ((lcbSed - 4) / (4 + SED_SIZE));
|
||||
int[] aCp = new int[n + 1];
|
||||
for (int i = 0; i <= n; i++) {
|
||||
long cp = CfbReader.u32(tableStream, (int) fcSed + i * 4);
|
||||
if (i > 0 && cp <= aCp[i - 1]) {
|
||||
throw new ValidationException("Невозрастающие aCP в PlcfSed .doc");
|
||||
}
|
||||
aCp[i] = (int) cp;
|
||||
}
|
||||
if (n == 0) {
|
||||
sections = List.of(defaultSection(0, ccpText));
|
||||
continuousEnds = 0;
|
||||
return;
|
||||
}
|
||||
int sedBase = (int) fcSed + (n + 1) * 4;
|
||||
List<Section> list = new ArrayList<>(n);
|
||||
int cont = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
SedGeom g = new SedGeom();
|
||||
long fcSepx = CfbReader.u32(tableStream, sedBase + i * SED_SIZE + SED_OFF_FC_SEPX);
|
||||
if (fcSepx == 0 || fcSepx + 2 > wordDocument.length) {
|
||||
continue;
|
||||
}
|
||||
int cb = (int) (CfbReader.u32(wordDocument, (int) fcSepx) & 0xFFFF);
|
||||
if (cb <= 0 || fcSepx + 2 + cb > wordDocument.length) {
|
||||
continue;
|
||||
}
|
||||
boolean last = i == n - 1;
|
||||
Grpprl.scan(wordDocument, (int) fcSepx + 2, cb, (sprm, buf, off, len) -> {
|
||||
int v = Grpprl.operandInt(buf, off, len);
|
||||
if (last) {
|
||||
applyGeometry(sprm, v);
|
||||
} else if (sprm == Grpprl.SPRM_S_BKC && v <= 1) {
|
||||
// bkcContinuous=0 / bkcNewColumn=1 (§2.6.3 SBkcOperand):
|
||||
// разрыв не начинает новую страницу
|
||||
continuousEnds++;
|
||||
if (fcSepx != 0 && fcSepx + 2 <= wordDocument.length) {
|
||||
int cb = (int) (CfbReader.u32(wordDocument, (int) fcSepx) & 0xFFFF);
|
||||
if (cb > 0 && fcSepx + 2 + cb <= wordDocument.length) {
|
||||
Grpprl.scan(wordDocument, (int) fcSepx + 2, cb, (sprm, buf, off, len) -> {
|
||||
int v = Grpprl.operandInt(buf, off, len);
|
||||
g.apply(sprm, v);
|
||||
// bkcContinuous=0 / bkcNewColumn=1 (§2.6.3 SBkcOperand):
|
||||
// разрыв, заканчивающий секцию, не начинает страницу
|
||||
if (sprm == Grpprl.SPRM_S_BKC && v <= 1) {
|
||||
g.continuous = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
if (i < n - 1 && g.continuous) {
|
||||
cont++;
|
||||
}
|
||||
// финальный aCP реальные файлы Word пишут за ccpText (page-numbers.doc:
|
||||
// aCp[1]=108 при ccpText=33 — PLC покрывает весь текстовый поток),
|
||||
// верхний guard невозможен; конец последней секции — ccpText
|
||||
int cpEnd = i == n - 1 ? Math.min(aCp[i + 1], ccpText) : aCp[i + 1];
|
||||
list.add(new Section(aCp[i], cpEnd, g.pageWidth, g.pageHeight,
|
||||
g.marginLeft, g.marginRight, g.marginTop, g.marginBottom,
|
||||
g.header, g.footer, g.continuous));
|
||||
}
|
||||
sections = List.copyOf(list);
|
||||
continuousEnds = cont;
|
||||
}
|
||||
|
||||
private void applyGeometry(int sprm, int value) {
|
||||
if (sprm == Grpprl.SPRM_S_XA_PAGE) {
|
||||
pageWidth = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_YA_PAGE) {
|
||||
pageHeight = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DXA_LEFT) {
|
||||
marginLeft = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DXA_RIGHT) {
|
||||
marginRight = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DYA_TOP) {
|
||||
marginTop = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DYA_BOTTOM) {
|
||||
marginBottom = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DYA_HDR_TOP) {
|
||||
header = value;
|
||||
} else if (sprm == Grpprl.SPRM_S_DYA_HDR_BOTTOM) {
|
||||
footer = value;
|
||||
}
|
||||
private static Section defaultSection(int cpStart, int cpEnd) {
|
||||
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);
|
||||
}
|
||||
|
||||
static Sections read(byte[] tableStream, long fcSed, long lcbSed, byte[] wordDocument) {
|
||||
return new Sections(tableStream, fcSed, lcbSed, wordDocument);
|
||||
static Sections read(byte[] tableStream, long fcSed, long lcbSed, byte[] wordDocument,
|
||||
int ccpText) {
|
||||
return new Sections(tableStream, fcSed, lcbSed, wordDocument, ccpText);
|
||||
}
|
||||
|
||||
/** Все секции по aCP PlcfSed; при отсутствии PlcfSed — одна неявная. */
|
||||
List<Section> list() {
|
||||
return sections;
|
||||
}
|
||||
|
||||
// Одиночные аксессоры — геометрия ПОСЛЕДНЕЙ секции (подсчёт страниц).
|
||||
|
||||
int pageWidth() {
|
||||
return pageWidth;
|
||||
return last().pageWidth();
|
||||
}
|
||||
|
||||
int pageHeight() {
|
||||
return pageHeight;
|
||||
return last().pageHeight();
|
||||
}
|
||||
|
||||
int marginLeft() {
|
||||
return marginLeft;
|
||||
return last().marginLeft();
|
||||
}
|
||||
|
||||
int marginRight() {
|
||||
return marginRight;
|
||||
return last().marginRight();
|
||||
}
|
||||
|
||||
int marginTop() {
|
||||
return marginTop;
|
||||
return last().marginTop();
|
||||
}
|
||||
|
||||
int marginBottom() {
|
||||
return marginBottom;
|
||||
return last().marginBottom();
|
||||
}
|
||||
|
||||
int header() {
|
||||
return header;
|
||||
return last().header();
|
||||
}
|
||||
|
||||
int footer() {
|
||||
return footer;
|
||||
return last().footer();
|
||||
}
|
||||
|
||||
int continuousSectionEnds() {
|
||||
return continuousEnds;
|
||||
}
|
||||
|
||||
private Section last() {
|
||||
return sections.get(sections.size() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
/**
|
||||
* Таблица стилей STSH ([MS-DOC] §2.9.271) и цепочки наследования
|
||||
* (§2.4.6.5 «Determining Properties of a Style»).
|
||||
*
|
||||
* <p>Разбор: LPStshi (cbStshi(2) + STSHI: cstd(2) + cbSTDBaseInFile(2),
|
||||
* §2.9.272/.274) → rglpstd со смещения {@code fc + 2 + cbStshi} (LPStd
|
||||
* хранятся на чётных границах, §2.9.207). Каждая LPStd: cbStd(2) + Std
|
||||
* (cbStd байт): stdf (cbSTDBaseInFile байт: StdfBase §2.9.260 — в первых
|
||||
* 4 байтах sti(12)|A–D(4)|stk(4)|istdBase(12), cupx — младший нибл байта 4)
|
||||
* + 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>
|
||||
*
|
||||
* <p>Цепочка свойств стиля — base-first: сначала grpprl предка по
|
||||
* istdBase (0x0FFF — без предка), затем собственный grpprl (шаг 8
|
||||
* «Determining Properties of a Style» в порядке применения last-wins:
|
||||
* производный стиль перекрывает базовый). istdBase обязан ссылаться на
|
||||
* непустой стиль и не создавать циклов (§2.9.260); глубина > 16 — обрыв
|
||||
* цепочки (защита от битого файла).</p>
|
||||
*
|
||||
* <p>Разбор снисходительный (образец {@link FontTable}): битый/отсутствующий
|
||||
* STSH не роняет конвертацию — документ рендерится на прямых свойствах,
|
||||
* {@link ValidationException} не бросается.</p>
|
||||
*/
|
||||
final class Styles {
|
||||
|
||||
/** stk абзацного стиля (§2.9.260). */
|
||||
private static final int STK_PARAGRAPH = 1;
|
||||
/** Индекс UpxPapx в Std абзацного стиля (§2.9.308). */
|
||||
private static final int UPX_PAPX = 0;
|
||||
/** Индекс UpxChpx в Std абзацного стиля (§2.9.309). */
|
||||
private static final int UPX_CHPX = 1;
|
||||
/** istdBase без предка (§2.9.260). */
|
||||
private static final int NO_BASE = 0x0FFF;
|
||||
/** Защита от цикла в istdBase. */
|
||||
private static final int MAX_CHAIN = 16;
|
||||
|
||||
/** Один стиль: предка + собственные grpprl'ы (пустые массивы — нет). */
|
||||
private record Style(int istdBase, byte[] papx, byte[] chpx) {
|
||||
}
|
||||
|
||||
private final Style[] styles;
|
||||
|
||||
private Styles(byte[] table, long fc, long lcb) {
|
||||
Style[] parsed;
|
||||
try {
|
||||
parsed = readAll(table, fc, lcb);
|
||||
} catch (RuntimeException broken) {
|
||||
parsed = new Style[0];
|
||||
}
|
||||
styles = parsed;
|
||||
}
|
||||
|
||||
private static Style[] readAll(byte[] table, long fc, long lcb) {
|
||||
if (lcb <= 0 || fc < 0 || fc + 6 > table.length) {
|
||||
return new Style[0];
|
||||
}
|
||||
int cbStshi = CfbReader.u16(table, (int) fc);
|
||||
int cstd = CfbReader.u16(table, (int) fc + 2);
|
||||
int cbStdf = CfbReader.u16(table, (int) fc + 4);
|
||||
if (cstd <= 0 || cstd >= 0x0FFE || cbStdf < 5 || cbStshi < 4) {
|
||||
return new Style[0];
|
||||
}
|
||||
int pos = (int) (fc + 2 + cbStshi);
|
||||
if ((pos & 1) != 0) {
|
||||
pos++;
|
||||
}
|
||||
int end = (int) (fc + lcb);
|
||||
Style[] out = new Style[cstd];
|
||||
for (int istd = 0; istd < cstd; istd++) {
|
||||
if (pos + 2 > end) {
|
||||
break;
|
||||
}
|
||||
int cbStd = CfbReader.u16(table, pos);
|
||||
pos += 2;
|
||||
if (cbStd <= 0) {
|
||||
continue; // пустой стиль (§2.9.271)
|
||||
}
|
||||
if (pos + cbStd > end) {
|
||||
break;
|
||||
}
|
||||
out[istd] = readStd(table, pos, cbStd, cbStdf);
|
||||
pos += cbStd;
|
||||
if ((pos & 1) != 0) {
|
||||
pos++; // LPStd на чётной границе, padding в cbStd не входит
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Std по {@code std}: stdf + xstzName + cupx × LPUpx. */
|
||||
private static Style readStd(byte[] table, int std, int cbStd, int cbStdf) {
|
||||
int stdEnd = std + cbStd;
|
||||
long base = CfbReader.u32(table, std);
|
||||
int stk = (int) ((base >>> 16) & 0xF);
|
||||
int istdBase = (int) ((base >>> 20) & 0xFFF);
|
||||
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]);
|
||||
}
|
||||
int cch = CfbReader.u16(table, p);
|
||||
p += 2 + 2 * cch + 2; // xstzName: cch + строка + chTerm (§2.9.348)
|
||||
byte[] papx = new byte[0];
|
||||
byte[] chpx = new byte[0];
|
||||
for (int i = 0; i < cupx && p + 2 <= stdEnd; i++) {
|
||||
int cbUpx = CfbReader.u16(table, p);
|
||||
p += 2;
|
||||
if (p + cbUpx > stdEnd) {
|
||||
break;
|
||||
}
|
||||
if (stk == STK_PARAGRAPH) {
|
||||
if (i == UPX_PAPX && cbUpx >= 2) {
|
||||
// UpxPapx: istd(2) + grpprlPapx (§2.9.345)
|
||||
papx = slice(table, p + 2, cbUpx - 2);
|
||||
} else if (i == UPX_CHPX) {
|
||||
chpx = slice(table, p, cbUpx); // UpxChpx (§2.9.343)
|
||||
}
|
||||
}
|
||||
p += cbUpx;
|
||||
if ((p & 1) != 0) {
|
||||
p++; // LPUpx выровнены на чёт, padding в cbUpx не входит
|
||||
}
|
||||
}
|
||||
return new Style(istdBase, papx, chpx);
|
||||
}
|
||||
|
||||
private static byte[] slice(byte[] src, int from, int len) {
|
||||
byte[] out = new byte[len];
|
||||
System.arraycopy(src, from, out, 0, len);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Таблица по {@code fcStshf} из табличного потока; битый STSH → пустая. */
|
||||
static Styles read(byte[] tableStream, long fc, long lcb) {
|
||||
return new Styles(tableStream, fc, lcb);
|
||||
}
|
||||
|
||||
/** Число стилей (для проверки границ istd из sprmPIstd). */
|
||||
int count() {
|
||||
return styles.length;
|
||||
}
|
||||
|
||||
/** Grpprl абзацных свойств стиля со всей цепочкой предков (base-first). */
|
||||
byte[] papxChain(int istd) {
|
||||
return chain(istd, true);
|
||||
}
|
||||
|
||||
/** Grpprl символьных свойств стиля со всей цепочкой предков (base-first). */
|
||||
byte[] chpxChain(int istd) {
|
||||
return chain(istd, false);
|
||||
}
|
||||
|
||||
private byte[] chain(int istd, boolean papx) {
|
||||
byte[] own = new byte[0];
|
||||
int depth = 0;
|
||||
while (istd >= 0 && istd < styles.length && styles[istd] != null && depth++ < MAX_CHAIN) {
|
||||
Style s = styles[istd];
|
||||
own = concat(papx ? s.papx() : s.chpx(), own);
|
||||
if (s.istdBase() == NO_BASE) {
|
||||
break;
|
||||
}
|
||||
istd = s.istdBase();
|
||||
}
|
||||
return own;
|
||||
}
|
||||
|
||||
private static byte[] concat(byte[] a, byte[] b) {
|
||||
if (a.length == 0) {
|
||||
return b;
|
||||
}
|
||||
if (b.length == 0) {
|
||||
return a;
|
||||
}
|
||||
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,228 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
/**
|
||||
* Разбор TAP (Table Properties) TTP-абзаца строки → сетка и границы таблицы.
|
||||
*
|
||||
* <p>[MS-DOC] §2.6.3: {@code sprmTDefTable} (0xD608) — TDefTableOperand
|
||||
* (§2.9.321): cb(2, «остаток+1») + NumberOfColumns(1, ≤63) + rgdxaCenter
|
||||
* ((ncols+1) × XAS со знаком: первый — левый край таблицы от поля, далее
|
||||
* правые края колонок) + rgTc80. Ширина колонки i = center[i+1] − center[i].
|
||||
* Границы строки: {@code sprmTTableBorders} (0xD613) — TableBordersOperand
|
||||
* (§2.9.302, cb=0x30, 6 × Brc по 8 байт: cv COLORREF + dptLineWidth +
|
||||
* brcType + флаги), иначе {@code sprmTTableBorders80} (0xD605) —
|
||||
* TableBordersOperand80 (§2.9.303, cb=0x18, 6 × Brc80 по 4 байта:
|
||||
* dptLineWidth + brcType + ico + флаги). Порядок Brc: top, left, bottom,
|
||||
* right, horizontalInside, verticalInside → w:top/w:left/w:bottom/w:right/
|
||||
* w:insideH/w:insideV (CT_TblBorders, ECMA-376 §17.4.40).</p>
|
||||
*
|
||||
* <p>brcType → ST_Border (§17.18.2) по таблице BrcType ([MS-DOC] §2.9.39,
|
||||
* колонка Reference); 0x00 — элемент не эмитится, нераспознанный — single.
|
||||
* w:sz = dptLineWidth (1/8 пункта, ECMA-376 §17.18.15; минимум 2; при
|
||||
* brcType ≥ 0x40 ширина в целых пунктах → ×8). Цвет: Brc.cv fAuto
|
||||
* (байт 3 = 0xFF) не эмитится, иначе RRGGBB; Brc80.ico — по таблице Ico
|
||||
* (§2.9.171); 0 = auto, > 0x10 — не эмитится.</p>
|
||||
*
|
||||
* <p>Вне контура (деградация {@code null} / молчаливый пропуск): вложенные
|
||||
* таблицы (sprmPFInnerTtp), объединённые ячейки (vertMerge, sprmTInsert),
|
||||
* отступы между ячейками (sprmTDxaCellSpacing), бордюры уровня ячейки
|
||||
* (TC80/sprmTCellBorders) — только строковые границы 0xD613/0xD605.</p>
|
||||
*/
|
||||
final class Tables {
|
||||
|
||||
/** brcType ≥ этого порога: dptLineWidth задан в целых пунктах (§2.9.38). */
|
||||
private static final int BRC_TYPE_POINT_UNITS = 0x40;
|
||||
/** Минимальный w:sz границы; значения Brc80 меньше эквивалентны 2 (§2.9.37). */
|
||||
private static final int MIN_BORDER_SZ = 2;
|
||||
|
||||
/** Минимум центров в TDefTable: ncols≥1 → centers[ncols+1]≥2 (§2.9.321). */
|
||||
private static final int MIN_CENTERS = 2;
|
||||
|
||||
/**
|
||||
* Сетка строки: ширины колонок, сдвиг от поля, XML границ (может быть
|
||||
* пустым), выравнивание таблицы ("center"/"right"; null = left → элемент
|
||||
* не эмитится).
|
||||
*/
|
||||
record Grid(int[] colWidths, int indent, String bordersXml, String tblJc) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Ico → RRGGBB ([MS-DOC] §2.9.171). Индекс = ico. 0 — auto (не эмитится).
|
||||
* В таблице спецификации строка 0x0D дублирует 0x0C (800080) — очевидная
|
||||
* опечатка документа: icoRedDark в палитре Word = 800000, взято значение
|
||||
* Word (иначе 0x0C и 0x0D неразличимы).
|
||||
*/
|
||||
private static final String[] ICO_COLORS = {
|
||||
null, // 0x00 auto
|
||||
"000000", // 1 black
|
||||
"0000FF", // 2 blue
|
||||
"00FFFF", // 3 teal
|
||||
"00FF00", // 4 green
|
||||
"FF00FF", // 5 magenta
|
||||
"FF0000", // 6 red
|
||||
"FFFF00", // 7 yellow
|
||||
"FFFFFF", // 8 white
|
||||
"000080", // 9 dark blue
|
||||
"008080", // 10 dark teal
|
||||
"008000", // 11 dark green
|
||||
"800080", // 12 dark magenta
|
||||
"800000", // 13 dark red
|
||||
"808000", // 14 dark yellow
|
||||
"808080", // 15 gray 50%
|
||||
"C0C0C0", // 16 gray 25%
|
||||
};
|
||||
|
||||
/**
|
||||
* Имена ST_Border по brcType (§2.9.39, колонка Reference); 0 — none.
|
||||
* package-private хук для юнита полного покрытия таблицы.
|
||||
*/
|
||||
static String borderVal(int brcType) {
|
||||
return switch (brcType) {
|
||||
case 0x01 -> "single";
|
||||
case 0x03 -> "double";
|
||||
case 0x06 -> "dotted";
|
||||
case 0x07 -> "dashed";
|
||||
case 0x08 -> "dotDash";
|
||||
case 0x09 -> "dotDotDash";
|
||||
case 0x0A -> "triple";
|
||||
case 0x0B -> "thinThickSmallGap";
|
||||
case 0x0C -> "thickThinSmallGap";
|
||||
case 0x0D -> "thinThickThinSmallGap";
|
||||
case 0x0E -> "thinThickMediumGap";
|
||||
case 0x0F -> "thickThinMediumGap";
|
||||
case 0x10 -> "thinThickThinMediumGap";
|
||||
case 0x11 -> "thinThickLargeGap";
|
||||
case 0x12 -> "thickThinLargeGap";
|
||||
case 0x13 -> "thinThickThinLargeGap";
|
||||
case 0x14 -> "wave";
|
||||
case 0x15 -> "doubleWave";
|
||||
case 0x16 -> "dashSmallGap";
|
||||
case 0x17 -> "dashDotStroked";
|
||||
case 0x18 -> "threeDEmboss";
|
||||
case 0x19 -> "threeDEngrave";
|
||||
case 0x1A, 0x1B -> "outset";
|
||||
default -> "single";
|
||||
};
|
||||
}
|
||||
|
||||
private Tables() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Сетка строки по TAP TTP-абзаца; {@code null} — сетку построить нельзя
|
||||
* (нет/битый sprmTDefTable, нулевая или неположительная ширина колонки) →
|
||||
* вызывающий деградирует в плоские абзацы.
|
||||
*/
|
||||
static Grid parse(byte[] tap) {
|
||||
int[][] centers = {new int[0]};
|
||||
String[] borders = {""};
|
||||
boolean[] d613Seen = {false};
|
||||
String[] jc = {null};
|
||||
boolean[] jcSeen = {false};
|
||||
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);
|
||||
} else if (sprm == Grpprl.SPRM_T_TABLE_BORDERS && len == 0x31) {
|
||||
borders[0] = readBorders(buf, off);
|
||||
d613Seen[0] = true;
|
||||
} else if (sprm == Grpprl.SPRM_T_TABLE_BORDERS_80 && len == 0x19
|
||||
&& !d613Seen[0]) {
|
||||
borders[0] = readBorders80(buf, off);
|
||||
} else if (sprm == Grpprl.SPRM_T_JC && len >= 2) {
|
||||
jc[0] = jcVal(Grpprl.operandInt(buf, off, len));
|
||||
jcSeen[0] = true;
|
||||
} else if (sprm == Grpprl.SPRM_T_JC90 && len >= 2 && !jcSeen[0]) {
|
||||
// тот же приоритет современного над 90-вариантом, что у границ
|
||||
jc[0] = jcVal(Grpprl.operandInt(buf, off, len));
|
||||
}
|
||||
});
|
||||
int[] c = centers[0];
|
||||
if (c.length < MIN_CENTERS) {
|
||||
return null;
|
||||
}
|
||||
int[] colWidths = new int[c.length - 1];
|
||||
for (int i = 0; i < colWidths.length; i++) {
|
||||
colWidths[i] = c[i + 1] - c[i];
|
||||
if (colWidths[i] <= 0) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return new Grid(colWidths, c[0], borders[0], jc[0]);
|
||||
}
|
||||
|
||||
/** sprmTJc/sprmTJc90 (§2.6.3): 1 → "center", 2 → "right", прочее (0/left) → null. */
|
||||
private static String jcVal(int v) {
|
||||
return v == 1 ? "center" : v == 2 ? "right" : null;
|
||||
}
|
||||
|
||||
/** TDefTableOperand → centers[ncols+1] (XAS со знаком) или пустой массив. */
|
||||
private static int[] readDefTable(byte[] buf, int off, int len) {
|
||||
int ncols = buf[off + 2] & 0xFF;
|
||||
if (ncols < 1 || ncols > 63 || len < 3 + 2 * (ncols + 1)) {
|
||||
return new int[0];
|
||||
}
|
||||
int[] centers = new int[ncols + 1];
|
||||
for (int i = 0; i <= ncols; i++) {
|
||||
centers[i] = signedXas(buf, off + 3 + 2 * i);
|
||||
}
|
||||
return centers;
|
||||
}
|
||||
|
||||
private static int signedXas(byte[] buf, int off) {
|
||||
int v = CfbReader.u16(buf, off);
|
||||
return (v & 0x8000) != 0 ? v - 0x10000 : v;
|
||||
}
|
||||
|
||||
/** 6 × Brc (8 байт, cv(4)+dptLineWidth+brcType+флаги(2)) → w:tblBorders. */
|
||||
private static String readBorders(byte[] buf, int off) {
|
||||
StringBuilder xml = new StringBuilder();
|
||||
String[] names = {"top", "left", "bottom", "right", "insideH", "insideV"};
|
||||
for (int i = 0; i < 6; i++) {
|
||||
int b = off + 1 + i * 8;
|
||||
// Brc (§2.9.36): cv(4: R,G,B,fAuto) + dptLineWidth(1) + brcType(1) + флаги(2)
|
||||
int type = buf[b + 5] & 0xFF;
|
||||
if (type == 0) {
|
||||
continue;
|
||||
}
|
||||
String color = (buf[b + 3] & 0xFF) == 0xFF
|
||||
? null
|
||||
: String.format("%02X%02X%02X", buf[b] & 0xFF, buf[b + 1] & 0xFF,
|
||||
buf[b + 2] & 0xFF);
|
||||
appendBorder(xml, names[i], type, buf[b + 4] & 0xFF, color);
|
||||
}
|
||||
return xml.length() == 0 ? "" : "<w:tblBorders>" + xml + "</w:tblBorders>";
|
||||
}
|
||||
|
||||
/** 6 × Brc80 (4 байта: dptLineWidth+brcType+ico+флаги) → w:tblBorders. */
|
||||
private static String readBorders80(byte[] buf, int off) {
|
||||
StringBuilder xml = new StringBuilder();
|
||||
String[] names = {"top", "left", "bottom", "right", "insideH", "insideV"};
|
||||
for (int i = 0; i < 6; i++) {
|
||||
int b = off + 1 + i * 4;
|
||||
int type = buf[b + 1] & 0xFF;
|
||||
if (type == 0) {
|
||||
continue;
|
||||
}
|
||||
int ico = buf[b + 2] & 0xFF;
|
||||
String color = ico < ICO_COLORS.length ? ICO_COLORS[ico] : null;
|
||||
appendBorder(xml, names[i], type, buf[b] & 0xFF, color);
|
||||
}
|
||||
return xml.length() == 0 ? "" : "<w:tblBorders>" + xml + "</w:tblBorders>";
|
||||
}
|
||||
|
||||
private static void appendBorder(StringBuilder xml, String name, int type,
|
||||
int dptLineWidth, String color) {
|
||||
int sz = dptLineWidth;
|
||||
if (type >= BRC_TYPE_POINT_UNITS) {
|
||||
sz *= 8; // ширина в целых пунктах (§2.9.38, таблица dptLineWidth)
|
||||
}
|
||||
if (sz < MIN_BORDER_SZ) {
|
||||
sz = MIN_BORDER_SZ; // Brc80: значения < 2 эквивалентны 2 (§2.9.37)
|
||||
}
|
||||
xml.append("<w:").append(name).append(" w:val=\"").append(borderVal(type))
|
||||
.append("\" w:sz=\"").append(sz).append('"');
|
||||
if (color != null) {
|
||||
xml.append(" w:color=\"").append(color).append('"');
|
||||
}
|
||||
xml.append("/>");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+108
-5
@@ -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)) {
|
||||
|
||||
+1018
-44
File diff suppressed because it is too large
Load Diff
@@ -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&imes <New> "Q"\""),
|
||||
"«>» в атрибуте легален и не экранируется: " + 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());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user