Мост .doc → .docx: конвертация бинарного Word 97-2003 (MS-DOC/MS-CFB/MS-OLEPS/MS-ODRAW)
- internal/doc: CfbReader, FibHeader, PieceTable, Grpprl, ChpxIndex, PapxIndex, Sections, FontTable, SummaryInfo, Headers, OfficeArt, DocFile, DocxWriter, DocToDocx — разбор бинарного .doc и сборка in-memory .docx (прямые свойства, колонтитуки с PAGE/NUMPAGES → fldSimple, BLIP-картинки PNG/JPEG/DIB) - роутинг WordPdfConverter по сигнатуре CFB; валидация страниц .doc по сырым байтам (SummaryInfo PageCount + 0x0C + pageBreakBefore) до конвертации - .docx/.doc: ConvertController, safeBaseName, фронт (DropZone accept) - фикстуры: 12 .doc (11 эталонов заказчика + doc-formats); doc-пары тестов - тесты: 13 классов internal/doc (98 @Test) + пары в конвертере/валидаторе/app; гейт mvn clean verify зелёный (core BRANCH 0.852, LINE 0.947) - AGENTS.md: секция «Мост .doc → .docx», обновлены счётчики и каталоги
This commit is contained in:
@@ -161,7 +161,20 @@ class WordPdfConverterTest {
|
||||
*/
|
||||
@Test
|
||||
void chartsSmartArt_drawingsBecomeImages() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("charts-smartart.docx"), "charts-smartart");
|
||||
assertDrawingsBecomeImages("charts-smartart.docx");
|
||||
}
|
||||
|
||||
/**
|
||||
* Тот же паритет для samples/charts-smartart.doc: BLIP'ы OfficeArt
|
||||
* извлекаются мостом в image-части, растров в PDF не меньше четырёх.
|
||||
*/
|
||||
@Test
|
||||
void chartsSmartArt_docDrawingsBecomeImages() throws Exception {
|
||||
assertDrawingsBecomeImages("charts-smartart.doc");
|
||||
}
|
||||
|
||||
private static void assertDrawingsBecomeImages(String fixture) throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes(fixture), baseName(fixture));
|
||||
|
||||
String text = norm(pdfText(pdf));
|
||||
assertTrue(text.contains("Диаграммы"), "пропал текст вокруг диаграмм: " + text);
|
||||
@@ -236,7 +249,21 @@ class WordPdfConverterTest {
|
||||
*/
|
||||
@Test
|
||||
void oleObjects_removedAndConverted() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("ole-embedded.docx"), "ole-embedded");
|
||||
assertOleObjectsRemoved("ole-embedded.docx");
|
||||
}
|
||||
|
||||
/**
|
||||
* samples/ole-embedded.doc: OLE-объект ([MS-DOC] U+0001 +
|
||||
* sprmCFOle2) не читается — мост берёт VML-плейсхолдер (BLIP по
|
||||
* {@code sprmCPicLocation}=0) и пишет штатной картинкой.
|
||||
*/
|
||||
@Test
|
||||
void oleObjects_docRemovedAndConverted() throws Exception {
|
||||
assertOleObjectsRemoved("ole-embedded.doc");
|
||||
}
|
||||
|
||||
private static void assertOleObjectsRemoved(String fixture) throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes(fixture), baseName(fixture));
|
||||
|
||||
String text = norm(pdfText(pdf));
|
||||
assertTrue(text.contains("OLE object test before"),
|
||||
@@ -251,6 +278,10 @@ class WordPdfConverterTest {
|
||||
/**
|
||||
* errorOnOle=true — {@link DrawingFoundException} с {@code Kind.OLE},
|
||||
* документ отвергается. Фикстура samples/ole-embedded.docx.
|
||||
*
|
||||
* <p>Флаг действует только на .docx: в бинарном .doc OLE-объект —
|
||||
* не часть, а форматирование U+0001, и мост деградирует его до
|
||||
* картинки-плейсхолдера (см. {@link #oleObjects_docRemovedAndConverted()}).</p>
|
||||
*/
|
||||
@Test
|
||||
void drawingErrors_errorFlagRejectsOle() throws Exception {
|
||||
@@ -296,25 +327,30 @@ class WordPdfConverterTest {
|
||||
*/
|
||||
@Test
|
||||
void exoticGlyphs_drawnNotHash() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("exotic-glyphs.docx"), "exotic-glyphs");
|
||||
assertExoticGlyphs("exotic-glyphs.docx");
|
||||
assertExoticGlyphs("exotic-glyphs.doc");
|
||||
}
|
||||
|
||||
private static void assertExoticGlyphs(String fixture) throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes(fixture), baseName(fixture));
|
||||
String text = norm(pdfText(pdf));
|
||||
|
||||
for (String ch : List.of("\u2152", "\u2181", "\u058D", "\u08E1")) {
|
||||
assertTrue(text.contains(ch), "нет символа U+"
|
||||
assertTrue(text.contains(ch), fixture + ": нет символа U+"
|
||||
+ Integer.toHexString(ch.charAt(0)) + ": " + text);
|
||||
}
|
||||
assertFalse(text.contains("#"),
|
||||
"в PDF остались .notdef-решётки: " + text);
|
||||
fixture + ": в PDF остались .notdef-решётки: " + text);
|
||||
|
||||
// Римская цифра — вшитым DejaVu Serif, а не базовым Helvetica
|
||||
assertTrue(fontNameOf(pdf, '\u2181').contains("DejaVuSerif"),
|
||||
"римская цифра нарисована не DejaVu Serif");
|
||||
fixture + ": римская цифра нарисована не DejaVu Serif");
|
||||
// Армянский знак Unicode 16 — Noto Sans Armenian
|
||||
assertTrue(fontNameOf(pdf, '\u058D').contains("NotoSansArmenian"),
|
||||
"армянский знак нарисован не Noto Sans Armenian");
|
||||
fixture + ": армянский знак нарисован не Noto Sans Armenian");
|
||||
// Соседний обычный текст не уехал в подставленное семейство
|
||||
assertTrue(fontNameOf(pdf, 'ы').contains("Tinos"),
|
||||
"кириллица уехала с Tinos");
|
||||
fixture + ": кириллица уехала с Tinos");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -326,26 +362,48 @@ class WordPdfConverterTest {
|
||||
*/
|
||||
@Test
|
||||
void pageNumbers_recomputedNotCached() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("page-numbers.docx"), "page-numbers");
|
||||
assertPageNumbers("page-numbers.docx");
|
||||
// .doc: колонтитуки с полями PAGE/NUMPAGES переносит мост (Headers +
|
||||
// fldSimple), кэш результата (2 / 11) в PDF не попадает
|
||||
assertPageNumbers("page-numbers.doc");
|
||||
}
|
||||
|
||||
for (int page = 1; page <= 3; page++) {
|
||||
private static void assertPageNumbers(String fixture) throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes(fixture), baseName(fixture));
|
||||
int pages;
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
pages = doc.getNumberOfPages();
|
||||
}
|
||||
assertTrue(pages >= 2, fixture + ": колонтитукам негде рендериться");
|
||||
for (int page = 1; page <= pages; page++) {
|
||||
String text = norm(pdfPageText(pdf, page));
|
||||
assertTrue(text.contains("Страница " + page),
|
||||
"страница " + page + " содержит не своё содержимое: " + text);
|
||||
assertTrue(text.contains(page + " / 3"),
|
||||
"колонтитул страницы " + page + " не пересчитан: " + text);
|
||||
fixture + ": страница " + page + " содержит не своё содержимое: " + text);
|
||||
assertTrue(text.contains(page + " / " + pages),
|
||||
fixture + ": колонтитул страницы " + page + " не пересчитан: " + text);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void ruPlain_cyrillicAndStyles() throws Exception {
|
||||
String text = norm(pdfText(convertPdf(sampleBytes("ru-plain.docx"), "ru-plain")));
|
||||
assertCyrillicAndStyles("ru-plain.docx");
|
||||
// .doc-двойник фикстуры — тот же текст через мост internal.doc
|
||||
assertCyrillicAndStyles("ru-plain.doc");
|
||||
}
|
||||
|
||||
assertTrue(text.contains("Привет, мир!"), "нет «Привет, мир!»: " + text);
|
||||
private static void assertCyrillicAndStyles(String fixture) throws Exception {
|
||||
String text = norm(pdfText(convertPdf(sampleBytes(fixture), baseName(fixture))));
|
||||
|
||||
assertTrue(text.contains("Привет, мир!"), fixture + ": нет «Привет, мир!»: " + text);
|
||||
// Полный кириллический алфавит — проверка, что все глифы встроились
|
||||
assertTrue(text.contains("абвгдеёжзийклмнопрстуфхцчшщъыьэюя"),
|
||||
"нет кириллического алфавита: " + text);
|
||||
assertTrue(text.contains("жирный курсив"), "нет «жирный курсив»: " + text);
|
||||
fixture + ": нет кириллического алфавита: " + text);
|
||||
assertTrue(text.contains("жирный курсив"), fixture + ": нет «жирный курсив»: " + text);
|
||||
}
|
||||
|
||||
/** Имя фикстуры без расширения — PDF-title и имя temp-файла. */
|
||||
private static String baseName(String fixture) {
|
||||
return fixture.replaceAll("\\.docx?$", "");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -398,34 +456,63 @@ class WordPdfConverterTest {
|
||||
|
||||
@Test
|
||||
void enPlain_englishText() throws Exception {
|
||||
String text = norm(pdfText(convertPdf(sampleBytes("en-plain.docx"), "en-plain")));
|
||||
assertEnglishText("en-plain.docx");
|
||||
assertEnglishText("en-plain.doc");
|
||||
}
|
||||
|
||||
assertTrue(text.contains("Hello, world!"), "нет «Hello, world!»: " + text);
|
||||
assertTrue(text.contains("quick brown fox"), "нет «quick brown fox»: " + text);
|
||||
private static void assertEnglishText(String fixture) throws Exception {
|
||||
String text = norm(pdfText(convertPdf(sampleBytes(fixture), baseName(fixture))));
|
||||
|
||||
assertTrue(text.contains("Hello, world!"), fixture + ": нет «Hello, world!»: " + text);
|
||||
assertTrue(text.contains("quick brown fox"), fixture + ": нет «quick brown fox»: " + text);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mixed_headingListTable() throws Exception {
|
||||
String text = norm(pdfText(convertPdf(sampleBytes("ru-en-mixed.docx"), "ru-en-mixed")));
|
||||
assertHeadingListTable("ru-en-mixed.docx");
|
||||
assertHeadingListTable("ru-en-mixed.doc");
|
||||
}
|
||||
|
||||
assertTrue(text.contains("Смешанный документ"), "нет заголовка: " + text);
|
||||
assertTrue(text.contains("first item"), "нет пункта списка: " + text);
|
||||
private static void assertHeadingListTable(String fixture) throws Exception {
|
||||
String text = norm(pdfText(convertPdf(sampleBytes(fixture), baseName(fixture))));
|
||||
|
||||
assertTrue(text.contains("Смешанный документ"), fixture + ": нет заголовка: " + text);
|
||||
assertTrue(text.contains("first item"), fixture + ": нет пункта списка: " + text);
|
||||
assertTrue(text.contains("Ячейка А") && text.contains("Cell B"),
|
||||
"нет ячеек таблицы: " + text);
|
||||
fixture + ": нет ячеек таблицы: " + text);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ruTimes_russianInTimes() throws Exception {
|
||||
String text = norm(pdfText(convertPdf(sampleBytes("ru-times.docx"), "ru-times")));
|
||||
assertRussianInTimes("ru-times.docx");
|
||||
assertRussianInTimes("ru-times.doc");
|
||||
}
|
||||
|
||||
private static void assertRussianInTimes(String fixture) throws Exception {
|
||||
String text = norm(pdfText(convertPdf(sampleBytes(fixture), baseName(fixture))));
|
||||
|
||||
assertTrue(text.contains("Съешь ещё этих мягких французских булок"),
|
||||
"нет русского текста: " + text);
|
||||
fixture + ": нет русского текста: " + text);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tableImage_tableAndImage() throws Exception {
|
||||
byte[] docx = sampleBytes("ru-table-image.docx");
|
||||
String text = norm(pdfText(convertPdf(docx, "ru-table-image")));
|
||||
assertTableImage("ru-table-image.docx");
|
||||
}
|
||||
|
||||
/**
|
||||
* samples/ru-table-image.doc: картинка — BLIP OfficeArt по
|
||||
* {@code sprmCPicLocation}; мост извлекает PNG в image-часть,
|
||||
* таблица и картинка рендерятся как в .docx.
|
||||
*/
|
||||
@Test
|
||||
void tableImage_docTableAndImage() throws Exception {
|
||||
assertTableImage("ru-table-image.doc");
|
||||
}
|
||||
|
||||
private static void assertTableImage(String fixture) throws Exception {
|
||||
byte[] docx = sampleBytes(fixture);
|
||||
String text = norm(pdfText(convertPdf(docx, baseName(fixture))));
|
||||
|
||||
// Таблица без tblGrid/tcW (auto-fit): docx4j 17.x считает ширины
|
||||
// колонок по контенту и вместе с padding'ом ячейки не оставляет
|
||||
@@ -436,7 +523,7 @@ class WordPdfConverterTest {
|
||||
assertTrue(flat.contains("Русский"), "нет «Русский»: " + text);
|
||||
|
||||
// Изображение: ищем XObject'ы-изображения среди ресурсов страниц
|
||||
Path pdf = convertPdf(docx, "ru-table-image");
|
||||
Path pdf = convertPdf(docx, baseName(fixture));
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
int images = 0;
|
||||
for (PDPage page : doc.getPages()) {
|
||||
@@ -482,9 +569,9 @@ class WordPdfConverterTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* Вход без zip-подписи — отказ как некорректный вход (ValidationException),
|
||||
* а не ошибка рендера: вход конвертера прогоняет тот же
|
||||
* {@link WordPdfValidator#validate(byte[], ConvertOptions)}, что и приложение до очереди.
|
||||
* Вход без подписи какого-либо поддерживаемого контейнера (ни zip,
|
||||
* ни CFB) — отказ как некорректный вход (ValidationException),
|
||||
* а не ошибка рендера: сообщение перечисляет оба формата.
|
||||
* Регрессия — WordPdfValidatorTest#validate_notAZip.
|
||||
*/
|
||||
@Test
|
||||
@@ -492,8 +579,8 @@ class WordPdfConverterTest {
|
||||
byte[] junk = {1, 2, 3, 4, 5, 6, 7, 8};
|
||||
ValidationException ex = assertThrows(ValidationException.class, () ->
|
||||
WordPdfConverter.convert(junk, "junk"));
|
||||
assertTrue(ex.getMessage().contains("не zip-архив"),
|
||||
"сообщение должно упоминать zip-подпись: " + ex.getMessage());
|
||||
assertTrue(ex.getMessage().contains("не похоже на .docx или .doc"),
|
||||
"сообщение должно перечислять форматы: " + ex.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -539,12 +626,18 @@ class WordPdfConverterTest {
|
||||
*/
|
||||
@Test
|
||||
void tooManyPages() {
|
||||
assertTooManyPages("too-many-pages.docx");
|
||||
// .doc: 150 разрывов 0x0C считает мост по чистому бинарному документу
|
||||
assertTooManyPages("too-many-pages.doc");
|
||||
}
|
||||
|
||||
private static void assertTooManyPages(String fixture) {
|
||||
ValidationException ex = assertThrows(ValidationException.class, () ->
|
||||
WordPdfConverter.convert(
|
||||
sampleBytes("too-many-pages.docx"), "too-many-pages",
|
||||
sampleBytes(fixture), baseName(fixture),
|
||||
new ConvertOptions(false, false, false, WordPdfSettings.MAX_INPUT_MB, 100)));
|
||||
assertTrue(ex.getMessage().contains("100"),
|
||||
"сообщение должно упоминать лимит: " + ex.getMessage());
|
||||
fixture + ": сообщение должно упоминать лимит: " + ex.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -563,6 +656,23 @@ class WordPdfConverterTest {
|
||||
"сообщение должно упоминать лимит: " + ex.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* Семантическое различие форматов: stale-cache.docx отвергается
|
||||
* (кэш {@code <Pages>1</Pages>} проигрывает 110 маркерам
|
||||
* {@code w:lastRenderedPageBreak}), а stale-cache.doc конвертируется:
|
||||
* в бинарном .doc понятия lastRenderedPageBreak нет, нижняя оценка —
|
||||
* кэш PageCount=5 плюс явные разрывы, и она в лимите 100.
|
||||
* Регрессия — WordPdfConverterTest#staleCache_docConvertsByCacheOnly.
|
||||
*/
|
||||
@Test
|
||||
void staleCache_docConvertsByCacheOnly() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("stale-cache.doc"), "stale-cache",
|
||||
new ConvertOptions(false, false, false, WordPdfSettings.MAX_INPUT_MB, 100));
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
assertTrue(doc.getNumberOfPages() >= 1, "PDF не отрендерился");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Заголовок PDF — параметр {@code title} (файлового API в ядре нет,
|
||||
* из имени файла заголовок больше не выводится).
|
||||
@@ -1165,4 +1275,43 @@ class WordPdfConverterTest {
|
||||
&& dfe.kind() == DrawingFoundException.Kind.CHARTS,
|
||||
"ожидался DrawingFoundException(CHARTS), получено: " + ex);
|
||||
}
|
||||
|
||||
/**
|
||||
* Бинарный .doc (фикстура заказчика): текст и кириллица рендерятся
|
||||
* бандл-шрифтами без .notdef; страницы считаются по чистому .doc.
|
||||
* Регрессия — internal.doc.DocToDocx (мост .doc → .docx).
|
||||
*/
|
||||
@Test
|
||||
void docBinary_russianTextRenders() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("ru-plain.doc"), "ru-plain");
|
||||
String text = norm(pdfText(pdf));
|
||||
assertTrue(text.contains("Тестовый документ (русский)"), "заголовок не отрисовался");
|
||||
assertTrue(text.contains("Привет, мир!"), "текст потерялся");
|
||||
assertTrue(text.contains("абвгдеёжзийклмнопрстуфхцчшщъыьэюя"), "алфавит потерялся");
|
||||
assertFalse(text.contains("#"), ".notdef-боксы в тексте");
|
||||
assertFalse(fontNameOf(pdf, 'П').contains("Helvetica"), "внешний шрифт");
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
assertEquals(1, doc.getNumberOfPages());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* .doc с прямым форматированием: sprmPFPageBreakBefore даёт вторую
|
||||
* страницу и удерживает лимит по чистому .doc (maxPages=1 → отказ).
|
||||
* Регрессия — Sections/PapxIndex (подсчёт страниц без конвертации).
|
||||
*/
|
||||
@Test
|
||||
void docBinary_formats_pageBreakAndLimit() throws Exception {
|
||||
Path pdf = convertPdf(sampleBytes("doc-formats.doc"), "doc-formats");
|
||||
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) {
|
||||
assertEquals(2, doc.getNumberOfPages(), "pageBreakBefore не отделил страницу");
|
||||
}
|
||||
assertTrue(norm(pdfPageText(pdf, 2)).contains("Вторая страница после разрыва"),
|
||||
"второй страницы нет");
|
||||
assertThrows(ValidationException.class, () -> convertPdf(sampleBytes("doc-formats.doc"),
|
||||
"doc-formats", new ConvertOptions(false, false, false,
|
||||
WordPdfSettings.MAX_INPUT_MB, 1)),
|
||||
"лимит 1 страница не удержал двухстраничный .doc");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -571,4 +571,46 @@ class WordPdfValidatorTest {
|
||||
() -> WordPdfValidator.validate(new byte[]{'P', 'K', 0, 4},
|
||||
ConvertOptions.defaults()));
|
||||
}
|
||||
|
||||
/** Фикстура samples/*.doc (бинарный .doc заказчика). */
|
||||
private static byte[] sample(String name) throws Exception {
|
||||
try (java.io.InputStream in = WordPdfValidatorTest.class.getClassLoader()
|
||||
.getResourceAsStream("samples/" + name)) {
|
||||
assertNotNull(in, "Нет фикстуры: samples/" + name);
|
||||
return in.readAllBytes();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* .doc: страницы считаются по чистому бинарному документу, ДО конвертации
|
||||
* в .docx (кэш PageCount + разрывы 0x0C + pageBreakBefore).
|
||||
* Регрессия — WordPdfValidator#checkPageCountDoc.
|
||||
*/
|
||||
@Test
|
||||
void checkPageCountDoc_onRawBinary() throws Exception {
|
||||
// too-many-pages.doc: 150 разрывов 0x0C → 151 — отказ
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> WordPdfValidator.checkPageCountDoc(sample("too-many-pages.doc"), PAGE_LIMIT));
|
||||
assertTrue(ex.getMessage().contains("не менее 151"), ex.getMessage());
|
||||
// stale-cache.doc: кэш 5 — проходит
|
||||
assertDoesNotThrow(() -> WordPdfValidator.checkPageCountDoc(
|
||||
sample("stale-cache.doc"), PAGE_LIMIT));
|
||||
// ru-plain.doc: 1 страница
|
||||
assertDoesNotThrow(() -> WordPdfValidator.checkPageCountDoc(
|
||||
sample("ru-plain.doc"), 1));
|
||||
// doc-formats.doc: 2 страницы (sprmPFPageBreakBefore) — лимит 1 отказывает
|
||||
ValidationException two = assertThrows(ValidationException.class,
|
||||
() -> WordPdfValidator.checkPageCountDoc(sample("doc-formats.doc"), 1));
|
||||
assertTrue(two.getMessage().contains("не менее 2"), two.getMessage());
|
||||
}
|
||||
|
||||
/** validate() роутирует .doc по CFB-подписи: страницы — без zip-проверок. */
|
||||
@Test
|
||||
void validate_binaryDocRoutedToDocPageCount() throws Exception {
|
||||
byte[] doc = sample("too-many-pages.doc");
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> WordPdfValidator.validate(doc,
|
||||
options(WordPdfSettings.MAX_INPUT_MB, PAGE_LIMIT)));
|
||||
assertTrue(ex.getMessage().contains("не менее 151"), ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Юниты {@link CfbReader} ([MS-CFB]): крафтовый контейнер (сектор 512,
|
||||
* mini 64, cutoff 4096) и враждебные мутации — цикл в цепочках, ссылки за
|
||||
* файл, обрезанные потоки, битый заголовок.
|
||||
*/
|
||||
class CfbReaderTest {
|
||||
|
||||
private static final int SECTOR = 512;
|
||||
private static final int MINI = 64;
|
||||
private static final long FREE = 0xFFFF_FFFFL;
|
||||
private static final long END = 0xFFFF_FFFEL;
|
||||
private static final long FATSECT = 0xFFFF_FFFDL;
|
||||
|
||||
record Spec(String name, byte[] data) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Контейнер: сектор 0 — FAT, 1 — directory, 2 — MiniFAT (если есть
|
||||
* mini-потоки), далее mini stream, затем сектора больших потоков.
|
||||
*/
|
||||
private static byte[] build(Spec... specs) {
|
||||
List<Spec> small = new ArrayList<>();
|
||||
List<Spec> big = new ArrayList<>();
|
||||
for (Spec s : specs) {
|
||||
(s.data().length < 4096 ? small : big).add(s);
|
||||
}
|
||||
// mini stream + MiniFAT
|
||||
ByteArrayOutputStream mini = new ByteArrayOutputStream();
|
||||
int[] miniHead = new int[small.size()];
|
||||
int[] miniFat = new int[64];
|
||||
for (int i = 0; i < miniFat.length; i++) {
|
||||
miniFat[i] = (int) FREE;
|
||||
}
|
||||
int miniSects = 0;
|
||||
for (int i = 0; i < small.size(); i++) {
|
||||
byte[] d = small.get(i).data();
|
||||
miniHead[i] = miniSects;
|
||||
int n = Math.max(1, (d.length + MINI - 1) / MINI);
|
||||
mini.write(d, 0, d.length);
|
||||
for (int k = d.length; k < n * MINI; k++) {
|
||||
mini.write(0);
|
||||
}
|
||||
for (int k = 0; k < n; k++) {
|
||||
miniFat[miniSects + k] = k == n - 1 ? (int) END : miniSects + k + 1;
|
||||
}
|
||||
miniSects += n;
|
||||
}
|
||||
boolean hasMini = !small.isEmpty();
|
||||
int miniStart = hasMini ? 3 : -1;
|
||||
int bigStart = hasMini ? 3 + miniSects : 2;
|
||||
int[] fat = new int[128];
|
||||
for (int i = 0; i < fat.length; i++) {
|
||||
fat[i] = (int) FREE;
|
||||
}
|
||||
fat[0] = (int) FATSECT;
|
||||
fat[1] = (int) END;
|
||||
if (hasMini) {
|
||||
fat[2] = (int) END;
|
||||
}
|
||||
int next = bigStart;
|
||||
int[] bigHead = new int[big.size()];
|
||||
int[] bigSects = new int[big.size()];
|
||||
for (int i = 0; i < big.size(); i++) {
|
||||
bigHead[i] = next;
|
||||
int n = (big.get(i).data().length + SECTOR - 1) / SECTOR;
|
||||
bigSects[i] = n;
|
||||
for (int k = 0; k < n; k++) {
|
||||
fat[next + k] = k == n - 1 ? (int) END : next + k + 1;
|
||||
}
|
||||
next += n;
|
||||
}
|
||||
int sectorTotal = next;
|
||||
byte[] file = new byte[SECTOR * (1 + sectorTotal)];
|
||||
// заголовок (§2.2)
|
||||
System.arraycopy(CfbReader.SIGNATURE, 0, file, 0, 8);
|
||||
put16(file, 0x1E, 9); // sectorShift
|
||||
put16(file, 0x20, 6); // miniSectorShift
|
||||
put32(file, 0x30, 1); // firstDir
|
||||
put32(file, 0x38, 4096); // cutoff
|
||||
put32(file, 0x3C, hasMini ? 2 : (int) FREE); // firstMiniFat
|
||||
put32(file, 0x44, (int) FREE); // firstDifat
|
||||
put32(file, 0x48, 0); // cDifat
|
||||
put32(file, 0x4C, 0); // DIFAT[0] = сектор FAT
|
||||
for (int i = 1; i < 109; i++) {
|
||||
put32(file, 0x4C + i * 4, (int) FREE);
|
||||
}
|
||||
// FAT
|
||||
for (int i = 0; i < fat.length; i++) {
|
||||
put32(file, SECTOR + i * 4, fat[i]);
|
||||
}
|
||||
// directory: root + потоки
|
||||
dirEntry(file, 1, 0, "Root Entry", 5,
|
||||
hasMini ? miniStart : (int) END, mini.size());
|
||||
for (int i = 0; i < specs.length; i++) {
|
||||
Spec s = specs[i];
|
||||
boolean smallOne = s.data().length < 4096;
|
||||
int idx = -1;
|
||||
for (int k = 0; k < (smallOne ? small : big).size(); k++) {
|
||||
if ((smallOne ? small : big).get(k) == s) {
|
||||
idx = k;
|
||||
}
|
||||
}
|
||||
dirEntry(file, 1, 1 + i, s.name(), 2,
|
||||
smallOne ? miniHead[idx] : bigHead[idx], s.data().length);
|
||||
}
|
||||
// miniFAT
|
||||
if (hasMini) {
|
||||
for (int i = 0; i < miniFat.length; i++) {
|
||||
put32(file, SECTOR * (1 + 2) + i * 4, miniFat[i]);
|
||||
}
|
||||
System.arraycopy(mini.toByteArray(), 0, file, SECTOR * (1 + miniStart),
|
||||
mini.size());
|
||||
}
|
||||
// большие потоки
|
||||
for (int i = 0; i < big.size(); i++) {
|
||||
byte[] d = big.get(i).data();
|
||||
System.arraycopy(d, 0, file, SECTOR * (1 + bigHead[i]), d.length);
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
private static void dirEntry(byte[] file, int dirSector, int index, String name,
|
||||
int type, int start, int size) {
|
||||
int base = SECTOR * (1 + dirSector) + index * 128;
|
||||
byte[] n = name.getBytes(StandardCharsets.UTF_16LE);
|
||||
System.arraycopy(n, 0, file, base, n.length);
|
||||
put16(file, base + 0x40, n.length + 2);
|
||||
file[base + 0x42] = (byte) type;
|
||||
put32(file, base + 0x74, start);
|
||||
put32(file, base + 0x78, size);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsBigAndMiniStreams() {
|
||||
byte[] big = new byte[5000];
|
||||
for (int i = 0; i < big.length; i++) {
|
||||
big[i] = (byte) i;
|
||||
}
|
||||
byte[] small = "WordDocument".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] file = build(new Spec("WordDocument", small), new Spec("Data", big));
|
||||
Map<String, byte[]> streams = CfbReader.readStreams(file);
|
||||
assertArrayEquals(small, streams.get("WordDocument"));
|
||||
assertArrayEquals(big, streams.get("Data"));
|
||||
// поиск регистронезависимый, отсутствующий — пустой массив
|
||||
assertArrayEquals(small, CfbReader.stream(streams, "worddocument"));
|
||||
assertEquals(0, CfbReader.stream(streams, "НетТакого").length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void badHeader_rejected() {
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(null));
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(new byte[511]));
|
||||
byte[] file = build();
|
||||
file[0] = 0;
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void badSectorSizes_rejected() {
|
||||
byte[] badSector = build();
|
||||
put16(badSector, 0x1E, 10); // не 9 и не 12
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(badSector));
|
||||
byte[] badMini = build();
|
||||
put16(badMini, 0x20, 17); // mini shift за потолком
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(badMini));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dirChainLoop_rejected() {
|
||||
byte[] file = build();
|
||||
put32(file, SECTOR + 1 * 4, 1); // fat[1] = 1 — directory в цикл
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> CfbReader.readStreams(file));
|
||||
assertTrue(ex.getMessage().contains("цикл") || ex.getMessage().contains("Цикл"),
|
||||
ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dirSectorBeyondFat_rejected() {
|
||||
byte[] file = build();
|
||||
put32(file, 0x30, 200); // firstDir за FAT этого файла
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fatSectorBeyondFile_rejected() {
|
||||
byte[] file = build();
|
||||
put32(file, 0x4C, 100); // DIFAT[0] — FAT-сектор за концом файла
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void difatTooManyFatSectors_rejected() {
|
||||
byte[] file = build();
|
||||
for (int i = 0; i < 8; i++) {
|
||||
put32(file, 0x4C + i * 4, i); // 8 FAT-секторов в 4-секторном файле
|
||||
}
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> CfbReader.readStreams(file));
|
||||
assertTrue(ex.getMessage().contains("DIFAT"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void difatChainLoop_rejected() {
|
||||
byte[] file = build();
|
||||
// firstDifat = сектор 1; следующий указатель DIFAT — сам на себя
|
||||
put32(file, 0x44, 1);
|
||||
put32(file, SECTOR * 3 - 4, 1); // sect = u32(base + entries*4), entries=127
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> CfbReader.readStreams(file));
|
||||
assertTrue(ex.getMessage().contains("DIFAT"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void difatSectorBeyondFile_rejected() {
|
||||
byte[] file = build();
|
||||
put32(file, 0x44, 100);
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamChainBeyondFile_rejected() {
|
||||
byte[] big = new byte[5000];
|
||||
byte[] file = build(new Spec("Data", big));
|
||||
put32(file, SECTOR + 1 * 4, (int) END); // fat[1] — directory цела
|
||||
// цепочка Data (head=2): 2→3→100 — сектор за файлом, но в FAT
|
||||
put32(file, SECTOR + 4 * 4, 100);
|
||||
put32(file, SECTOR + 100 * 4, (int) END);
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(file));
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamTruncated_rejected() {
|
||||
byte[] big = new byte[5000];
|
||||
byte[] file = build(new Spec("Data", big));
|
||||
put32(file, SECTOR + 2 * 4, (int) END); // цепочка из одного сектора
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> CfbReader.readStreams(file));
|
||||
assertTrue(ex.getMessage().contains("Обрезанный поток"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void miniWithoutRoot_rejected() {
|
||||
byte[] file = build(new Spec("WordDocument", "abc".getBytes()));
|
||||
// root: start=END, size=0 → mini stream нет, а поток mini-размера есть
|
||||
int root = SECTOR * 2;
|
||||
put32(file, root + 0x74, (int) END);
|
||||
put32(file, root + 0x78, 0);
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> CfbReader.readStreams(file));
|
||||
assertTrue(ex.getMessage().contains("Mini stream"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void miniChainLoop_rejected() {
|
||||
byte[] file = build(new Spec("WordDocument", "abc".getBytes()));
|
||||
put32(file, SECTOR * 3, 0); // miniFat[0] = 0 — цикл
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> CfbReader.readStreams(file));
|
||||
assertTrue(ex.getMessage().contains("MiniFAT"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void miniBeyondStream_rejected() {
|
||||
byte[] file = build(new Spec("WordDocument", new byte[128]));
|
||||
// поток 128 байт (2 mini-сектора), а root объявляет mini stream в 64
|
||||
put32(file, SECTOR * 2 + 0x78, MINI);
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> CfbReader.readStreams(file));
|
||||
assertTrue(ex.getMessage().contains("за конец mini stream"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void miniTruncated_rejected() {
|
||||
byte[] file = build(new Spec("WordDocument", new byte[128]));
|
||||
put32(file, SECTOR * 3, (int) END); // цепочка обрывается на первом
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> CfbReader.readStreams(file));
|
||||
assertTrue(ex.getMessage().contains("Обрезанный mini-поток"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void badEntries_skipped() {
|
||||
byte[] good = "ok".getBytes();
|
||||
byte[] file = build(new Spec("Good", good));
|
||||
// запись 2: nameLen=0 — пропускается; запись 3: size за файлом — пропускается
|
||||
dirEntry(file, 1, 2, "", 2, 3, 2); // nameLen=2 → имя пустое — пропуск
|
||||
dirEntry(file, 1, 3, "Huge", 2, 3, file.length + 1);
|
||||
Map<String, byte[]> streams = CfbReader.readStreams(file);
|
||||
assertEquals(1, streams.size(), "битые записи не попадают в результат");
|
||||
assertArrayEquals(good, streams.get("Good"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rootChainBeyondFile_rejected() {
|
||||
byte[] file = build(new Spec("WordDocument", "abc".getBytes()));
|
||||
put32(file, SECTOR * 2 + 0x74, 100); // root start за файлом
|
||||
put32(file, SECTOR * 2 + 0x78, 64);
|
||||
put32(file, SECTOR + 100 * 4, (int) END);
|
||||
assertThrows(ValidationException.class, () -> CfbReader.readStreams(file));
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Юниты {@link ChpxIndex} ([MS-DOC] §2.4.6.2, §2.9 ChpxFkp): крафтовый
|
||||
* PlcfBteChpx + FKP-страница WordDocument — happy path, пропуски
|
||||
* (bOffset=0, пустой Chpx, деградация за страницу) и отказные ветви.
|
||||
*/
|
||||
class ChpxIndexTest {
|
||||
|
||||
private static final byte[] GRPRL = {0x35, 0x08, 0x01}; // sprmCFBold on
|
||||
|
||||
/** Таблица: aFc [2048, 2100] + pn; FKP-страница pn=2 в wd. */
|
||||
private static byte[] table(int pn) {
|
||||
byte[] t = new byte[12];
|
||||
put32(t, 0, 2048);
|
||||
put32(t, 4, 2100);
|
||||
put32(t, 8, pn);
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* WordDocument с ChpxFkp на странице pn: crun=1, rgfc [2048, 2100],
|
||||
* rgb[0]=bx, Chpx (cb+grpprl) по bx*2; crun-байт = 1.
|
||||
*/
|
||||
private static byte[] wordDocument(int bx, int cb, byte[] grpprl) {
|
||||
byte[] wd = new byte[1536];
|
||||
int page = 2 * 512;
|
||||
put32(wd, page, 2048);
|
||||
put32(wd, page + 4, 2100);
|
||||
wd[page + 8] = (byte) bx;
|
||||
wd[page + 511] = 1; // crun
|
||||
if (bx > 0) {
|
||||
wd[page + bx * 2] = (byte) cb;
|
||||
System.arraycopy(grpprl, 0, wd, page + bx * 2 + 1,
|
||||
Math.min(grpprl.length, cb));
|
||||
}
|
||||
return wd;
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyBte_defaults() {
|
||||
ChpxIndex idx = ChpxIndex.read(new byte[0], 0, 0, new byte[0]);
|
||||
assertArrayEquals(new byte[0], idx.grpprlFor(2048));
|
||||
assertEquals(999, idx.rangeEnd(2048, 999));
|
||||
}
|
||||
|
||||
@Test
|
||||
void badBte_rejected() {
|
||||
byte[] t = table(2);
|
||||
byte[] wd = wordDocument(5, 3, GRPRL);
|
||||
assertThrows(ValidationException.class,
|
||||
() -> ChpxIndex.read(t, 0, 10, wd)); // (10-4)%8 != 0
|
||||
assertThrows(ValidationException.class,
|
||||
() -> ChpxIndex.read(t, 0, t.length + 1, wd)); // за таблицей
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageBeyondWordDocument_rejected() {
|
||||
byte[] t = table(100);
|
||||
assertThrows(ValidationException.class,
|
||||
() -> ChpxIndex.read(t, 0, t.length, new byte[1536]));
|
||||
}
|
||||
|
||||
@Test
|
||||
void badCrun_rejected() {
|
||||
byte[] wd = wordDocument(5, 3, GRPRL);
|
||||
wd[2 * 512 + 511] = 0;
|
||||
assertThrows(ValidationException.class,
|
||||
() -> ChpxIndex.read(table(2), 0, 12, wd));
|
||||
wd[2 * 512 + 511] = 0x66;
|
||||
assertThrows(ValidationException.class,
|
||||
() -> ChpxIndex.read(table(2), 0, 12, wd));
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroOffsetAndEmptyChpx_skipped() {
|
||||
byte[] wd = wordDocument(0, 0, GRPRL);
|
||||
ChpxIndex idx = ChpxIndex.read(table(2), 0, 12, wd);
|
||||
assertArrayEquals(new byte[0], idx.grpprlFor(2048), "bOffset=0 — дефолт");
|
||||
|
||||
byte[] cbZero = wordDocument(5, 0, GRPRL);
|
||||
assertArrayEquals(new byte[0],
|
||||
ChpxIndex.read(table(2), 0, 12, cbZero).grpprlFor(2048),
|
||||
"cb=0 — свойств нет");
|
||||
}
|
||||
|
||||
@Test
|
||||
void chpxBeyondPage_skipped() {
|
||||
byte[] wd = wordDocument(250, 200, GRPRL); // chpxOff+1+cb за 512
|
||||
assertArrayEquals(new byte[0],
|
||||
ChpxIndex.read(table(2), 0, 12, wd).grpprlFor(2048));
|
||||
}
|
||||
|
||||
@Test
|
||||
void happyPath_grpprlAndRangeEnd() {
|
||||
ChpxIndex idx = ChpxIndex.read(table(2), 0, 12, wordDocument(5, 3, GRPRL));
|
||||
assertArrayEquals(GRPRL, idx.grpprlFor(2048));
|
||||
assertArrayEquals(GRPRL, idx.grpprlFor(2099));
|
||||
assertArrayEquals(new byte[0], idx.grpprlFor(2100), "fc за диапазоном");
|
||||
assertEquals(2100, idx.rangeEnd(2048, Long.MAX_VALUE >>> 1));
|
||||
assertEquals(2060, idx.rangeEnd(2048, 2060), "rangeEnd режется fcLimit");
|
||||
}
|
||||
|
||||
private static void put32(byte[] b, int off, int v) {
|
||||
b[off] = (byte) v;
|
||||
b[off + 1] = (byte) (v >>> 8);
|
||||
b[off + 2] = (byte) (v >>> 16);
|
||||
b[off + 3] = (byte) (v >>> 24);
|
||||
}
|
||||
}
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
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.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Мост на синтетическом .doc (крафтовый FIB + Clx + FKP-страницы, упаковка
|
||||
* POIFS): ветви {@code DocxBody}, которых нет в фикстурах заказчика —
|
||||
* полные CHPX/PAPX-свойства, знаки переноса/разрыва, поля в основном
|
||||
* тексте (не fldSimple), TTP-строка таблицы, картинки-пропуски, выбор
|
||||
* 0Table/1Table и отсутствующий табличный поток.
|
||||
*/
|
||||
class DocToDocxFormattingTest {
|
||||
|
||||
private static final int TEXT_FC = 2048;
|
||||
|
||||
private static final String DOCUMENT_XML = "word/document.xml";
|
||||
|
||||
/** Основной текст: форматированный абзац, знаки, U+0001, поле, TTP. */
|
||||
private static final String TEXT = "Bold&<>\r"
|
||||
+ "\t" + (char) 0x0B + (char) 0x0C + (char) 0x1E + (char) 0x1F + (char) 0x02
|
||||
+ "br1\r"
|
||||
+ (char) 1 + (char) 1 + "end\r"
|
||||
+ (char) 0x13 + "PAGE " + (char) 0x14 + "5" + (char) 0x18 + "\r"
|
||||
+ (char) 7 + "\r";
|
||||
|
||||
// --- крафтовый документ -------------------------------------------
|
||||
|
||||
private static byte[] wordDocument() {
|
||||
byte[] wd = new byte[TEXT_FC + TEXT.length() * 2];
|
||||
// FibBase + FibRgLw97
|
||||
put16(wd, 0, 0xA5EC);
|
||||
put16(wd, 2, 0x00C1);
|
||||
put16(wd, 10, 1 << 9); // fWhichTblStm → 1Table
|
||||
put16(wd, 62, 4); // cslw
|
||||
put32(wd, 64, wd.length); // cbMac
|
||||
put32(wd, 76, TEXT.length()); // ccpText
|
||||
put16(wd, 152, 98); // cbRgFcLcb
|
||||
// пары FibRgFcLcb97
|
||||
pair(wd, 6, 0, 20); // PlcfSed
|
||||
pair(wd, 12, 20, 12); // PlcfBteChpx
|
||||
pair(wd, 13, 32, 12); // PlcfBtePapx
|
||||
pair(wd, 15, 44, 110); // SttbfFfn
|
||||
pair(wd, 33, 160, 21); // Clx
|
||||
// текст UTF-16LE
|
||||
byte[] t = TEXT.getBytes(StandardCharsets.UTF_16LE);
|
||||
System.arraycopy(t, 0, wd, TEXT_FC, t.length);
|
||||
chpxPage(wd);
|
||||
papxPage(wd);
|
||||
return wd;
|
||||
}
|
||||
|
||||
/** ChpxFkp pn=2: ран 1 — полные свойства, ран 3 — cvAuto, ран 5 — picLocation. */
|
||||
private static void chpxPage(byte[] wd) {
|
||||
int page = 2 * 512;
|
||||
int[] rgfc = {TEXT_FC, TEXT_FC + 16, TEXT_FC + 28, TEXT_FC + 34,
|
||||
TEXT_FC + 38, TEXT_FC + 40};
|
||||
for (int i = 0; i < rgfc.length; i++) {
|
||||
put32(wd, page + i * 4, rgfc[i]);
|
||||
}
|
||||
wd[page + 24] = 16; // rgb[0] → chpx по page+32 (за rgfc+rgb)
|
||||
wd[page + 26] = 40; // rgb[2] → page+80 (cvAuto)
|
||||
wd[page + 28] = 44; // rgb[4] → page+88 (picLocation=0)
|
||||
wd[page + 511] = 5; // crun
|
||||
byte[] full = concat(
|
||||
prl(0x0835, 1), prl(0x0836, 1), prl(0x0837, 1), prl(0x2A3E, 1),
|
||||
prl2(0x4A43, 28), prl2(0x4A61, 24), prl2(0x4A4F, 0), prl2(0x4A50, 1),
|
||||
new byte[] {0x70, 0x68, (byte) 0xFF, 0, 0, 0});
|
||||
chpx(wd, page, 16, full);
|
||||
chpx(wd, page, 40, new byte[] {0x70, 0x68, (byte) 0xFF, 0, 0, (byte) 0xFF}); // cvAuto
|
||||
chpx(wd, page, 44, new byte[] {0x03, 0x6A, 0, 0, 0, 0}); // sprmCPicLocation=0
|
||||
}
|
||||
|
||||
private static void chpx(byte[] wd, int page, int bx, byte[] grpprl) {
|
||||
wd[page + bx * 2] = (byte) grpprl.length;
|
||||
System.arraycopy(grpprl, 0, wd, page + bx * 2 + 1, grpprl.length);
|
||||
}
|
||||
|
||||
/** PapxFkp pn=3: 5 абзацев с pPr, шестой (¶) — без диапазона → <w:p/>. */
|
||||
private static void papxPage(byte[] wd) {
|
||||
int page = 3 * 512;
|
||||
int[] rgfc = {TEXT_FC, TEXT_FC + 16, TEXT_FC + 36, TEXT_FC + 48,
|
||||
TEXT_FC + 68, TEXT_FC + 70, TEXT_FC + 72};
|
||||
for (int i = 0; i < rgfc.length; i++) {
|
||||
put32(wd, page + i * 4, rgfc[i]);
|
||||
}
|
||||
int rgbx = page + rgfc.length * 4;
|
||||
int[] bx = {54, 62, 72, 76, 80, 0};
|
||||
for (int i = 0; i < bx.length; i++) {
|
||||
wd[rgbx + i * 13] = (byte) bx[i];
|
||||
}
|
||||
wd[page + 511] = 6; // cpara
|
||||
// p1: center + left 720 + hanging 360 (cb≠0: istd + grpprl, 2cb−1)
|
||||
byte[] g1 = concat(prl(0x2403, 1), prl2(0x845E, 720),
|
||||
new byte[] {0x60, (byte) 0x84, (byte) 0x98, (byte) 0xFE});
|
||||
wd[page + 54 * 2] = 7; // 2·7−1 = 14 = istd(2) + g1(11) + istd… ровно 2cb−3=11
|
||||
System.arraycopy(g1, 0, wd, page + 54 * 2 + 3, g1.length);
|
||||
// p2: pageBreakBefore + right + firstLine 180 (cb=0 → cb', 2cb'−2)
|
||||
byte[] g2 = concat(prl(0x2407, 1), prl(0x2461, 2), prl2(0x845D, 240),
|
||||
prl2(0x8460, 180));
|
||||
wd[page + 62 * 2] = 0;
|
||||
wd[page + 62 * 2 + 1] = 8; // 2·8−2 = 14 = |g2|
|
||||
System.arraycopy(g2, 0, wd, page + 62 * 2 + 4, g2.length);
|
||||
// p3: both; p4: distribute; p5: TTP (cb=3 → grpprl 3 байта с +3)
|
||||
wd[page + 72 * 2] = 3;
|
||||
wd[page + 72 * 2 + 3] = 0x61;
|
||||
wd[page + 72 * 2 + 4] = 0x24;
|
||||
wd[page + 72 * 2 + 5] = 3;
|
||||
wd[page + 76 * 2] = 3;
|
||||
wd[page + 76 * 2 + 3] = 0x61;
|
||||
wd[page + 76 * 2 + 4] = 0x24;
|
||||
wd[page + 76 * 2 + 5] = 4;
|
||||
wd[page + 80 * 2] = 3;
|
||||
wd[page + 80 * 2 + 3] = 0x17; // sprmPFTtp
|
||||
wd[page + 80 * 2 + 4] = 0x24;
|
||||
wd[page + 80 * 2 + 5] = 1;
|
||||
}
|
||||
|
||||
private static byte[] tableStream() {
|
||||
byte[] t = new byte[181];
|
||||
// PlcfSed: aFc [0, ccpText] + SED (fcSepx=0)
|
||||
put32(t, 0, 0);
|
||||
put32(t, 4, TEXT.length());
|
||||
// PlcfBteChpx @20: aFc [TEXT_FC, TEXT_FC+72] + pn=2
|
||||
put32(t, 20, TEXT_FC);
|
||||
put32(t, 24, TEXT_FC + 72);
|
||||
put32(t, 28, 2);
|
||||
// PlcfBtePapx @32: то же, pn=3
|
||||
put32(t, 32, TEXT_FC);
|
||||
put32(t, 36, TEXT_FC + 72);
|
||||
put32(t, 40, 3);
|
||||
// SttbfFfn @44: Arial, T&imes
|
||||
t[44] = 2;
|
||||
t[48] = 51; // cch Arial: 39 + 12
|
||||
byte[] arial = "Arial\0".getBytes(StandardCharsets.UTF_16LE);
|
||||
System.arraycopy(arial, 0, t, 48 + 40, arial.length);
|
||||
t[48 + 52] = 53; // cch T&imes: 39 + 14
|
||||
byte[] times = "T&imes\0".getBytes(StandardCharsets.UTF_16LE);
|
||||
System.arraycopy(times, 0, t, 48 + 52 + 40, times.length);
|
||||
// Clx @160: Pcdt, один несжатый кусок
|
||||
t[160] = 0x02;
|
||||
put32(t, 161, 16);
|
||||
put32(t, 165, 0);
|
||||
put32(t, 169, TEXT.length());
|
||||
put32(t, 175, TEXT_FC); // PCD.fc (бит fCompressed = 0)
|
||||
return t;
|
||||
}
|
||||
|
||||
private static byte[] cfb(boolean use1Table, boolean withTable) throws IOException {
|
||||
POIFSFileSystem fs = new POIFSFileSystem();
|
||||
byte[] wd = wordDocument();
|
||||
if (!use1Table) {
|
||||
wd[11] &= ~0x02; // fWhichTblStm (бит 9 u16) → 0Table
|
||||
}
|
||||
fs.getRoot().createDocument("WordDocument", new ByteArrayInputStream(wd));
|
||||
if (withTable) {
|
||||
fs.getRoot().createDocument(use1Table ? "1Table" : "0Table",
|
||||
new ByteArrayInputStream(tableStream()));
|
||||
}
|
||||
fs.getRoot().createDocument("Data", new ByteArrayInputStream(new byte[64]));
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
fs.writeFilesystem(out);
|
||||
fs.close();
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static String documentXml(byte[] doc) throws IOException {
|
||||
byte[] docx = DocToDocx.convert(doc);
|
||||
try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(docx))) {
|
||||
ZipEntry e;
|
||||
while ((e = zip.getNextEntry()) != null) {
|
||||
if (DOCUMENT_XML.equals(e.getName())) {
|
||||
return new String(zip.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new AssertionError("нет document.xml");
|
||||
}
|
||||
|
||||
// --- тесты ----------------------------------------------------------
|
||||
|
||||
@Test
|
||||
void runProps_fullDirectFormatting() throws IOException {
|
||||
String xml = documentXml(cfb(true, true));
|
||||
assertTrue(xml.contains("<w:b/>"), xml);
|
||||
assertTrue(xml.contains("<w:i/>"), xml);
|
||||
assertTrue(xml.contains("<w:strike/>"), xml);
|
||||
assertTrue(xml.contains("<w:u w:val=\"single\"/>"), xml);
|
||||
assertTrue(xml.contains("<w:sz w:val=\"28\"/>"), xml);
|
||||
assertTrue(xml.contains("<w:szCs w:val=\"24\"/>"), xml);
|
||||
assertTrue(xml.contains("<w:color w:val=\"FF0000\"/>"), xml);
|
||||
assertTrue(xml.contains("w:ascii=\"Arial\" w:hAnsi=\"Arial\""), xml);
|
||||
assertTrue(xml.contains("w:cs=\"T&imes\""), "escapeAttr имени шрифта: " + xml);
|
||||
assertTrue(xml.contains("Bold&<>"), "escape текста: " + xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
void paraProps_jcIndentsAndPageBreak() throws IOException {
|
||||
String xml = documentXml(cfb(true, true));
|
||||
assertTrue(xml.contains("<w:jc w:val=\"center\"/>"), xml);
|
||||
assertTrue(xml.contains("w:left=\"720\""), xml);
|
||||
assertTrue(xml.contains("w:hanging=\"360\""), "XAS со знаком: " + xml);
|
||||
assertTrue(xml.contains("<w:pageBreakBefore/>"), xml);
|
||||
assertTrue(xml.contains("<w:jc w:val=\"right\"/>"), xml);
|
||||
assertTrue(xml.contains("w:right=\"240\""), xml);
|
||||
assertTrue(xml.contains("w:firstLine=\"180\""), xml);
|
||||
assertTrue(xml.contains("<w:jc w:val=\"both\"/>"), xml);
|
||||
assertTrue(xml.contains("<w:jc w:val=\"distribute\"/>"), xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
void specialMarks_rendered() throws IOException {
|
||||
String xml = documentXml(cfb(true, true));
|
||||
assertTrue(xml.contains("<w:tab/>"), xml);
|
||||
assertTrue(xml.contains("<w:br/>"), xml);
|
||||
assertTrue(xml.contains("<w:br w:type=\"page\"/>"), xml);
|
||||
assertTrue(xml.contains("\u2011"), "неразрывный дефис: " + xml);
|
||||
assertTrue(xml.contains("\u00AD"), "мягкий перенос: " + xml);
|
||||
assertTrue(xml.contains("br1"), "ссылка на сноску пропущена, текст цел: " + xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
void bodyField_resultVisibleInstructionHidden() throws IOException {
|
||||
String xml = documentXml(cfb(true, true));
|
||||
// fieldsAsSimple=false в основном тексте: инструкция не попадает,
|
||||
// кэшированный результат после разделителя — да
|
||||
assertFalse(xml.contains("PAGE"), "инструкция поля утекла в вывод: " + xml);
|
||||
assertTrue(xml.contains(">5<"), "результат поля потерян: " + xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
void embeddedObjectsWithoutPicture_skipped() throws IOException {
|
||||
// U+0001 без sprmCPicLocation и с picLocation на мусорный Data —
|
||||
// ни одной image-части
|
||||
byte[] docx = DocToDocx.convert(cfb(true, true));
|
||||
try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(docx))) {
|
||||
ZipEntry e;
|
||||
while ((e = zip.getNextEntry()) != null) {
|
||||
assertFalse(e.getName().startsWith("word/media/"),
|
||||
"битая картинка не должна становиться частью");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void ttpRowMark_droppedEmptyParaKept() throws IOException {
|
||||
String xml = documentXml(cfb(true, true));
|
||||
// абзацы: p1..p4 + пустой <w:p/> (последний ¶); TTP-строка (0x07) — не абзац
|
||||
int paras = xml.split("<w:p[ />]", -1).length - 1;
|
||||
assertEquals(5, paras, "TTP-маркер не должен давать абзац: " + xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroTable_usedWhenFlagClear() throws IOException {
|
||||
String xml = documentXml(cfb(false, true));
|
||||
assertTrue(xml.contains("<w:b/>"), "0Table должен читаться так же: " + xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingTableStream_rejected() throws IOException {
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> DocToDocx.convert(cfb(true, false)));
|
||||
assertTrue(ex.getMessage().contains("1Table"), ex.getMessage());
|
||||
}
|
||||
|
||||
// --- мелочь ----------------------------------------------------------
|
||||
|
||||
private static byte[] prl(int sprm, int toggle) {
|
||||
return new byte[] {(byte) sprm, (byte) (sprm >>> 8), (byte) toggle};
|
||||
}
|
||||
|
||||
private static byte[] prl2(int sprm, int v) {
|
||||
return new byte[] {(byte) sprm, (byte) (sprm >>> 8), (byte) v, (byte) (v >>> 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;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Мост .doc → .docx на фикстурах заказчика (samples/*.doc, POI-продукция)
|
||||
* и синтетических CFB (POIFS).
|
||||
*/
|
||||
class DocToDocxTest {
|
||||
|
||||
private static final String DOCUMENT_ENTRY = "word/document.xml";
|
||||
|
||||
private static byte[] sample(String name) throws IOException {
|
||||
try (InputStream in = DocToDocxTest.class.getClassLoader()
|
||||
.getResourceAsStream("samples/" + name)) {
|
||||
assertNotNull(in, "Нет фикстуры: samples/" + name);
|
||||
return in.readAllBytes();
|
||||
}
|
||||
}
|
||||
|
||||
/** document.xml из конвертированного .docx. */
|
||||
private static String documentXml(byte[] docBytes) throws IOException {
|
||||
byte[] docx = DocToDocx.convert(docBytes);
|
||||
try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(docx))) {
|
||||
ZipEntry entry;
|
||||
while ((entry = zip.getNextEntry()) != null) {
|
||||
if (DOCUMENT_ENTRY.equals(entry.getName())) {
|
||||
return new String(zip.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new AssertionError("в конвертате нет word/document.xml");
|
||||
}
|
||||
|
||||
/** CFB-контейнер с указанными потоками (для негативных случаев). */
|
||||
private static byte[] cfbWith(String... streamNames) throws IOException {
|
||||
try (POIFSFileSystem fs = new POIFSFileSystem(); ByteArrayOutputStream out =
|
||||
new ByteArrayOutputStream()) {
|
||||
for (String name : streamNames) {
|
||||
fs.createDocument(new ByteArrayInputStream(new byte[64]), name);
|
||||
}
|
||||
fs.writeFilesystem(out);
|
||||
return out.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void ruFixture_runsCarryDirectFormatting() throws IOException {
|
||||
String xml = documentXml(sample("ru-plain.doc"));
|
||||
assertTrue(xml.contains("Тестовый документ (русский)"), "нет заголовка");
|
||||
assertTrue(xml.contains("<w:b/>"), "жирное начертание потеряно");
|
||||
assertTrue(xml.contains("<w:i/>"), "курсив потерян");
|
||||
assertTrue(xml.contains("<w:sz w:val=\"36\"/>"), "размер заголовка потерян");
|
||||
assertTrue(xml.contains("абвгдеёжзийклмнопрстуфхцчшщъыьэюя"), "алфавит потерян");
|
||||
}
|
||||
|
||||
@Test
|
||||
void formatsFixture_propsTabsAndCells() throws IOException {
|
||||
String xml = documentXml(sample("doc-formats.doc"));
|
||||
assertTrue(xml.contains("<w:jc w:val=\"center\"/>"), "центрирование потеряно");
|
||||
assertTrue(xml.contains("<w:jc w:val=\"right\"/>"), "правое выравнивание потеряно");
|
||||
assertTrue(xml.contains("<w:jc w:val=\"both\"/>"), "растягивание потеряно");
|
||||
assertTrue(xml.contains("<w:ind w:left=\"1440\" w:firstLine=\"720\"/>"),
|
||||
"отступы потеряны: " + xml.substring(0, Math.min(xml.length(), 2000)));
|
||||
assertTrue(xml.contains("<w:tab/>"), "табуляция потеряна");
|
||||
assertTrue(xml.contains("<w:pageBreakBefore/>"), "перенос страницы потерян");
|
||||
for (int i = 1; i <= 4; i++) {
|
||||
assertTrue(xml.contains("Ячейка " + i), "ячейка " + i + " потеряна");
|
||||
}
|
||||
assertTrue(xml.indexOf("Ячейка 1") < xml.indexOf("Ячейка 2"), "порядок ячеек сбился");
|
||||
// конец строки таблицы (пустой абзац с 0x07+sprmPFTtp) в вывод не попадает
|
||||
assertTrue(xml.indexOf("Ячейка 2") < xml.indexOf("Ячейка 3"), "между строками мусор");
|
||||
assertTrue(!xml.contains("<w:p/>"), "пустые абзацы-концы строк не выброшены");
|
||||
}
|
||||
|
||||
@Test
|
||||
void encrypted_rejected() throws IOException {
|
||||
byte[] cfb = cfbWith("EncryptedPackage", "WordDocument");
|
||||
ValidationException e = assertThrows(ValidationException.class,
|
||||
() -> DocToDocx.convert(cfb));
|
||||
assertTrue(e.getMessage().contains("зашифрован"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cfbWithoutWordDocument_rejected() throws IOException {
|
||||
byte[] cfb = cfbWith("Workbook");
|
||||
ValidationException e = assertThrows(ValidationException.class,
|
||||
() -> DocToDocx.convert(cfb));
|
||||
assertTrue(e.getMessage().contains("не похоже"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void truncated_rejected() throws IOException {
|
||||
byte[] full = sample("ru-plain.doc");
|
||||
byte[] cut = Arrays.copyOf(full, 2048);
|
||||
assertThrows(ValidationException.class, () -> DocToDocx.convert(cut));
|
||||
}
|
||||
|
||||
@Test
|
||||
void countPages_breaksBeatStaleCache() throws IOException {
|
||||
// too-many-pages.doc: 150 разрывов 0x0C → 151; кэш PageCount=150 не выше
|
||||
assertEquals(151, DocToDocx.countPages(sample("too-many-pages.doc")));
|
||||
// page-numbers.doc: кэш PageCount=3 устарел, в тексте 3 разрыва 0x0C → 4
|
||||
// (каждый 0x0C — реальный разрыв, §2.8.26; нижняя оценка консервативна)
|
||||
assertEquals(4, DocToDocx.countPages(sample("page-numbers.doc")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageBreakBefore_countedWithoutCache() throws IOException {
|
||||
// фикстура без достоверного PageCount — «2 страницы» обязана дать
|
||||
// отсчёт по чистому .doc (абзац с sprmPFPageBreakBefore), не кэш
|
||||
assertEquals(2, DocToDocx.countPages(sample("doc-formats.doc")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
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 org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Юниты {@link FibHeader} ([MS-DOC] §2.5): крафтовый WordDocument-поток —
|
||||
* happy path и все отказные ветви (битый wIdent, старая версия, шифрование,
|
||||
* обрезанный FIB, отрицательный ccpText, устаревший cbRgFcLcb).
|
||||
*/
|
||||
class FibHeaderTest {
|
||||
|
||||
/** Минимальный валидный FIB: 98 пар, 1Table, ccpText=10. */
|
||||
private static byte[] fib(int flags) {
|
||||
byte[] wd = new byte[154 + 98 * 8];
|
||||
put16(wd, 0, 0xA5EC); // wIdent
|
||||
put16(wd, 2, 0x00C1); // nFib = Word 97
|
||||
put16(wd, 10, flags); // grpprl FIB
|
||||
put16(wd, 62, 4); // cslw
|
||||
put32(wd, 76, 10); // ccpText
|
||||
put32(wd, 152, 98); // cbRgFcLcb
|
||||
return wd;
|
||||
}
|
||||
|
||||
@Test
|
||||
void valid_readsFields() {
|
||||
FibHeader f = FibHeader.read(fib(1 << 9)); // fWhichTblStm=1
|
||||
assertEquals(10, f.ccpText());
|
||||
assertTrue(f.use1Table());
|
||||
FibHeader f0 = FibHeader.read(fib(0));
|
||||
assertFalse(f0.use1Table());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tooShort_rejected() {
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> FibHeader.read(new byte[153]));
|
||||
assertTrue(ex.getMessage().contains("не похоже"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void badWIdent_rejected() {
|
||||
byte[] wd = fib(1 << 9);
|
||||
put16(wd, 0, 0x1234);
|
||||
assertThrows(ValidationException.class, () -> FibHeader.read(wd));
|
||||
}
|
||||
|
||||
@Test
|
||||
void oldVersion_rejected() {
|
||||
byte[] wd = fib(1 << 9);
|
||||
put16(wd, 2, 0x00BF); // Word 95
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> FibHeader.read(wd));
|
||||
assertTrue(ex.getMessage().contains("Word 97"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void encrypted_rejected() {
|
||||
byte[] wd = fib(1 << 8); // fEncrypted
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> FibHeader.read(wd));
|
||||
assertTrue(ex.getMessage().contains("зашифрован"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void smallCslw_rejected() {
|
||||
byte[] wd = fib(1 << 9);
|
||||
put16(wd, 62, 3);
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> FibHeader.read(wd));
|
||||
assertTrue(ex.getMessage().contains("Обрезанный FIB"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void negativeCcpText_rejected() {
|
||||
byte[] wd = fib(1 << 9);
|
||||
put32(wd, 76, -1);
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> FibHeader.read(wd));
|
||||
assertTrue(ex.getMessage().contains("Отрицательная длина"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void staleFib_rejected() {
|
||||
byte[] wd = fib(1 << 9);
|
||||
put16(wd, 152, 33); // cbRgFcLcb ≤ индекса fcClx — нет нужных пар
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> FibHeader.read(wd));
|
||||
assertTrue(ex.getMessage().contains("Устаревшая структура"), ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void truncatedPairs_rejected() {
|
||||
byte[] full = fib(1 << 9);
|
||||
byte[] wd = new byte[300]; // пары до индекса 33 не влезают
|
||||
System.arraycopy(full, 0, wd, 0, 300);
|
||||
ValidationException ex = assertThrows(ValidationException.class,
|
||||
() -> FibHeader.read(wd));
|
||||
assertTrue(ex.getMessage().contains("Обрезанный FIB"), ex.getMessage());
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/** Юниты {@link FontTable} ([MS-DOC] §2.9, SttbfFfn/FFN). */
|
||||
class FontTableTest {
|
||||
|
||||
/** SttbfFfn: cData(2)+cbExtra(2) + (cch + FFN(39)+имя) × n. */
|
||||
private static byte[] sttbf(String... names) {
|
||||
int size = 4;
|
||||
for (String n : names) {
|
||||
size += 1 + 39 + (n.length() + 1) * 2;
|
||||
}
|
||||
byte[] t = new byte[size];
|
||||
t[0] = (byte) names.length;
|
||||
int p = 4;
|
||||
for (String n : names) {
|
||||
byte[] name = (n + "\0").getBytes(StandardCharsets.UTF_16LE);
|
||||
t[p] = (byte) (39 + name.length);
|
||||
p += 40; // cch + FFN-тело до имени
|
||||
System.arraycopy(name, 0, t, p, name.length);
|
||||
p += name.length;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyLcb_emptyTable() {
|
||||
FontTable ft = FontTable.read(new byte[0], 0, 0);
|
||||
assertNull(ft.font(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void outOfRange_rejected() {
|
||||
byte[] t = sttbf("Arial");
|
||||
assertThrows(ValidationException.class, () -> FontTable.read(t, 0, t.length + 1));
|
||||
assertThrows(ValidationException.class, () -> FontTable.read(t, 1, t.length));
|
||||
assertThrows(ValidationException.class, () -> FontTable.read(t, 0, 3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void truncatedEntry_rejected() {
|
||||
byte[] cut = new byte[4]; // cData=1, но элемента нет вовсе
|
||||
cut[0] = 1;
|
||||
assertThrows(ValidationException.class, () -> FontTable.read(cut, 0, cut.length));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shortFfn_rejected() {
|
||||
byte[] t = sttbf("Arial");
|
||||
t[4] = 38; // cch < 39
|
||||
assertThrows(ValidationException.class, () -> FontTable.read(t, 0, t.length));
|
||||
t[4] = 120; // cch за конец буфера
|
||||
assertThrows(ValidationException.class, () -> FontTable.read(t, 0, t.length));
|
||||
}
|
||||
|
||||
@Test
|
||||
void happyPath_namesByIndex() {
|
||||
byte[] t = sttbf("Arial", "Times New Roman");
|
||||
FontTable ft = FontTable.read(t, 0, t.length);
|
||||
assertEquals("Arial", ft.font(0));
|
||||
assertEquals("Times New Roman", ft.font(1));
|
||||
assertNull(ft.font(2));
|
||||
assertNull(ft.font(-1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nameBeyondCch_truncatedAtNul() {
|
||||
// имя длиннее cch-хвоста не читается: обрезаем по \0 в пределах cch
|
||||
byte[] t = sttbf("Arial");
|
||||
assertTrue(FontTable.read(t, 0, t.length).font(0).startsWith("Arial"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
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.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Юниты {@link Grpprl} ([MS-DOC] §2.6, §3 Figure 33): обход Prl всех форм. */
|
||||
class GrpprlTest {
|
||||
|
||||
@Test
|
||||
void scan_allOperandForms() {
|
||||
List<Integer> seen = new ArrayList<>();
|
||||
List<Integer> sizes = new ArrayList<>();
|
||||
byte[] buf = {
|
||||
0x35, 0x08, 0x01, // toggle (spra 0) — 1 байт
|
||||
0x3E, 0x2A, 0x01, // 1-байтовый (spra 1)
|
||||
0x43, 0x4A, 0x16, 0x00, // 2-байтовый (spra 2)
|
||||
0x03, 0x6A, 0x01, 0x00, 0x00, 0x00, // 4-байтовый (spra 3)
|
||||
(byte) 0x01, (byte) 0xE0, 0x0A, 0x00, 0x00, // 3-байтовый (spra 7)
|
||||
0x00, // хвост 1 байт — обрыв
|
||||
};
|
||||
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> {
|
||||
seen.add(sprm);
|
||||
sizes.add(len);
|
||||
});
|
||||
assertEquals(List.of(0x0835, 0x2A3E, 0x4A43, 0x6A03, 0xE001), seen);
|
||||
assertEquals(List.of(1, 1, 2, 4, 3), sizes);
|
||||
}
|
||||
|
||||
@Test
|
||||
void scan_variableOperand() {
|
||||
// spra 6 (старшие биты 110): первый байт операнда — длина остального
|
||||
byte[] buf = {0x10, (byte) 0xC0, 0x02, (byte) 0xAA, (byte) 0xBB};
|
||||
int[] got = {-1};
|
||||
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> {
|
||||
got[0] = len;
|
||||
assertEquals(0xC010, sprm);
|
||||
});
|
||||
assertEquals(3, got[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void scan_truncatedOperand_stops() {
|
||||
byte[] buf = {0x43, 0x4A, 0x16}; // 2-байтовый операнд не влезает
|
||||
int[] count = {0};
|
||||
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> count[0]++);
|
||||
assertEquals(0, count[0], "битый хвост — свойства не применяются");
|
||||
}
|
||||
|
||||
@Test
|
||||
void scan_variableWithoutLengthByte_stops() {
|
||||
byte[] buf = {0x10, (byte) 0xC0}; // spra 6, а байта длины нет
|
||||
int[] count = {0};
|
||||
Grpprl.scan(buf, 0, buf.length, (sprm, b, off, len) -> count[0]++);
|
||||
assertEquals(0, count[0]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void operandInt_widths() {
|
||||
byte[] buf = {0x34, 0x12, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF};
|
||||
assertEquals(0x1234, Grpprl.operandInt(buf, 0, 2));
|
||||
assertEquals(0xCDAB1234, Grpprl.operandInt(buf, 0, 5), "длиннее 4 — обрезается");
|
||||
}
|
||||
|
||||
@Test
|
||||
void toggleOn_parity() {
|
||||
assertTrue(Grpprl.toggleOn(new byte[] {1}, 0));
|
||||
assertFalse(Grpprl.toggleOn(new byte[] {2}, 0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
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 org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/** Юниты {@link Headers} ([MS-DOC] §2.8.22, §2.4.4). */
|
||||
class HeadersTest {
|
||||
|
||||
/** aCP: 6 разделителей + 6 историй секции 0 + хвост (13 значений). */
|
||||
private static byte[] plcf(int... cps) {
|
||||
byte[] t = new byte[cps.length * 4];
|
||||
for (int i = 0; i < cps.length; i++) {
|
||||
put32(t, i * 4, cps[i]);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyPlcf_noStories() {
|
||||
Headers h = Headers.read(new byte[0], 0, 0, 100);
|
||||
assertFalse(h.oddHeader(0).hasContent());
|
||||
assertFalse(h.oddFooter(0).hasContent());
|
||||
assertEquals(0, h.oddHeader(0).cpStart());
|
||||
}
|
||||
|
||||
@Test
|
||||
void outOfRange_rejected() {
|
||||
byte[] t = plcf(0, 1);
|
||||
assertThrows(ValidationException.class, () -> Headers.read(t, 0, 12, 0));
|
||||
assertThrows(ValidationException.class, () -> Headers.read(t, 0, 6, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void decreasingAcp_rejected() {
|
||||
assertThrows(ValidationException.class,
|
||||
() -> Headers.read(plcf(0, 5, 3), 0, 12, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stories_absoluteCpAndGuards() {
|
||||
int[] cps = new int[13];
|
||||
for (int i = 0; i < 13; i++) {
|
||||
cps[i] = 2 * i;
|
||||
}
|
||||
byte[] t = plcf(cps);
|
||||
Headers h = Headers.read(t, 0, t.length, 1000); // baseCp = ccpText+ccpFtn
|
||||
// история 7 = odd header секции 0: [1000+14, 1000+16)
|
||||
Headers.Story hdr = h.oddHeader(0);
|
||||
assertEquals(1014, hdr.cpStart());
|
||||
assertEquals(1016, hdr.cpEnd());
|
||||
assertTrue(hdr.hasContent());
|
||||
assertEquals(1015, hdr.contentEnd(), "последний ¶ — guard, вне контента");
|
||||
// история 9 = odd footer: [1018, 1020)
|
||||
Headers.Story ftr = h.oddFooter(0);
|
||||
assertEquals(1018, ftr.cpStart());
|
||||
assertEquals(1019, ftr.contentEnd());
|
||||
assertTrue(ftr.hasContent());
|
||||
// одна guard-¶ — содержимого нет
|
||||
assertFalse(new Headers.Story(5, 6).hasContent());
|
||||
// секции 1 нет (aCp короче) → пустая история
|
||||
assertEquals(0, h.oddHeader(1).cpEnd());
|
||||
}
|
||||
|
||||
private static void put32(byte[] b, int off, int v) {
|
||||
b[off] = (byte) v;
|
||||
b[off + 1] = (byte) (v >>> 8);
|
||||
b[off + 2] = (byte) (v >>> 16);
|
||||
b[off + 3] = (byte) (v >>> 24);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Юниты {@link OfficeArt}: крафтовые PICF+BLIP-области ([MS-DOC] §2.9.192,
|
||||
* [MS-ODRAW] §2.2.23–.31) — отбор по сигнатуре, UID-чётность, размеры,
|
||||
* DIB→PNG, деградация на метафайлах и мусоре. Фикстуры-документы
|
||||
* (samples/ru-table-image.doc и др.) покрывает WordPdfConverterTest.
|
||||
*/
|
||||
class OfficeArtTest {
|
||||
|
||||
private static final byte[] PNG_TINY = pngBytes();
|
||||
|
||||
@Test
|
||||
void pngBlip_extractedWithScaledSize() {
|
||||
byte[] region = region(picf(1800, 900, 1000, 1000),
|
||||
blip(0x6E0, 0xF01E, 16, PNG_TINY));
|
||||
OfficeArt.Picture pic = OfficeArt.read(region, 0);
|
||||
assertNotNull(pic);
|
||||
assertEquals("png", pic.extension());
|
||||
assertEquals("image/png", pic.contentType());
|
||||
assertArrayEquals(PNG_TINY, pic.data());
|
||||
assertEquals(1800 * 635, pic.cxEmu());
|
||||
assertEquals(900 * 635, pic.cyEmu());
|
||||
}
|
||||
|
||||
@Test
|
||||
void oddInstance_secondUidSkipped() {
|
||||
byte[] region = region(picf(100, 100, 1000, 1000),
|
||||
blip(0x6E1, 0xF01E, 32, PNG_TINY));
|
||||
OfficeArt.Picture pic = OfficeArt.read(region, 0);
|
||||
assertNotNull(pic, "нечётный recInstance — два UID, данные после 32+1");
|
||||
assertArrayEquals(PNG_TINY, pic.data());
|
||||
}
|
||||
|
||||
@Test
|
||||
void jpegBlip_extracted() {
|
||||
byte[] jpeg = {(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE0, 1, 2, 3};
|
||||
byte[] region = region(picf(100, 100, 1000, 1000), blip(0x46B, 0xF01D, 16, jpeg));
|
||||
OfficeArt.Picture pic = OfficeArt.read(region, 0);
|
||||
assertNotNull(pic);
|
||||
assertEquals("jpg", pic.extension());
|
||||
assertEquals("image/jpeg", pic.contentType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void jpegAltRecType_accepted() {
|
||||
// [MS-ODRAW] A.1: 0xF02A трактуется как 0xF01D
|
||||
byte[] jpeg = {(byte) 0xFF, (byte) 0xD8, 1, 2};
|
||||
byte[] region = region(picf(100, 100, 1000, 1000), blip(0x46B, 0xF02A, 16, jpeg));
|
||||
assertNotNull(OfficeArt.read(region, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void metafileBlips_skipped() {
|
||||
for (int type : new int[] {0xF01A, 0xF01B, 0xF01C}) {
|
||||
byte[] region = region(picf(100, 100, 1000, 1000),
|
||||
blip(0x2FC, type, 16, PNG_TINY));
|
||||
assertNull(OfficeArt.read(region, 0),
|
||||
"метафайл 0x" + Integer.toHexString(type) + " не рендерится");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void pngSignatureRequired() {
|
||||
byte[] region = region(picf(100, 100, 1000, 1000),
|
||||
blip(0x6E0, 0xF01E, 16, new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9}));
|
||||
assertNull(OfficeArt.read(region, 0), "recType=PNG без сигнатуры — ложное срабатывание");
|
||||
}
|
||||
|
||||
@Test
|
||||
void badPicfHeader_rejected() {
|
||||
byte[] good = region(picf(100, 100, 1000, 1000), blip(0x6E0, 0xF01E, 16, PNG_TINY));
|
||||
byte[] badCb = good.clone();
|
||||
badCb[4] = 0x40; // cbHeader ≠ 0x44 (NilPICFAndBinData — OLE-бинарник)
|
||||
assertNull(OfficeArt.read(badCb, 0));
|
||||
|
||||
byte[] badLcb = good.clone();
|
||||
put32(badLcb, 0, 40); // lcb < PICF_SIZE
|
||||
assertNull(OfficeArt.read(badLcb, 0));
|
||||
|
||||
assertNull(OfficeArt.read(good, -1), "отрицательный picLocation");
|
||||
assertNull(OfficeArt.read(good, good.length - 10), "PICF не влезает в поток");
|
||||
|
||||
byte[] truncated = new byte[good.length - 1];
|
||||
System.arraycopy(good, 0, truncated, 0, truncated.length);
|
||||
assertNull(OfficeArt.read(truncated, 0), "off + lcb за концом потока");
|
||||
}
|
||||
|
||||
@Test
|
||||
void garbageRegion_null() {
|
||||
byte[] region = new byte[256];
|
||||
for (int i = 0; i < region.length; i++) {
|
||||
region[i] = (byte) (i * 31 + 7);
|
||||
}
|
||||
put32(region, 0, region.length);
|
||||
put16(region, 4, 0x44);
|
||||
assertNull(OfficeArt.read(region, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shapefilePrefix_skipped() {
|
||||
// mm=0x0066: после PICF идёт cchPicName + stPicName ([MS-DOC] §2.9.190)
|
||||
byte[] picf = picf(100, 100, 1000, 1000);
|
||||
put16(picf, 6, 0x0066);
|
||||
byte[] name = {3, 'b', 'm', 'p'};
|
||||
byte[] blip = blip(0x6E0, 0xF01E, 16, PNG_TINY);
|
||||
byte[] region = new byte[picf.length + name.length + blip.length];
|
||||
System.arraycopy(picf, 0, region, 0, picf.length);
|
||||
System.arraycopy(name, 0, region, picf.length, name.length);
|
||||
System.arraycopy(blip, 0, region, picf.length + name.length, blip.length);
|
||||
put32(region, 0, region.length);
|
||||
assertNotNull(OfficeArt.read(region, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pngSizeFallsBackToIhdr() {
|
||||
// dxaGoal=0 → размер из IHDR @96 dpi: 100×50 px → 1500×750 twips
|
||||
byte[] region = region(picf(0, 0, 1000, 1000), blip(0x6E0, 0xF01E, 16, PNG_TINY));
|
||||
OfficeArt.Picture pic = OfficeArt.read(region, 0);
|
||||
assertNotNull(pic);
|
||||
assertEquals(1500 * 635, pic.cxEmu());
|
||||
assertEquals(750 * 635, pic.cyEmu());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dibReencodedToPng() {
|
||||
byte[] dib = dib24();
|
||||
byte[] region = region(picf(100, 100, 1000, 1000), blip(0x6E4, 0xF01F, 16, dib));
|
||||
OfficeArt.Picture pic = OfficeArt.read(region, 0);
|
||||
assertNotNull(pic, "DIB обязан перекодироваться в PNG");
|
||||
assertEquals("png", pic.extension());
|
||||
assertEquals((byte) 0x89, pic.data()[0]);
|
||||
assertEquals('P', pic.data()[1]);
|
||||
}
|
||||
|
||||
@Test
|
||||
void truncatedDib_null() {
|
||||
byte[] region = region(picf(100, 100, 1000, 1000),
|
||||
blip(0x6E4, 0xF01F, 16, new byte[20]));
|
||||
assertNull(OfficeArt.read(region, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void blipBeyondLcb_rejected() {
|
||||
byte[] picf = picf(100, 100, 1000, 1000);
|
||||
byte[] blip = blip(0x6E0, 0xF01E, 16, PNG_TINY);
|
||||
byte[] region = new byte[picf.length + blip.length];
|
||||
System.arraycopy(picf, 0, region, 0, picf.length);
|
||||
System.arraycopy(blip, 0, region, picf.length, blip.length);
|
||||
put32(region, 0, picf.length + 4); // lcb обрезает BLIP-область
|
||||
assertNull(OfficeArt.read(region, 0), "cb за пределами lcb — не картинка");
|
||||
}
|
||||
|
||||
// --- конструкторы крафтовых областей -------------------------------
|
||||
|
||||
/** PICF (68 байт) с заданными dxaGoal/dyaGoal/mx/my. */
|
||||
private static byte[] picf(int dxaGoal, int dyaGoal, int mx, int my) {
|
||||
byte[] picf = new byte[68];
|
||||
put16(picf, 4, 0x44);
|
||||
put16(picf, 0x1C, dxaGoal);
|
||||
put16(picf, 0x1E, dyaGoal);
|
||||
put16(picf, 0x20, mx);
|
||||
put16(picf, 0x22, my);
|
||||
return picf;
|
||||
}
|
||||
|
||||
/** OfficeArtRecord: verInstance/type/cb + uid(16|32) + tag + данные. */
|
||||
private static byte[] blip(int verInstance, int type, int uidSize, byte[] data) {
|
||||
ByteBuffer buf = ByteBuffer.allocate(8 + uidSize + 1 + data.length)
|
||||
.order(ByteOrder.LITTLE_ENDIAN);
|
||||
buf.putShort((short) verInstance);
|
||||
buf.putShort((short) type);
|
||||
buf.putInt(uidSize + 1 + data.length);
|
||||
buf.position(8 + uidSize);
|
||||
buf.put((byte) 0xFF); // tag
|
||||
buf.put(data);
|
||||
return buf.array();
|
||||
}
|
||||
|
||||
/** PICF + записи, lcb = вся область. */
|
||||
private static byte[] region(byte[] picf, byte[]... records) {
|
||||
int len = picf.length;
|
||||
for (byte[] r : records) {
|
||||
len += r.length;
|
||||
}
|
||||
byte[] out = new byte[len];
|
||||
System.arraycopy(picf, 0, out, 0, picf.length);
|
||||
int at = picf.length;
|
||||
for (byte[] r : records) {
|
||||
System.arraycopy(r, 0, out, at, r.length);
|
||||
at += r.length;
|
||||
}
|
||||
put32(out, 0, len);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Минимальный PNG 100×50 (сигнатура + IHDR + усечённое тело). */
|
||||
private static byte[] pngBytes() {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
byte[] sig = {(byte) 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A};
|
||||
out.writeBytes(sig);
|
||||
ByteBuffer ihdr = ByteBuffer.allocate(21).order(ByteOrder.BIG_ENDIAN);
|
||||
ihdr.putInt(13).put(new byte[] {'I', 'H', 'D', 'R'})
|
||||
.putInt(100).putInt(50).put((byte) 8).put((byte) 2)
|
||||
.put((byte) 0).put((byte) 0).put((byte) 0);
|
||||
out.writeBytes(ihdr.array());
|
||||
out.writeBytes(new byte[8]); // хвост: pngDxa читает IHDR до +24
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
/** DIB 24 bpp 2×2 (BITMAPINFOHEADER + 2 ряда по 8 байт). */
|
||||
private static byte[] dib24() {
|
||||
ByteBuffer buf = ByteBuffer.allocate(40 + 16).order(ByteOrder.LITTLE_ENDIAN);
|
||||
buf.putInt(40).putInt(2).putInt(2).putShort((short) 1).putShort((short) 24)
|
||||
.putInt(0).putInt(0).putInt(0).putInt(0).putInt(0).putInt(0);
|
||||
for (int i = 0; i < 16; i++) {
|
||||
buf.put((byte) (i * 40));
|
||||
}
|
||||
return buf.array();
|
||||
}
|
||||
|
||||
private static void put16(byte[] data, int off, int value) {
|
||||
data[off] = (byte) value;
|
||||
data[off + 1] = (byte) (value >>> 8);
|
||||
}
|
||||
|
||||
private static void put32(byte[] data, int off, int value) {
|
||||
data[off] = (byte) value;
|
||||
data[off + 1] = (byte) (value >>> 8);
|
||||
data[off + 2] = (byte) (value >>> 16);
|
||||
data[off + 3] = (byte) (value >>> 24);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Юниты {@link PapxIndex} ([MS-DOC] §2.4.6.1, §2.9.16/.175): крафтовый
|
||||
* PlcfBtePapx + PapxFkp — обе формы PapxInFkp (cb≠0 и cb=0→cb'), пропуски
|
||||
* и {@code countPageBreakBefore}.
|
||||
*/
|
||||
class PapxIndexTest {
|
||||
|
||||
/** sprmPFPageBreakBefore=0x2407 toggle, on. */
|
||||
private static final byte[] GRPRL_PB = {0x07, 0x24, 0x01};
|
||||
|
||||
private static byte[] table(int pn) {
|
||||
byte[] t = new byte[12];
|
||||
put32(t, 0, 2048);
|
||||
put32(t, 4, 2100);
|
||||
put32(t, 8, pn);
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* WordDocument с PapxFkp на странице pn: cpara=1, rgfc [2048, 2100],
|
||||
* BxPap.bOffset=bx; PapxInFkp: cb≠0 → istd(2)+grpprl (2cb−1 всего),
|
||||
* cb=0 → cb'-байт и 2cb' всего.
|
||||
*/
|
||||
private static byte[] wordDocument(int bx, boolean shortForm, int cb,
|
||||
byte[] grpprl) {
|
||||
byte[] wd = new byte[1536];
|
||||
int page = 2 * 512;
|
||||
put32(wd, page, 2048);
|
||||
put32(wd, page + 4, 2100);
|
||||
wd[page + 8] = (byte) bx; // rgbx[0].bOffset (BxPap 13 байт, первый)
|
||||
wd[page + 511] = 1; // cpara
|
||||
int infkp = page + bx * 2;
|
||||
if (shortForm) { // cb=0: следующий байт — cb'
|
||||
wd[infkp] = 0;
|
||||
wd[infkp + 1] = (byte) cb;
|
||||
wd[infkp + 2] = 0; // istd
|
||||
wd[infkp + 3] = 0;
|
||||
System.arraycopy(grpprl, 0, wd, infkp + 4, grpprl.length);
|
||||
} else {
|
||||
wd[infkp] = (byte) cb;
|
||||
wd[infkp + 1] = 0; // istd
|
||||
wd[infkp + 2] = 0;
|
||||
System.arraycopy(grpprl, 0, wd, infkp + 3, grpprl.length);
|
||||
}
|
||||
return wd;
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyBte_defaults() {
|
||||
PapxIndex idx = PapxIndex.read(new byte[0], 0, 0, new byte[0]);
|
||||
assertArrayEquals(new byte[0], idx.grpprlFor(2048));
|
||||
assertEquals(0, idx.countPageBreakBefore());
|
||||
}
|
||||
|
||||
@Test
|
||||
void badBte_rejected() {
|
||||
byte[] t = table(2);
|
||||
byte[] wd = wordDocument(11, false, 3, GRPRL_PB);
|
||||
assertThrows(ValidationException.class, () -> PapxIndex.read(t, 0, 11, wd));
|
||||
assertThrows(ValidationException.class, () -> PapxIndex.read(t, 0, 13, wd));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageBeyondWordDocument_rejected() {
|
||||
assertThrows(ValidationException.class,
|
||||
() -> PapxIndex.read(table(100), 0, 12, new byte[1536]));
|
||||
}
|
||||
|
||||
@Test
|
||||
void badCpara_rejected() {
|
||||
byte[] wd = wordDocument(11, false, 3, GRPRL_PB);
|
||||
wd[2 * 512 + 511] = 0;
|
||||
assertThrows(ValidationException.class, () -> PapxIndex.read(table(2), 0, 12, wd));
|
||||
wd[2 * 512 + 511] = 0x61;
|
||||
assertThrows(ValidationException.class, () -> PapxIndex.read(table(2), 0, 12, wd));
|
||||
}
|
||||
|
||||
@Test
|
||||
void longForm_extractsGrpprl() {
|
||||
// cb=3 → stdSize=5 = istd(2)+grpprl(3)
|
||||
PapxIndex idx = PapxIndex.read(table(2), 0, 12, wordDocument(11, false, 3, GRPRL_PB));
|
||||
assertArrayEquals(GRPRL_PB, idx.grpprlFor(2048));
|
||||
assertEquals(1, idx.countPageBreakBefore());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shortForm_extractsGrpprl() {
|
||||
// cb=0, cb'=3 → stdSize=6 = istd(2)+grpprl(4)… берём grpprl 4 байта
|
||||
byte[] grpprl = {0x07, 0x24, 0x01, 0x00};
|
||||
PapxIndex idx = PapxIndex.read(table(2), 0, 12, wordDocument(11, true, 3, grpprl));
|
||||
assertArrayEquals(grpprl, idx.grpprlFor(2048));
|
||||
}
|
||||
|
||||
@Test
|
||||
void zeroOffsetAndTinyStd_skipped() {
|
||||
assertArrayEquals(new byte[0],
|
||||
PapxIndex.read(table(2), 0, 12, wordDocument(0, false, 3, GRPRL_PB))
|
||||
.grpprlFor(2048), "bOffset=0 — дефолт");
|
||||
// cb=1 → stdSize=1 → grpprlLen=-1 — слишком мелко, пропуск
|
||||
assertArrayEquals(new byte[0],
|
||||
PapxIndex.read(table(2), 0, 12, wordDocument(11, false, 1, GRPRL_PB))
|
||||
.grpprlFor(2048));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stdBeyondPage_skipped() {
|
||||
// bx=250: infkp=page+500, std за границу 512-байтовой страницы
|
||||
assertArrayEquals(new byte[0],
|
||||
PapxIndex.read(table(2), 0, 12, wordDocument(250, false, 60, GRPRL_PB))
|
||||
.grpprlFor(2048));
|
||||
}
|
||||
|
||||
@Test
|
||||
void countPageBreakBefore_countsOnlyOn() {
|
||||
byte[] wd = wordDocument(11, false, 3, GRPRL_PB);
|
||||
wd[2 * 512 + 27] = 0; // toggle off (grpprl по infkp+3=+25, operand +2)
|
||||
assertEquals(0, PapxIndex.read(table(2), 0, 12, wd).countPageBreakBefore());
|
||||
}
|
||||
|
||||
private static void put32(byte[] b, int off, int v) {
|
||||
b[off] = (byte) v;
|
||||
b[off + 1] = (byte) (v >>> 8);
|
||||
b[off + 2] = (byte) (v >>> 16);
|
||||
b[off + 3] = (byte) (v >>> 24);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Юниты guard'а {@link PieceTable}: FC-диапазон куска обязан лежать внутри
|
||||
* WordDocument-потока ([MS-DOC] §2.9.177) — иначе charAt/fcOf читали бы за
|
||||
* массивом (IOOBE вместо 400).
|
||||
*/
|
||||
class PieceTableTest {
|
||||
|
||||
/** Clx = Pcdt с одним Pcd: aCp=[0, cpEnd], fc с флагом сжатия. */
|
||||
private static byte[] clxOnePiece(int cpEnd, long fc, boolean compressed) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
out.write(0x02); // clxt Pcdt
|
||||
out.write(le32(4 + 12)); // lcb PlcPcd: 2 aCP + 1 Pcd
|
||||
out.write(le32(0));
|
||||
out.write(le32(cpEnd));
|
||||
out.write(new byte[] {0, 0}); // Pcd.flags
|
||||
long fcw = (fc & 0x3FFF_FFFFL) | (compressed ? 0x4000_0000L : 0);
|
||||
out.write(le32((int) fcw));
|
||||
out.write(new byte[] {0, 0}); // Pcd.prm
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] le32(int v) {
|
||||
return new byte[] {(byte) v, (byte) (v >>> 8), (byte) (v >>> 16), (byte) (v >>> 24)};
|
||||
}
|
||||
|
||||
@Test
|
||||
void uncompressedPieceBeyondWordDocument_rejected() throws Exception {
|
||||
byte[] table = clxOnePiece(10, 0, false); // 10 CP × 2 байта = 20
|
||||
byte[] wordDocument = new byte[8];
|
||||
ValidationException e = assertThrows(ValidationException.class,
|
||||
() -> PieceTable.read(table, 0, table.length, wordDocument));
|
||||
assertTrue(e.getMessage().contains("WordDocument"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void compressedPieceBeyondWordDocument_rejected() throws Exception {
|
||||
byte[] table = clxOnePiece(10, 2 * 8, true); // сжатый: fc/2=8, span=10 > 8
|
||||
byte[] wordDocument = new byte[8];
|
||||
assertThrows(ValidationException.class,
|
||||
() -> PieceTable.read(table, 0, table.length, wordDocument));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pieceWithinWordDocument_reads() throws Exception {
|
||||
byte[] table = clxOnePiece(2, 0, false);
|
||||
byte[] wordDocument = {'H', 0, 'i', 0};
|
||||
PieceTable pt = PieceTable.read(table, 0, table.length, wordDocument);
|
||||
assertEquals('H', pt.charAt(0));
|
||||
assertEquals('i', pt.charAt(1));
|
||||
assertEquals(2, pt.fcOf(1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import ru.pjandro.wordpdf.ValidationException;
|
||||
|
||||
/**
|
||||
* Юниты {@link Sections} ([MS-DOC] §2.6.3, PlcfSed/Sepx): геометрия
|
||||
* последней секции, continuous-оценки предыдущих, пропуски битых Sepx.
|
||||
*/
|
||||
class SectionsTest {
|
||||
|
||||
/** PlcfSed из n секций; fcSepx[i] — по wordDocument-адресам. */
|
||||
private static byte[] plcfSed(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);
|
||||
}
|
||||
int sedBase = (n + 1) * 4;
|
||||
for (int i = 0; i < n; i++) {
|
||||
put32(t, sedBase + i * 12 + 2, fcSepxs[i]);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/** Sepx в wordDocument: cb(2) + grpprl. */
|
||||
private static void sepx(byte[] wd, int fc, byte[] grpprl) {
|
||||
wd[fc] = (byte) grpprl.length;
|
||||
wd[fc + 1] = 0;
|
||||
System.arraycopy(grpprl, 0, wd, fc + 2, grpprl.length);
|
||||
}
|
||||
|
||||
/** Prl: sprm LE + 2-байтовый операнд. */
|
||||
private static byte[] prl2(int sprm, int v) {
|
||||
return new byte[] {(byte) sprm, (byte) (sprm >>> 8), (byte) v, (byte) (v >>> 8)};
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptySed_defaults() {
|
||||
Sections s = Sections.read(new byte[0], 0, 0, new byte[0]);
|
||||
assertEquals(12240, s.pageWidth());
|
||||
assertEquals(15840, s.pageHeight());
|
||||
assertEquals(1440, s.marginLeft());
|
||||
assertEquals(720, s.header());
|
||||
assertEquals(0, s.continuousSectionEnds());
|
||||
}
|
||||
|
||||
@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]));
|
||||
}
|
||||
|
||||
@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);
|
||||
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);
|
||||
assertEquals(12240, s2.pageWidth());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lastSection_geometryApplied() {
|
||||
byte[] wd = new byte[4096];
|
||||
byte[] gpr = concat(prl2(Grpprl.SPRM_S_XA_PAGE, 16838),
|
||||
prl2(Grpprl.SPRM_S_YA_PAGE, 11906),
|
||||
prl2(Grpprl.SPRM_S_DXA_LEFT, 1080),
|
||||
prl2(Grpprl.SPRM_S_DXA_RIGHT, 1081),
|
||||
prl2(Grpprl.SPRM_S_DYA_TOP, 1440),
|
||||
prl2(Grpprl.SPRM_S_DYA_BOTTOM, 1441),
|
||||
prl2(Grpprl.SPRM_S_DYA_HDR_TOP, 850),
|
||||
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);
|
||||
assertEquals(16838, s.pageWidth());
|
||||
assertEquals(11906, s.pageHeight());
|
||||
assertEquals(1080, s.marginLeft());
|
||||
assertEquals(1081, s.marginRight());
|
||||
assertEquals(1440, s.marginTop());
|
||||
assertEquals(1441, s.marginBottom());
|
||||
assertEquals(850, s.header());
|
||||
assertEquals(992, s.footer());
|
||||
}
|
||||
|
||||
@Test
|
||||
void continuousEnds_countedForNonLastOnly() {
|
||||
byte[] wd = new byte[4096];
|
||||
byte[] cont = {0x09, 0x30, 0x00}; // sprmSBkc=0x3009, bkcContinuous
|
||||
byte[] newPage = {0x09, 0x30, 0x02}; // bkcNewPage
|
||||
sepx(wd, 64, cont);
|
||||
sepx(wd, 128, cont);
|
||||
sepx(wd, 192, newPage);
|
||||
byte[] t = plcfSed(64, 128, 192);
|
||||
Sections s = Sections.read(t, 0, t.length, wd);
|
||||
// секции 0 и 1 — не последние: обе continuous считаются;
|
||||
// секция 2 — последняя: bkc в оценку не идёт
|
||||
assertEquals(2, s.continuousSectionEnds());
|
||||
}
|
||||
|
||||
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 put32(byte[] b, int off, int v) {
|
||||
b[off] = (byte) v;
|
||||
b[off + 1] = (byte) (v >>> 8);
|
||||
b[off + 2] = (byte) (v >>> 16);
|
||||
b[off + 3] = (byte) (v >>> 24);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package ru.pjandro.wordpdf.internal.doc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Юниты {@link SummaryInfo} на крафтовом PropertySetStream ([MS-OLEPS] §2.21):
|
||||
* реальные фикстуры смещение offset свойства (относительное vs абсолютное) не
|
||||
* различают — max(кэш, разрывы) маскирует, поэтому поток собирается вручную.
|
||||
*/
|
||||
class SummaryInfoTest {
|
||||
|
||||
/**
|
||||
* PropertySetStream: заголовок 0x30 (ByteOrder/Version/SysId/CLSID(16)/
|
||||
* NumPropertySets/FMTID0(16)/Offset0) + PropertySet (cb, NumProperties,
|
||||
* массив (pid, offset), VT_I4 + значение); offset свойства — относительно
|
||||
* начала PropertySet (§2.20).
|
||||
*/
|
||||
private static byte[] propertySet(int pagecount) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
out.write(new byte[] {(byte) 0xFF, (byte) 0xFE, 1, 0}); // ByteOrder, Version
|
||||
out.write(new byte[4]); // SystemIdentifier
|
||||
out.write(new byte[16]); // CLSID
|
||||
out.write(le32(1)); // NumPropertySets
|
||||
out.write(new byte[16]); // FMTID0 (SummaryInformation)
|
||||
out.write(le32(0x30)); // Offset0
|
||||
out.write(le32(8 + 8 + 8)); // cbPropertySet
|
||||
out.write(le32(1)); // NumProperties
|
||||
out.write(le32(0x0000000E)); // PIDSI_PAGECOUNT
|
||||
out.write(le32(8 + 8)); // offset — относительно начала PropertySet
|
||||
out.write(le32(3)); // VT_I4
|
||||
out.write(le32(pagecount));
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] le32(int v) {
|
||||
return new byte[] {(byte) v, (byte) (v >>> 8), (byte) (v >>> 16), (byte) (v >>> 24)};
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageCount_readFromRelativeOffset() throws Exception {
|
||||
assertEquals(42, SummaryInfo.pageCount(propertySet(42)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageCount_shortStream_returnsZero() {
|
||||
assertEquals(0, SummaryInfo.pageCount(new byte[4]));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageCount_offsetBeyondStream_returnsZero() throws Exception {
|
||||
byte[] s = propertySet(42);
|
||||
s[0x2C] = 0x7F; // Offset0 за концом потока
|
||||
s[0x2D] = 0x7F;
|
||||
assertEquals(0, SummaryInfo.pageCount(s));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageCount_truncatedProperty_returnsZero() throws Exception {
|
||||
byte[] s = propertySet(42);
|
||||
byte[] cut = new byte[s.length - 4];
|
||||
System.arraycopy(s, 0, cut, 0, cut.length);
|
||||
assertEquals(0, SummaryInfo.pageCount(cut));
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user