Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
feat(hwp): extend the document model for rendering fidelity
KnifeLemon89b4c322be13
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex c76957ad..ddade477 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -342,7 +342,13 @@ nested `<svg>`, CSS and text are resolved the same way.## HWPX writerFilee writes OWPML (HWPX) itself, so saving as HWPX needs no Hancom Office and shows no approval dialog.-Readers turn the source into a small document model (`Hwp/Hwpx/HwpxModel.cs`) and `HwpxWriter` writes the package:+Readers turn the source into a small document model (`Hwp/Hwpx/HwpxModel.cs`) and `HwpxWriter` writes the package.+The model also keeps what a renderer needs and the writers ignore (`Hwp/Hwpx/HwpxModel.Layout.cs`): line rules with+the source's meaning (Word's multiple and document grid, 한글's "between lines"), 한글's seven language slots and Word's+four run fonts, paragraph borders and line breaking, stored line layouts, crops, rotation, z-order, master pages,+polygons, curves and arcs (`HwpxReader.ReadForLayout` also keeps runs apart by that detail and reads master pages and+those shapes, which `Read` leaves out as before). `StyleResolver` turns what a document leaves to the+한글 style into concrete values. What the readers take over:- **DOCX** is read directly (`Hwp/Hwpx/Docx/DocxReader*.cs`) so the layout survives:- page size, orientation and margins per section; columns, also when they change mid-page;diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Drawing.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Drawing.csindex ea9e9f7a..c70003a5 100644--- a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Drawing.cs+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Drawing.cs@@ -28,8 +28,24 @@ internal sealed partial class DocxReadervar height = HwpxUnits.FromEmu(Long(extent, "cy") ?? 0);var anchor = anchored ? Anchor(container) : null;var data = container.Element(A + "graphic")?.Element(A + "graphicData");+ // Stacking order of floating objects (members of a group share the group's).+ var zOrder = anchored && Long(container, "relativeHeight") is { } height32 ? (int?)Math.Min(height32, int.MaxValue) : null;foreach (var inline in GraphicObjects(data?.Elements() ?? [], width, height, anchor, (0, 0, 1, 1)))+ {+ switch (inline)+ {+ case HImage image:+ image.ZOrder = zOrder;+ break;+ case HShape shape:+ shape.ZOrder = zOrder;+ break;+ case HTextBox box:+ box.ZOrder = zOrder;+ break;+ }yield return inline;+ }}}@@ -111,7 +127,29 @@ internal sealed partial class DocxReader{var blip = pic.Descendants(A + "blip").FirstOrDefault();var path = ExtractImage(Attr(blip, "embed", R));- return path is null ? null : new HImage(path) { Width = width > 0 ? width : null, Height = height > 0 ? height : null, Anchor = anchor };+ return path is null ? null : new HImage(path)+ {+ Width = width > 0 ? width : null,+ Height = height > 0 ? height : null,+ Anchor = anchor,+ Crop = Crop(pic.Descendants(A + "srcRect").FirstOrDefault()),+ Transform = Transform(pic.Element(Pic + "spPr")?.Element(A + "xfrm")),+ };+ }++ /// <summary>a:srcRect: the part of the picture cut away at each edge, in 1/1000 percent.</summary>+ private static HCrop? Crop(XElement? sourceRect)+ {+ double Edge(string name) => Math.Clamp((Long(sourceRect, name) ?? 0) / 100000.0, 0, 1);+ var crop = new HCrop(Edge("l"), Edge("t"), Edge("r"), Edge("b"));+ return sourceRect is null || crop.IsEmpty ? null : crop;+ }++ /// <summary>Rotation (a:xfrm rot, 1/60000 degree, clockwise) and mirroring; null when there is neither.</summary>+ private static HTransform? Transform(XElement? xfrm)+ {+ var transform = new HTransform((Long(xfrm, "rot") ?? 0) / 60000.0, Attr(xfrm, "flipH") is "1" or "true", Attr(xfrm, "flipV") is "1" or "true");+ return transform.IsIdentity ? null : transform;}/// <summary>A text box, or a rectangle / ellipse / line without text. Other geometries are skipped.</summary>@@ -162,6 +200,7 @@ internal sealed partial class DocxReaderCornerRatio = geometry is "roundRect" or "round1Rect" or "round2SameRect" or "flowChartAlternateProcess" ? 20 : 0,FlipHorizontal = Attr(xfrm, "flipH") is "1" or "true",FlipVertical = Attr(xfrm, "flipV") is "1" or "true",+ Transform = Transform(xfrm),};}@@ -183,6 +222,7 @@ internal sealed partial class DocxReader_ => HVerticalAlign.Top,},}.Build();+ box.Transform = Transform(spPr?.Element(A + "xfrm"));ReadTextBoxContent(content, box.Blocks);return box;}@@ -393,10 +433,12 @@ internal sealed partial class DocxReadervar width = HwpxUnits.ParseLength(style.GetValueOrDefault("width")) ?? 0;var height = HwpxUnits.ParseLength(style.GetValueOrDefault("height")) ?? 0;var anchor = style.GetValueOrDefault("position") == "absolute" ? VmlAnchor(shape, style) : null;+ var transform = VmlTransform(style);+ int? zOrder = anchor is not null && int.TryParse(style.GetValueOrDefault("z-index"), NumberStyles.Integer, CultureInfo.InvariantCulture, out var z) ? z : null;if (shape.Element(V + "imagedata") is { } imageData && ExtractImage(Attr(imageData, "id", R)) is { } path){- yield return new HImage(path) { Width = width > 0 ? width : null, Height = height > 0 ? height : null, Anchor = anchor };+ yield return new HImage(path) { Width = width > 0 ? width : null, Height = height > 0 ? height : null, Anchor = anchor, Transform = transform, ZOrder = zOrder };}else if (shape.Element(V + "textbox")?.Element(W + "txbxContent") is { } content){@@ -405,6 +447,7 @@ internal sealed partial class DocxReaderFill = VmlFill(shape),Line = VmlLine(shape),}.Build();+ (box.Transform, box.ZOrder) = (transform, zOrder);ReadTextBoxContent(content, box.Blocks);yield return box;}@@ -453,6 +496,8 @@ internal sealed partial class DocxReaderFill = kind == HShapeKind.Line ? null : VmlFill(shape),Line = VmlLine(shape),CornerRatio = shape.Name.LocalName == "roundrect" ? 20 : 0,+ Transform = transform,+ ZOrder = zOrder,};}}@@ -494,9 +539,23 @@ internal sealed partial class DocxReaderBold = font.GetValueOrDefault("font-weight") is { } weight ? weight == "bold" || int.TryParse(weight, out var w) && w >= 600 : format.Bold,Italic = font.GetValueOrDefault("font-style") is { } italic ? italic == "italic" : format.Italic,Color = color ?? format.Color,+ Layout = family is null || format.Layout is null ? format.Layout : format.Layout with { WordFonts = new HWordFonts(family, family, family, family) },});}+ /// <summary>VML rotation (style "rotation", degrees clockwise) and mirroring ("flip: x y"); null when there is neither.</summary>+ private static HTransform? VmlTransform(Dictionary<string, string> style)+ {+ var rotation = style.GetValueOrDefault("rotation")?.TrimEnd('f', 'd') is { } value &&+ double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var degrees) ? degrees : 0;+ // "fd" values are in 1/65536 degree.+ if (style.GetValueOrDefault("rotation")?.EndsWith("fd", StringComparison.Ordinal) == true)+ rotation /= 65536;+ var flip = style.GetValueOrDefault("flip")?.Split(' ', StringSplitOptions.RemoveEmptyEntries) ?? [];+ var transform = new HTransform(rotation, flip.Contains("x"), flip.Contains("y"));+ return transform.IsIdentity ? null : transform;+ }+private static string? VmlFill(XElement shape) =>(string?)shape.Attribute("filled") is "f" or "false" ? null : VmlColor((string?)shape.Attribute("fillcolor")) ?? "#FFFFFF";diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Styles.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Styles.csindex d944fa69..328980fe 100644--- a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Styles.cs+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Styles.cs@@ -35,10 +35,20 @@ internal sealed partial class DocxReaderpublic int? Ilvl;public List<(int Position, string Kind, string Leader)> Tabs = [];+ /// <summary>Paragraph border edges (w:pBdr: top, left, bottom, right, between) with their distance to the text in points.</summary>+ public Dictionary<string, (HBorder Border, int Space)> Borders = [];++ /// <summary>Paragraph background (w:shd); null = none.</summary>+ public string? Shading;++ /// <summary>East Asian typography switches (w:kinsoku, w:wordWrap, w:overflowPunct, w:topLinePunct, w:autoSpaceDE / DN).</summary>+ public bool? Kinsoku, WordWrap, OverflowPunct, TopLinePunct, AutoSpaceDE, AutoSpaceDN;+public ParaProps Clone(){var copy = (ParaProps)MemberwiseClone();copy.Tabs = [.. Tabs];+ copy.Borders = new Dictionary<string, (HBorder, int)>(Borders);return copy;}@@ -86,6 +96,24 @@ internal sealed partial class DocxReaderPageBreakBefore = Toggle(pPr, "pageBreakBefore") ?? PageBreakBefore;WidowControl = Toggle(pPr, "widowControl") ?? WidowControl;SnapToGrid = Toggle(pPr, "snapToGrid") ?? SnapToGrid;+ Kinsoku = Toggle(pPr, "kinsoku") ?? Kinsoku;+ WordWrap = Toggle(pPr, "wordWrap") ?? WordWrap;+ OverflowPunct = Toggle(pPr, "overflowPunct") ?? OverflowPunct;+ TopLinePunct = Toggle(pPr, "topLinePunct") ?? TopLinePunct;+ AutoSpaceDE = Toggle(pPr, "autoSpaceDE") ?? AutoSpaceDE;+ AutoSpaceDN = Toggle(pPr, "autoSpaceDN") ?? AutoSpaceDN;+ foreach (var edge in pPr.Element(W + "pBdr")?.Elements() ?? [])+ {+ var side = edge.Name.LocalName switch+ {+ "start" => "left",+ "end" => "right",+ var other => other,+ };+ Borders[side] = (Border(edge), Twips(edge, "space") ?? 0);+ }+ if (pPr.Element(W + "shd") is { } shd)+ Shading = ShadingColor(shd);if (pPr.Element(W + "outlineLvl") is { } outline && int.TryParse(Val(outline), out var level))OutlineLevel = level;if (pPr.Element(W + "numPr") is { } numPr)@@ -116,6 +144,12 @@ internal sealed partial class DocxReaderpublic string? VertAlign, Color, Highlight, Shade, Ascii, EastAsia, AsciiTheme, EastAsiaTheme;public int? Size, Spacing;+ /// <summary>The four Word fonts one by one (Ascii above falls back to hAnsi for the writers) and the hint.</summary>+ public string? AsciiOnly, AsciiOnlyTheme, HighAnsi, HighAnsiTheme, ComplexScript, ComplexScriptTheme, Hint;++ /// <summary>w:w (percent) and w:position (half points).</summary>+ public int? Scale, Position;+public RunProps Clone() => (RunProps)MemberwiseClone();public void Apply(XElement? rPr)@@ -140,8 +174,26 @@ internal sealed partial class DocxReaderSize = halfPoints;if (rPr.Element(W + "spacing") is { } spacing && int.TryParse(Val(spacing), out var twips))Spacing = twips;+ if (rPr.Element(W + "w") is { } scale && int.TryParse(Val(scale), out var percent))+ Scale = percent;+ if (rPr.Element(W + "position") is { } position && int.TryParse(Val(position), out var shift))+ Position = shift;if (rPr.Element(W + "rFonts") is { } fonts){+ if (Attr(fonts, "ascii") is { } asciiOnly)+ (AsciiOnly, AsciiOnlyTheme) = (asciiOnly, null);+ if (Attr(fonts, "asciiTheme") is { } asciiOnlyTheme)+ AsciiOnlyTheme = asciiOnlyTheme;+ if (Attr(fonts, "hAnsi") is { } highAnsi)+ (HighAnsi, HighAnsiTheme) = (highAnsi, null);+ if (Attr(fonts, "hAnsiTheme") is { } highAnsiTheme)+ HighAnsiTheme = highAnsiTheme;+ if (Attr(fonts, "cs") is { } complex)+ (ComplexScript, ComplexScriptTheme) = (complex, null);+ if (Attr(fonts, "cstheme") is { } complexTheme)+ ComplexScriptTheme = complexTheme;+ Hint = Attr(fonts, "hint") ?? Hint;+// A theme reference wins over an explicit name in Word, so a later explicit name clears it.if ((Attr(fonts, "ascii") ?? Attr(fonts, "hAnsi")) is { } ascii)(Ascii, AsciiTheme) = (ascii, null);@@ -183,6 +235,7 @@ internal sealed partial class DocxReaderprivate string? _defaultParagraphStyle;private string? _defaultTableStyle;private (string? Latin, string? EastAsian) _minorFont, _majorFont;+ private string? _minorComplexFont, _majorComplexFont;private void LoadStyles(Part? part){@@ -232,6 +285,8 @@ internal sealed partial class DocxReader}_minorFont = Read("minorFont");_majorFont = Read("majorFont");+ _minorComplexFont = NullIfEmpty(Attr(fonts?.Element(A + "minorFont")?.Element(A + "cs"), "typeface"));+ _majorComplexFont = NullIfEmpty(Attr(fonts?.Element(A + "majorFont")?.Element(A + "cs"), "typeface"));}private void LoadNumbering(Part? part)@@ -401,7 +456,44 @@ internal sealed partial class DocxReader"underscore" or "heavy" => "SOLID",_ => "NONE",}))- .ToList());+ .ToList(),+ Layout: ParaLayout(p));+ }++ /// <summary>+ /// The paragraph's rendering detail in Word's terms: the line rule as Word means it (see #280; LineSpacing above+ /// holds its 한글 approximation), borders and shading, and the East Asian line breaking switches with Word's defaults.+ /// </summary>+ private static HParaLayout ParaLayout(ParaProps p)+ {+ var lineHeight = p.LineRule switch+ {+ "exact" when p.Line is { } exact => new HLineHeight(HLineHeightRule.Exact, HwpxUnits.FromTwips(exact)),+ "atLeast" when p.Line is { } atLeast => new HLineHeight(HLineHeightRule.AtLeast, HwpxUnits.FromTwips(atLeast)),+ _ => new HLineHeight(HLineHeightRule.Multiple, p.Line ?? 240),+ };++ var border = HParaBorder.None;+ if (p.Borders.Count > 0 || p.Shading is not null)+ {+ (HBorder Border, int Space) Edge(string side) => p.Borders.GetValueOrDefault(side, (HBorder.None, 0));+ // w:space is in points; Word joins consecutive paragraphs with the same borders into one box.+ border = new HParaBorder(+ new HBorders(Edge("left").Border, Edge("right").Border, Edge("top").Border, Edge("bottom").Border),+ p.Shading,+ new HInsets(Edge("left").Space * 100, Edge("right").Space * 100, Edge("top").Space * 100, Edge("bottom").Space * 100),+ Connect: true,+ Between: p.Borders.TryGetValue("between", out var between) && between.Border.Style != HBorderStyle.None ? between.Border : null);+ }++ var breaking = new HLineBreaking(+ Latin: p.WordWrap == false ? HLatinBreak.BreakWord : HLatinBreak.KeepWord,+ Kinsoku: p.Kinsoku ?? true,+ OverflowPunctuation: p.OverflowPunct ?? true,+ CompressPunctuation: p.TopLinePunct ?? false,+ AutoSpaceLatin: p.AutoSpaceDE ?? true,+ AutoSpaceDigits: p.AutoSpaceDN ?? true);+ return new HParaLayout(lineHeight, border, breaking, SnapToGrid: p.SnapToGrid ?? true);}private HCharFormat CharFormat(RunProps r)@@ -421,7 +513,27 @@ internal sealed partial class DocxReaderColor: r.Color ?? "#000000",Shade: r.Highlight ?? r.Shade,// Word letter spacing is absolute (twips); 한글's is a percentage of the font size.- Spacing: r.Spacing is { } twips and not 0 ? Math.Clamp((int)Math.Round(twips * 10.0 / size), -50, 50) : 0);+ Spacing: r.Spacing is { } twips and not 0 ? Math.Clamp((int)Math.Round(twips * 10.0 / size), -50, 50) : 0,+ // The exact values for layout: the four fonts, scale, spacing and position as Word means them.+ Layout: new HCharLayout(+ WordFonts: WordFonts(r),+ Scale: r.Scale ?? 100,+ LetterSpacing: HwpxUnits.FromTwips(r.Spacing ?? 0),+ Position: (r.Position ?? 0) * 50));+ }++ /// <summary>Word's four run fonts, theme references resolved.</summary>+ private HWordFonts WordFonts(RunProps r)+ {+ string? Latin(string? theme, string? name) => theme is null ? name+ : theme.StartsWith("major", StringComparison.Ordinal) ? _majorFont.Latin ?? name : _minorFont.Latin ?? name;+ var complex = r.ComplexScriptTheme is { } theme+ ? (theme.StartsWith("major", StringComparison.Ordinal) ? _majorComplexFont : _minorComplexFont) ?? r.ComplexScript+ : r.ComplexScript;+ var eastAsian = r.EastAsiaTheme is { } eastAsiaTheme+ ? (eastAsiaTheme.StartsWith("major", StringComparison.Ordinal) ? _majorFont.EastAsian : _minorFont.EastAsian) ?? r.EastAsia+ : r.EastAsia;+ return new HWordFonts(Latin(r.AsciiOnlyTheme, r.AsciiOnly), Latin(r.HighAnsiTheme, r.HighAnsi), eastAsian, complex, r.Hint);}private (string? Latin, string? EastAsian) Fonts(RunProps r)diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Tables.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Tables.csindex 8db41c84..d5eaf6e4 100644--- a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Tables.cs+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.Tables.cs@@ -1,5 +1,6 @@// DOCX tables: grid column widths, merged cells (gridSpan / vMerge), borders from the table style, the table and-// each cell, cell shading, cell margins, vertical alignment, row heights and repeated header rows.+// each cell, cell shading, cell margins, vertical alignment, row heights, repeated header rows and rows that do not+// split across pages.using System.Xml.Linq;@@ -55,7 +56,11 @@ internal sealed partial class DocxReader{var tr = rows[r];var trPr = tr.Element(W + "trPr");- var row = new HRow { Header = trPr?.Element(W + "tblHeader") is { } header && Val(header) is not ("0" or "false") };+ var row = new HRow+ {+ Header = trPr?.Element(W + "tblHeader") is { } header && Val(header) is not ("0" or "false"),+ CantSplit = trPr is not null && Toggle(trPr, "cantSplit") == true,+ };if (trPr?.Element(W + "trHeight") is { } height && Twips(height, "val") is > 0 and var h)row.Height = HwpxUnits.FromTwips(h);diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.csindex 513f3967..8a3f316c 100644--- a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs@@ -158,7 +158,8 @@ internal sealed partial class DocxReaderLoadTheme(theme);LoadThemeColors(theme);LoadNumbering(RelatedPart(main, "/numbering"));- _evenAndOddHeaders = RelatedPart(main, "/settings")?.Xml.Root?.Element(W + "evenAndOddHeaders") is { } evenOdd && Val(evenOdd) is not ("0" or "false");+ var settings = RelatedPart(main, "/settings")?.Xml.Root;+ _evenAndOddHeaders = settings?.Element(W + "evenAndOddHeaders") is { } evenOdd && Val(evenOdd) is not ("0" or "false");_footnotesPart = RelatedPart(main, "/footnotes");_endnotesPart = RelatedPart(main, "/endnotes");foreach (var note in _footnotesPart?.Xml.Root?.Elements(W + "footnote") ?? [])@@ -167,6 +168,7 @@ internal sealed partial class DocxReader_endnotes[Attr(note, "id") ?? ""] = note;var document = new HDocument { Title = Title() };+ Kinsoku(settings, document);var body = main.Xml.Root?.Element(W + "body") ?? throw new InvalidDataException("word/document.xml has no body.");// A section ends with the paragraph whose properties hold its sectPr; the last one is the body's own sectPr.@@ -224,7 +226,7 @@ internal sealed partial class DocxReaderreturn;}- var section = new HSection { Page = page, Columns = columns };+ var section = new HSection { Page = page, Columns = columns, Grid = Grid(sectPr) };section.Blocks.AddRange(blocks);// Sections without their own header or footer reference inherit the previous section's.@@ -339,7 +341,45 @@ internal sealed partial class DocxReadervar natural = size * WordLineToHwpPercent / 100.0; // 1/100 pt = HWPUNITvar lines = Math.Max(1, Math.Ceiling(natural / cell));var multiple = (props.Line ?? 240) / 240.0;- paragraph.Format = paragraph.Format with { LineSpacing = new HLineSpacing(HLineSpacingKind.AtLeast, (int)Math.Round(lines * cell * multiple)) };+ // The line rule itself stays Word's multiple, with the grid its lines snap to.+ var layout = paragraph.Format.Layout ?? new HParaLayout();+ paragraph.Format = paragraph.Format with+ {+ LineSpacing = new HLineSpacing(HLineSpacingKind.AtLeast, (int)Math.Round(lines * cell * multiple)),+ Layout = layout with { LineHeight = (layout.LineHeight ?? new HLineHeight(HLineHeightRule.Multiple, props.Line ?? 240)) with { GridPitch = cell } },+ };+ }++ /// <summary>The section's document grid (w:docGrid); null without one.</summary>+ private static HDocumentGrid? Grid(XElement? sectPr)+ {+ var grid = sectPr?.Element(W + "docGrid");+ var kind = Attr(grid, "type") switch+ {+ "lines" => HGridKind.Lines,+ "linesAndChars" => HGridKind.LinesAndChars,+ "snapToChars" => HGridKind.SnapToChars,+ _ => HGridKind.None,+ };+ return kind == HGridKind.None ? null : new HDocumentGrid(kind, HwpxUnits.FromTwips(Twips(grid, "linePitch") ?? 0), CharSpace: Twips(grid, "charSpace") ?? 0);+ }++ /// <summary>Custom East Asian line breaking characters of the document (settings: w:noLineBreaksBefore / After).</summary>+ private static void Kinsoku(XElement? settings, HDocument document)+ {+ var rules = new Dictionary<string, (string? Start, string? End)>();+ foreach (var element in settings?.Elements() ?? [])+ {+ var before = element.Name == W + "noLineBreaksBefore";+ if (!before && element.Name != W + "noLineBreaksAfter")+ continue;+ var language = Attr(element, "lang") ?? "";+ var (start, end) = rules.GetValueOrDefault(language);+ // "No line break before" a character: it cannot start a line; "after": it cannot end one.+ rules[language] = before ? (Val(element), end) : (start, Val(element));+ }+ foreach (var (language, (start, end)) in rules)+ document.Kinsoku.Add(new HKinsoku(language.Length > 0 ? language : null, start, end));}private static int? MaxFontSize(IEnumerable<HInline> inlines)diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.Layout.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.Layout.csnew file mode 100644index 00000000..7f45d5b1--- /dev/null+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.Layout.cs@@ -0,0 +1,361 @@+// Rendering detail of the document model: what a layout engine needs and the writers do not write.+//+// Values keep the meaning the source gave them: a Word "multiple" line rule stays a multiple of the font's line+// height instead of becoming a 한글 percentage, 한글's seven language slots stay seven, Word's four run fonts stay+// four. The writers keep using the members of HCharFormat / HParaFormat that hold the 한글 approximations, so+// nothing here changes a written file. Lengths are HWPUNIT, sizes 1/100 pt, like the rest of the model.++namespace Filee.Engines.Hwp.Hwpx;++// ───────────────────────── Characters ─────────────────────────++/// <summary>Rendering detail of a character format (see <see cref="HCharFormat.Layout"/>).</summary>+/// <param name="Slots">한글's per-language properties (fonts, 장평, 자간, 상대 크기, 글자 위치).</param>+/// <param name="WordFonts">Word's run fonts by character class.</param>+/// <param name="Scale">Word character scale (w:w) in percent: the width of every glyph, like 한글's 장평.</param>+/// <param name="LetterSpacing">Word letter spacing (w:spacing) as an absolute distance added after each character.</param>+/// <param name="Position">Word baseline shift (w:position): positive raises the text.</param>+internal sealed record HCharLayout(+ HLanguageSlots? Slots = null,+ HWordFonts? WordFonts = null,+ int? Scale = null,+ int? LetterSpacing = null,+ int? Position = null)+{+ /// <summary>This layout with the members it leaves open taken from <paramref name="baseline"/>.</summary>+ public HCharLayout Over(HCharLayout? baseline) => baseline is null ? this : new HCharLayout(+ Slots is null ? baseline.Slots : Slots.Over(baseline.Slots),+ WordFonts ?? baseline.WordFonts,+ Scale ?? baseline.Scale,+ LetterSpacing ?? baseline.LetterSpacing,+ Position ?? baseline.Position);+}++/// <summary>한글's seven language slots (글꼴 언어): each character takes the properties of the slot its script falls into.</summary>+internal enum HLanguage+{+ Hangul,+ Latin,+ Hanja,+ Japanese,+ Other,+ Symbol,+ User,+}++/// <summary>Font and spacing of one language slot; null members are left to the style.</summary>+/// <param name="Ratio">장평: glyph width in percent.</param>+/// <param name="Spacing">자간: extra space in percent of the font size (negative = tighter).</param>+/// <param name="RelativeSize">상대 크기: size in percent of the run's font size.</param>+/// <param name="Offset">글자 위치: baseline shift in percent of the font size (negative = up).</param>+internal readonly record struct HSlotFormat(string? Font = null, int? Ratio = null, int? Spacing = null, int? RelativeSize = null, int? Offset = null)+{+ /// <summary>This slot with the members it leaves open taken from <paramref name="baseline"/>.</summary>+ public HSlotFormat Over(HSlotFormat baseline) => new(+ Font ?? baseline.Font, Ratio ?? baseline.Ratio, Spacing ?? baseline.Spacing, RelativeSize ?? baseline.RelativeSize, Offset ?? baseline.Offset);+}++/// <summary>The seven slots of a 한글 character shape.</summary>+internal sealed record HLanguageSlots(+ HSlotFormat Hangul, HSlotFormat Latin, HSlotFormat Hanja, HSlotFormat Japanese, HSlotFormat Other, HSlotFormat Symbol, HSlotFormat User)+{+ public static readonly HLanguage[] Languages = Enum.GetValues<HLanguage>();++ /// <summary>The same properties in every slot.</summary>+ public static HLanguageSlots All(HSlotFormat slot) => new(slot, slot, slot, slot, slot, slot, slot);++ public HSlotFormat this[HLanguage language] => language switch+ {+ HLanguage.Hangul => Hangul,+ HLanguage.Latin => Latin,+ HLanguage.Hanja => Hanja,+ HLanguage.Japanese => Japanese,+ HLanguage.Other => Other,+ HLanguage.Symbol => Symbol,+ _ => User,+ };++ public HLanguageSlots With(HLanguage language, HSlotFormat slot) => language switch+ {+ HLanguage.Hangul => this with { Hangul = slot },+ HLanguage.Latin => this with { Latin = slot },+ HLanguage.Hanja => this with { Hanja = slot },+ HLanguage.Japanese => this with { Japanese = slot },+ HLanguage.Other => this with { Other = slot },+ HLanguage.Symbol => this with { Symbol = slot },+ _ => this with { User = slot },+ };++ /// <summary>Every slot with the members it leaves open taken from <paramref name="baseline"/>.</summary>+ public HLanguageSlots Over(HLanguageSlots? baseline)+ {+ if (baseline is null)+ return this;+ var result = this;+ foreach (var language in Languages)+ result = result.With(language, this[language].Over(baseline[language]));+ return result;+ }+}++/// <summary>+/// Word's run fonts (w:rFonts): ASCII characters, other Latin (high ANSI), East Asian and complex-script text; the+/// hint says which font ambiguous characters (quotes, dashes) take. Theme references are resolved to names.+/// </summary>+internal sealed record HWordFonts(string? Ascii, string? HighAnsi, string? EastAsia, string? ComplexScript, string? Hint = null);++// ───────────────────────── Paragraphs ─────────────────────────++/// <summary>Rendering detail of a paragraph format (see <see cref="HParaFormat.Layout"/>).</summary>+/// <param name="LineHeight">The line rule with the source's meaning (the writers use <see cref="HParaFormat.LineSpacing"/>).</param>+/// <param name="Border">Border and background; <see cref="HParaBorder.None"/> = none, null = left to the style.</param>+/// <param name="SnapToGrid">Lines follow the section's line grid (한글 "줄 격자 사용", Word w:snapToGrid).</param>+/// <param name="FontLineHeight">한글 "글꼴에 어울리는 줄 높이": line height from the font's own metrics.</param>+internal sealed record HParaLayout(+ HLineHeight? LineHeight = null,+ HParaBorder? Border = null,+ HLineBreaking? Breaking = null,+ bool? SnapToGrid = null,+ bool? FontLineHeight = null)+{+ /// <summary>This layout with the members it leaves open taken from <paramref name="baseline"/>.</summary>+ public HParaLayout Over(HParaLayout? baseline) => baseline is null ? this : new HParaLayout(+ LineHeight ?? baseline.LineHeight,+ Border ?? baseline.Border,+ Breaking is null ? baseline.Breaking : Breaking.Over(baseline.Breaking),+ SnapToGrid ?? baseline.SnapToGrid,+ FontLineHeight ?? baseline.FontLineHeight);+}++internal enum HLineHeightRule+{+ /// <summary>한글 percent of the font size (100 = the size itself; 한글's default is 160).</summary>+ Percent,++ /// <summary>Word "multiple" (w:lineRule="auto"): <c>Value</c> in 1/240 of the font's own line height (240 = single).</summary>+ Multiple,++ /// <summary>Exactly <c>Value</c> high (한글 FIXED, Word exact).</summary>+ Exact,++ /// <summary>At least <c>Value</c> high (한글 AT_LEAST, Word atLeast).</summary>+ AtLeast,++ /// <summary>한글 "여백만 지정" (BETWEEN_LINES): the line's own height plus <c>Value</c>.</summary>+ BetweenLines,+}++/// <summary>A line height rule as the source states it.</summary>+/// <param name="GridPitch">+/// Pitch of the document grid the lines snap to (Word: each line takes a whole number of grid lines), 0 = none.+/// Set by the reader where the source snaps this paragraph.+/// </param>+internal readonly record struct HLineHeight(HLineHeightRule Rule, int Value, int GridPitch = 0)+{+ /// <summary>The rule a writer-side <see cref="HLineSpacing"/> stands for, when the source gave no other.</summary>+ public static HLineHeight From(HLineSpacing spacing) => spacing.Kind switch+ {+ HLineSpacingKind.Fixed => new HLineHeight(HLineHeightRule.Exact, spacing.Value),+ HLineSpacingKind.AtLeast => new HLineHeight(HLineHeightRule.AtLeast, spacing.Value),+ _ => new HLineHeight(HLineHeightRule.Percent, spacing.Value),+ };+}++/// <summary>Border and background of a paragraph.</summary>+/// <param name="Offsets">Distance between the text and each border line.</param>+/// <param name="Connect">Consecutive paragraphs with the same border share one box (한글 "문단 테두리 연결"; Word always).</param>+/// <param name="IgnoreMargin">The box spans the column, not just the paragraph's indents (한글 "문단 여백 무시").</param>+/// <param name="Between">Line between consecutive paragraphs of one box (Word w:between); null = none.</param>+internal sealed record HParaBorder(HBorders Borders, string? Fill, HInsets Offsets, bool Connect = false, bool IgnoreMargin = false, HBorder? Between = null)+{+ public static readonly HParaBorder None = new(HBorders.Empty, null, default);++ public bool IsVisible => Fill is not null || Between is { Style: not HBorderStyle.None } ||+ new[] { Borders.Left, Borders.Right, Borders.Top, Borders.Bottom }.Any(b => b.Style != HBorderStyle.None);+}++/// <summary>Where lines may break and how they are fitted. Null members are left to the style (or the default rules).</summary>+/// <param name="Latin">Latin words: kept whole (어절), hyphenated or broken anywhere (한글 breakLatinWord, Word w:wordWrap).</param>+/// <param name="NonLatin">Korean words: kept whole (어절) or broken at any syllable (글자) (한글 breakNonLatinWord).</param>+/// <param name="LineWrap">한글 lineWrap: wrap, squeeze the line, or keep it on one line.</param>+/// <param name="Kinsoku">East Asian line start / end rules apply (Word w:kinsoku; 한글 applies its 금칙 characters).</param>+/// <param name="OverflowPunctuation">Punctuation may hang past the line end (Word w:overflowPunct).</param>+/// <param name="CompressPunctuation">Punctuation at the line start is compressed (Word w:topLinePunct).</param>+/// <param name="AutoSpaceLatin">Space between East Asian and Latin text (한글 autoSpacing eAsianEng, Word w:autoSpaceDE).</param>+/// <param name="AutoSpaceDigits">Space between East Asian text and digits (한글 eAsianNum, Word w:autoSpaceDN).</param>+/// <param name="Condense">한글 "최소 공백": how far spaces may shrink to fit a line, in percent.</param>+internal sealed record HLineBreaking(+ HLatinBreak? Latin = null,+ HNonLatinBreak? NonLatin = null,+ HLineWrap? LineWrap = null,+ bool? Kinsoku = null,+ bool? OverflowPunctuation = null,+ bool? CompressPunctuation = null,+ bool? AutoSpaceLatin = null,+ bool? AutoSpaceDigits = null,+ int? Condense = null)+{+ /// <summary>These settings with the members they leave open taken from <paramref name="baseline"/>.</summary>+ public HLineBreaking Over(HLineBreaking? baseline) => baseline is null ? this : new HLineBreaking(+ Latin ?? baseline.Latin, NonLatin ?? baseline.NonLatin, LineWrap ?? baseline.LineWrap, Kinsoku ?? baseline.Kinsoku,+ OverflowPunctuation ?? baseline.OverflowPunctuation, CompressPunctuation ?? baseline.CompressPunctuation,+ AutoSpaceLatin ?? baseline.AutoSpaceLatin, AutoSpaceDigits ?? baseline.AutoSpaceDigits, Condense ?? baseline.Condense);+}++internal enum HLatinBreak+{+ KeepWord,+ Hyphenation,+ BreakWord,+}++internal enum HNonLatinBreak+{+ KeepWord,+ BreakWord,+}++internal enum HLineWrap+{+ Break,+ Squeeze,+ Keep,+}++/// <summary>Custom East Asian line breaking characters for a language (Word w:noLineBreaksBefore / After).</summary>+/// <param name="Language">Language tag ("ja-JP", "zh-CN" ...); null = every language.</param>+/// <param name="NotAtLineStart">Characters that may not start a line.</param>+/// <param name="NotAtLineEnd">Characters that may not end a line.</param>+internal sealed record HKinsoku(string? Language, string? NotAtLineStart, string? NotAtLineEnd);++/// <summary>+/// Line layout stored in the file (HWPX hp:linesegarray), one segment per line part. A paragraph that a table splits+/// in the model keeps the array on its first part, with text positions counted over the whole stored paragraph.+/// </summary>+/// <param name="Estimated">The values were estimated by Filee, not laid out by 한글, so they must not be trusted.</param>+internal sealed record HLineLayout(IReadOnlyList<HLineSegment> Segments, bool Estimated);++/// <summary>One stored line (all lengths HWPUNIT).</summary>+/// <param name="TextPosition">First character of the line in the paragraph's text.</param>+/// <param name="VerticalPosition">Top of the line from the top of the paragraph list (column, cell, ...).</param>+/// <param name="VerticalSize">Height of the line including its line spacing share.</param>+/// <param name="TextHeight">Height of the text itself.</param>+/// <param name="Baseline">Distance from the top of the line to its baseline.</param>+/// <param name="Spacing">Space after the line (line spacing).</param>+/// <param name="HorizontalPosition">Start of the line part from the column edge.</param>+/// <param name="HorizontalSize">Width of the line part.</param>+/// <param name="Flags">한글's line flags (first line of a page or column, empty segment, ...).</param>+internal readonly record struct HLineSegment(+ int TextPosition, int VerticalPosition, int VerticalSize, int TextHeight, int Baseline, int Spacing,+ int HorizontalPosition, int HorizontalSize, int Flags);++// ───────────────────────── Sections ─────────────────────────++internal enum HGridKind+{+ None,++ /// <summary>Lines snap to the line pitch.</summary>+ Lines,++ /// <summary>Lines snap to the line pitch and characters to the character pitch.</summary>+ LinesAndChars,++ /// <summary>Characters snap to the character pitch (Word snapToChars).</summary>+ SnapToChars,+}++/// <summary>A page grid.</summary>+/// <param name="LinePitch">Distance between grid lines (Word linePitch, 한글 lineGrid); 0 = none.</param>+/// <param name="CharPitch">Character pitch (한글 charGrid); 0 = none or derived from the font (Word).</param>+/// <param name="CharSpace">Word w:charSpace as stored: extra character pitch in 1/4096 pt over the default font size.</param>+internal sealed record HDocumentGrid(HGridKind Kind, int LinePitch, int CharPitch = 0, int CharSpace = 0);++internal enum HMasterPageKind+{+ Both,+ Even,+ Odd,++ /// <summary>The last page of the section.</summary>+ LastPage,++ /// <summary>The page <see cref="HMasterPage.PageNumber"/>.</summary>+ OptionalPage,+}++/// <summary>A 한글 master page (바탕쪽): paragraphs and objects drawn on every page it applies to.</summary>+internal sealed class HMasterPage(HMasterPageKind kind)+{+ public HMasterPageKind Kind { get; } = kind;++ /// <summary>Page of an <see cref="HMasterPageKind.OptionalPage"/> master page.</summary>+ public int PageNumber { get; set; }++ /// <summary>한글 "겹치기": drawn together with the other master pages of the section.</summary>+ public bool Duplicate { get; set; }++ /// <summary>한글 "앞으로 보내기": drawn in front of the body text.</summary>+ public bool Front { get; set; }++ public List<HBlock> Blocks { get; } = [];+}++// ───────────────────────── Tables and objects ─────────────────────────++/// <summary>How a table splits at the end of a page (OWPML hp:tbl pageBreak).</summary>+internal enum HTablePageBreak+{+ /// <summary>나누지 않음: the table moves to the next page whole.</summary>+ None,++ /// <summary>나눔: the table splits, inside rows too.</summary>+ Table,++ /// <summary>셀 단위로 나눔: the table splits between rows only.</summary>+ Cell,+}++/// <summary>Parts of a picture cut away at each edge, as fractions (0..1) of the source picture.</summary>+internal readonly record struct HCrop(double Left, double Top, double Right, double Bottom)+{+ public bool IsEmpty => Left == 0 && Top == 0 && Right == 0 && Bottom == 0;+}++/// <summary>+/// Rotation and mirroring of an object about its centre. <c>Rotation</c> is in degrees as the source stores it+/// (DrawingML measures clockwise; 한글's rotationInfo angle is kept as written).+/// </summary>+internal sealed record HTransform(double Rotation = 0, bool FlipHorizontal = false, bool FlipVertical = false)+{+ public bool IsIdentity => Rotation == 0 && !FlipHorizontal && !FlipVertical;+}++internal readonly record struct HPoint(int X, int Y);++/// <summary>+/// Outline of a polygon, curve or arc in the object's own coordinates, which span <c>Width</c> × <c>Height</c>+/// (한글 orgSz); the object is drawn scaled to its displayed size.+/// </summary>+/// <param name="Points">Polygon corners in order (한글 hc:pt).</param>+/// <param name="Segments">Curve segments as 한글 stores them (hp:seg): each a straight or curved piece from start to end.</param>+/// <param name="Arc">Arc of an ellipse (한글 hp:arc).</param>+internal sealed record HGeometry(int Width, int Height, IReadOnlyList<HPoint>? Points = null, IReadOnlyList<HCurveSegment>? Segments = null, HArc? Arc = null);++/// <summary>A piece of a 한글 curve; <c>Curve</c> is false for a straight piece (seg type LINE).</summary>+internal readonly record struct HCurveSegment(bool Curve, HPoint Start, HPoint End);++/// <summary>Arc of the ellipse around <c>Center</c> with axis end points <c>Axis1</c> and <c>Axis2</c> (한글 hp:arc).</summary>+internal readonly record struct HArc(HArcKind Kind, HPoint Center, HPoint Axis1, HPoint Axis2);++internal enum HArcKind+{+ /// <summary>The open arc.</summary>+ Normal,++ /// <summary>Closed through the centre.</summary>+ Pie,++ /// <summary>Closed by a straight line between the ends.</summary>+ Chord,+}diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.csindex e91c6298..e5bfab95 100644--- a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs@@ -1,7 +1,12 @@// In-memory document model between the readers (DOCX, Pandoc AST, plain text) and HwpxWriter.//// Lengths are HWPUNIT (1/7200 inch) and font sizes are 1/100 pt, like OWPML itself. A null format field means-// "inherit from the 한글 style" (the Pandoc reader only knows bold/italic/..., the DOCX reader knows everything).+// "inherit from the 한글 style" (the Pandoc reader only knows bold/italic/..., the DOCX reader knows everything);+// StyleResolver turns those into concrete values.+//+// Members the writers write describe the document in 한글's terms. What only a renderer needs, kept with the meaning+// the source gave it (Word line rules, 한글's language slots, stored line layout, crops, master pages ...), is in+// HwpxModel.Layout.cs; the writers ignore it, so adding it changes no written file.namespace Filee.Engines.Hwp.Hwpx;@@ -10,6 +15,9 @@ internal sealed class HDocument{public string? Title { get; set; }public List<HSection> Sections { get; } = [];++ /// <summary>Custom East Asian line breaking characters (Word settings), by language; empty = the usual rules.</summary>+ public List<HKinsoku> Kinsoku { get; } = [];}/// <summary>A run of pages sharing page setup, headers and footers (한글 "구역").</summary>@@ -29,6 +37,12 @@ internal sealed class HSection/// <summary>Restart page numbering at this number; null continues from the previous section.</summary>public int? StartPageNumber { get; set; }+ /// <summary>Line and character grid of the pages (Word's document grid, 한글's 줄/글자 격자); null = none.</summary>+ public HDocumentGrid? Grid { get; set; }++ /// <summary>Master pages (한글 바탕쪽) drawn behind the body of the section's pages.</summary>+ public List<HMasterPage> MasterPages { get; } = [];+public List<HBlock> Blocks { get; } = [];}@@ -88,6 +102,9 @@ internal sealed class HParagraph : HBlock/// <summary>Columns change here without a new page (DOCX continuous section break); null = unchanged.</summary>public HColumns? ColumnsChange { get; set; }+ /// <summary>Line layout stored with the paragraph (HWPX hp:linesegarray), or null.</summary>+ public HLineLayout? Lines { get; set; }+public List<HInline> Inlines { get; } = [];}@@ -137,6 +154,9 @@ internal sealed class HTable : HBlock/// </summary>public bool Tight { get; set; }+ /// <summary>How the table splits at the end of a page (한글 "쪽 경계에서"); null = the source does not say.</summary>+ public HTablePageBreak? PageBreak { get; set; }+public List<HBlock> Caption { get; } = [];}@@ -148,6 +168,9 @@ internal sealed class HRowpublic int? Height { get; set; }public bool Header { get; set; }++ /// <summary>The row is not split across pages (Word w:cantSplit).</summary>+ public bool CantSplit { get; set; }}internal sealed class HCell@@ -267,6 +290,15 @@ internal sealed class HImage(string path) : HInline/// <summary>Position for floating pictures; null = inline, moves with the text like a character.</summary>public HAnchor? Anchor { get; set; }++ /// <summary>Parts of the picture cut away; null = the whole picture.</summary>+ public HCrop? Crop { get; set; }++ /// <summary>Rotation and mirroring; null = none.</summary>+ public HTransform? Transform { get; set; }++ /// <summary>Stacking order among floating objects (higher is in front); null = document order.</summary>+ public int? ZOrder { get; set; }}/// <summary>A box with its own paragraphs (DOCX text box, 한글 글상자).</summary>@@ -275,6 +307,15 @@ internal sealed class HTextBox : HInlinepublic int Width { get; set; }public int Height { get; set; }public HAnchor? Anchor { get; set; }++ /// <summary>Rotation and mirroring; null = none.</summary>+ public HTransform? Transform { get; set; }++ /// <summary>Stacking order among floating objects (higher is in front); null = document order.</summary>+ public int? ZOrder { get; set; }++ /// <summary>Outline of a polygon, curve or arc holding the text (<see cref="Shape"/> says which); else null.</summary>+ public HGeometry? Geometry { get; set; }public string? Fill { get; set; }public HGradient? Gradient { get; set; }public HBorder Line { get; set; } = HBorder.Thin;@@ -295,15 +336,33 @@ internal enum HShapeKindRectangle,Ellipse,Line,++ /// <summary>한글 다각형: <see cref="HGeometry.Points"/>. Only in models read for layout (the writers have none).</summary>+ Polygon,++ /// <summary>한글 곡선: <see cref="HGeometry.Segments"/>. Only in models read for layout.</summary>+ Curve,++ /// <summary>한글 호: <see cref="HGeometry.Arc"/>. Only in models read for layout.</summary>+ Arc,}-/// <summary>A drawing without text: rectangle, ellipse or straight line.</summary>+/// <summary>A drawing without text: rectangle, ellipse or straight line (and, read for layout, polygon, curve or arc).</summary>internal sealed class HShape(HShapeKind kind) : HInline{public HShapeKind Kind { get; } = kind;public int Width { get; set; }public int Height { get; set; }public HAnchor? Anchor { get; set; }++ /// <summary>Rotation and mirroring as the source stores them; null = none.</summary>+ public HTransform? Transform { get; set; }++ /// <summary>Stacking order among floating objects (higher is in front); null = document order.</summary>+ public int? ZOrder { get; set; }++ /// <summary>Outline of a polygon, curve or arc; null for the other kinds.</summary>+ public HGeometry? Geometry { get; set; }public string? Fill { get; set; }public HGradient? Gradient { get; set; }public HBorder Line { get; set; } = HBorder.Thin;@@ -358,6 +417,11 @@ internal readonly record struct HLineSpacing(HLineSpacingKind Kind, int Value);/// <paramref name="Left"/> and <paramref name="Right"/> then name the start and the end side, as Word's w:bidi/// paragraphs do (Left aligns to the right edge). Written to DOCX only; HWPX has no right-to-left paragraphs./// </param>+/// <param name="LineSpacing">Line spacing in 한글's terms, as the writers write it (Word spacing converted).</param>+/// <param name="Layout">+/// Rendering detail the writers do not write (the source's own line rule, borders, line breaking ...). It takes no+/// part in equality: formats that differ only here are written alike. <see cref="SameLayout"/> compares it too.+/// </param>internal readonly record struct HParaFormat(HAlign? Align = null,int? Left = null,@@ -370,10 +434,15 @@ internal readonly record struct HParaFormat(bool? KeepLines = null,bool? WidowOrphan = null,IReadOnlyList<HTabStop>? Tabs = null,- bool? RightToLeft = null)+ bool? RightToLeft = null,+ HParaLayout? Layout = null){+ /// <summary>No member the writers write is set (<see cref="Layout"/> does not count).</summary>public bool IsEmpty => this == default;+ /// <summary>Equal, including <see cref="Layout"/>.</summary>+ public bool SameLayout(HParaFormat other) => Equals(other) && Equals(Layout, other.Layout);+// Tab stop lists compare by content so equal formats share one paraPr.public bool Equals(HParaFormat other) =>Align == other.Align && Left == other.Left && Right == other.Right && FirstLine == other.FirstLine &&@@ -402,6 +471,12 @@ internal readonly record struct HTabStop(int Position, HTabKind Kind, string Lea/// <param name="EastAsianFont">Font for Hangul / Hanja / Japanese text and CJK punctuation (the symbol slot).</param>/// <param name="Color">Text colour "#RRGGBB".</param>/// <param name="Shade">Background (highlight) colour "#RRGGBB".</param>+/// <param name="Spacing">Letter spacing in percent of the font size, as 한글 has it (Word's absolute spacing converted).</param>+/// <param name="Layout">+/// Rendering detail the writers do not write (한글's per-language slots, Word's four fonts and exact spacing). It+/// takes no part in equality, hashing or <see cref="ToString"/>: formats that differ only here are written alike.+/// <see cref="SameLayout"/> compares it too.+/// </param>internal readonly record struct HCharFormat(bool? Bold = null,bool? Italic = null,@@ -414,7 +489,29 @@ internal readonly record struct HCharFormat(string? EastAsianFont = null,string? Color = null,string? Shade = null,- int? Spacing = null)+ int? Spacing = null,+ HCharLayout? Layout = null){+ /// <summary>No member the writers write is set (<see cref="Layout"/> does not count).</summary>public bool IsEmpty => this == default;++ /// <summary>Equal, including <see cref="Layout"/>.</summary>+ public bool SameLayout(HCharFormat other) => Equals(other) && Equals(Layout, other.Layout);++ public bool Equals(HCharFormat other) =>+ Bold == other.Bold && Italic == other.Italic && Underline == other.Underline && Strike == other.Strike &&+ Superscript == other.Superscript && Subscript == other.Subscript && Size == other.Size &&+ Font == other.Font && EastAsianFont == other.EastAsianFont && Color == other.Color && Shade == other.Shade &&+ Spacing == other.Spacing;++ public override int GetHashCode() =>+ HashCode.Combine(HashCode.Combine(Bold, Italic, Underline, Strike, Superscript, Subscript), Size, Font, EastAsianFont, Color, Shade, Spacing);++ private bool PrintMembers(System.Text.StringBuilder builder)+ {+ builder.Append($"Bold = {Bold}, Italic = {Italic}, Underline = {Underline}, Strike = {Strike}, Superscript = {Superscript}, ")+ .Append($"Subscript = {Subscript}, Size = {Size}, Font = {Font}, EastAsianFont = {EastAsianFont}, Color = {Color}, ")+ .Append($"Shade = {Shade}, Spacing = {Spacing}");+ return true;+ }}diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Body.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Body.csindex 45182eb1..a74fc163 100644--- a/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Body.cs+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Body.cs@@ -63,11 +63,14 @@ internal sealed partial class HwpxReaderprivate readonly HParaFormat _format;private readonly int _heading;private readonly HListRef? _list;+ private readonly bool _keepLayoutRuns;private bool _afterTable;- public ParagraphBuilder(List<HBlock> output, List<OpenField> fields, HParaFormat format, int heading, HListRef? list)+ /// <param name="keepLayoutRuns">Texts are joined only when their layout detail is the same too (read for layout).</param>+ public ParagraphBuilder(List<HBlock> output, List<OpenField> fields, HParaFormat format, int heading, HListRef? list, bool keepLayoutRuns){_output = output;+ _keepLayoutRuns = keepLayoutRuns;_fields = fields;_format = format;_heading = heading;@@ -90,7 +93,7 @@ internal sealed partial class HwpxReaderif (text.Length == 0)return;var sink = Sink;- if (sink.Count > 0 && sink[^1] is HText last && last.Format == format)+ if (sink.Count > 0 && sink[^1] is HText last && (_keepLayoutRuns ? last.Format.SameLayout(format) : last.Format == format))sink[^1] = new HText(last.Text + text, format);elsesink.Add(new HText(text, format));@@ -149,7 +152,9 @@ internal sealed partial class HwpxReader{var shape = ParaShapeOf(Attr(p, "paraPrIDRef"));var (heading, list) = HeadingAndList(shape, Attr(p, "styleIDRef"));- var builder = new ParagraphBuilder(output, _fields, shape.Format, heading, list) { MarkFormat = CharFormat(null) };+ var builder = new ParagraphBuilder(output, _fields, shape.Format, heading, list, _forLayout) { MarkFormat = CharFormat(null) };+ var first = output.Count;+ HLineLayout? lines = null;builder.Current.PageBreakBefore = Flag(p, "pageBreak") || shape.PageBreakBefore;builder.Current.ColumnBreakBefore = Flag(p, "columnBreak");@@ -161,13 +166,26 @@ internal sealed partial class HwpxReaderRun(child, builder, section);break;case "linesegarray":- break; // layout cache, computed again by every reader+ lines = LineLayout(child);+ break;default:Skip(child);break;}}builder.Finish();+ // The stored lines belong to the whole 한글 paragraph: they go with its first part when a table splits it.+ if (lines is not null && output.Skip(first).OfType<HParagraph>().FirstOrDefault() is { } part)+ part.Lines = lines;+ }++ /// <summary>The layout cache 한글 stores with a paragraph (hp:linesegarray); null when it holds no lines.</summary>+ private HLineLayout? LineLayout(XElement array)+ {+ var segments = Children(array, "lineseg").Select(s => new HLineSegment(+ Int(s, "textpos"), Int(s, "vertpos"), Int(s, "vertsize"), Int(s, "textheight"), Int(s, "baseline"), Int(s, "spacing"),+ Int(s, "horzpos"), Int(s, "horzsize"), Int(s, "flags"))).ToList();+ return segments.Count == 0 ? null : new HLineLayout(segments, _estimatedLines);}/// <summary>@@ -472,7 +490,17 @@ internal sealed partial class HwpxReaderprivate HTable Table(XElement tbl){- var table = new HTable { ColumnCount = Math.Max(0, Int(tbl, "colCnt")) };+ var table = new HTable+ {+ ColumnCount = Math.Max(0, Int(tbl, "colCnt")),+ PageBreak = Attr(tbl, "pageBreak") switch+ {+ "NONE" => HTablePageBreak.None,+ "TABLE" => HTablePageBreak.Table,+ "CELL" => HTablePageBreak.Cell,+ _ => null,+ },+ };var pos = Child(tbl, "pos");if (pos is not null && !Flag(pos, "treatAsChar")){diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Header.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Header.csindex df8b6a0d..1902ffba 100644--- a/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Header.cs+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Header.cs@@ -97,12 +97,35 @@ internal sealed partial class HwpxReaderEastAsianFont: Face("HANGUL"),Color: Color(Attr(charPr, "textColor")) ?? "#000000",Shade: Color(Attr(charPr, "shadeColor")),- Spacing: Int(Child(charPr, "spacing"), "hangul"));+ Spacing: Int(Child(charPr, "spacing"), "hangul"),+ Layout: new HCharLayout(Slots(charPr, Face)));return _charFormats[id] = format;}+ /// <summary>The seven language slots of a character shape: font, 장평, 자간, 상대 크기 and 글자 위치 each.</summary>+ private static HLanguageSlots Slots(XElement charPr, Func<string, string?> face)+ {+ var (ratio, spacing, relSz, offset) = (Child(charPr, "ratio"), Child(charPr, "spacing"), Child(charPr, "relSz"), Child(charPr, "offset"));+ var slots = HLanguageSlots.All(default);+ foreach (var language in HLanguageSlots.Languages)+ {+ var name = language.ToString().ToUpperInvariant();+ var attribute = name.ToLowerInvariant();+ slots = slots.With(language, new HSlotFormat(+ face(name),+ Int(ratio, attribute, 100), Int(spacing, attribute), Int(relSz, attribute, 100), Int(offset, attribute)));+ }+ return slots;+ }++ /// <summary>The complete character format of a charPr id (for <see cref="StyleResolver"/>).</summary>+ internal HCharFormat CharacterShape(string id) => CharFormat(id);+// ───────────────────────── Paragraph shapes ─────────────────────────+ /// <summary>The complete paragraph format of a paraPr id (for <see cref="StyleResolver"/>).</summary>+ internal HParaFormat ParagraphShape(string id) => ParaShapeOf(id).Format;+private ParaShape ParaShapeOf(string? id){id ??= "0";@@ -114,7 +137,7 @@ internal sealed partial class HwpxReadervar heading = Child(paraPr, "heading");var breaks = Child(paraPr, "breakSetting");- var (intent, left, right, before, after, lineSpacing) = Spacing(paraPr);+ var (intent, left, right, before, after, lineSpacing, lineHeight) = Spacing(paraPr);var format = new HParaFormat(Align: Attr(Child(paraPr, "align"), "horizontal") switch{@@ -135,13 +158,46 @@ internal sealed partial class HwpxReaderKeepWithNext: Flag(breaks, "keepWithNext"),KeepLines: Flag(breaks, "keepLines"),WidowOrphan: Flag(breaks, "widowOrphan"),- Tabs: TabStops(Attr(paraPr, "tabPrIDRef")));+ Tabs: TabStops(Attr(paraPr, "tabPrIDRef")),+ Layout: ParaLayout(paraPr, breaks, lineHeight));var shape = new ParaShape(format, Attr(heading, "type") ?? "NONE", Attr(heading, "idRef"), Math.Max(0, Int(heading, "level")), Flag(breaks, "pageBreakBefore"));return _paraShapes[id] = shape;}+ /// <summary>Line rule, border, line breaking and grid settings of a paragraph shape.</summary>+ private HParaLayout ParaLayout(XElement paraPr, XElement? breaks, HLineHeight lineHeight)+ {+ var autoSpacing = Child(paraPr, "autoSpacing");+ var breaking = new HLineBreaking(+ Latin: Attr(breaks, "breakLatinWord") switch+ {+ "HYPHENATION" => HLatinBreak.Hyphenation,+ "BREAK_WORD" => HLatinBreak.BreakWord,+ _ => HLatinBreak.KeepWord,+ },+ NonLatin: Attr(breaks, "breakNonLatinWord") == "BREAK_WORD" ? HNonLatinBreak.BreakWord : HNonLatinBreak.KeepWord,+ LineWrap: Attr(breaks, "lineWrap") switch+ {+ "SQUEEZE" => HLineWrap.Squeeze,+ "KEEP" => HLineWrap.Keep,+ _ => HLineWrap.Break,+ },+ AutoSpaceLatin: Flag(autoSpacing, "eAsianEng"),+ AutoSpaceDigits: Flag(autoSpacing, "eAsianNum"),+ Condense: Int(paraPr, "condense"));++ var border = HParaBorder.None;+ if (Child(paraPr, "border") is { } element && BorderFill(Attr(element, "borderFillIDRef")) is (var borders, var fill))+ {+ border = new HParaBorder(borders, fill,+ new HInsets(Int(element, "offsetLeft"), Int(element, "offsetRight"), Int(element, "offsetTop"), Int(element, "offsetBottom")),+ Connect: Flag(element, "connect"), IgnoreMargin: Flag(element, "ignoreMargin"));+ }+ return new HParaLayout(lineHeight, border, breaking, SnapToGrid: Flag(paraPr, "snapToGrid", true), FontLineHeight: Flag(paraPr, "fontLineHeight"));+ }+/// <summary>Margins and line spacing from the switch branch with exact values, else the doubled ones halved.</summary>- private static (int Intent, int Left, int Right, int Before, int After, HLineSpacing LineSpacing) Spacing(XElement paraPr)+ private static (int Intent, int Left, int Right, int Before, int After, HLineSpacing LineSpacing, HLineHeight LineHeight) Spacing(XElement paraPr){XElement? margin = null, line = null;bool marginExact = false, lineExact = false;@@ -186,7 +242,14 @@ internal sealed partial class HwpxReader"BETWEEN_LINES" or "SPACE_ONLY" or "SPACEONLY" => new HLineSpacing(HLineSpacingKind.AtLeast, 1000 + length),_ => new HLineSpacing(HLineSpacingKind.Percent, value),};- return (Length("intent", "indent"), Length("left", "left"), Length("right", "right"), Length("prev", "prev"), Length("next", "next"), lineSpacing);+ var lineHeight = type switch+ {+ "FIXED" => new HLineHeight(HLineHeightRule.Exact, length),+ "AT_LEAST" or "MINIMUM" => new HLineHeight(HLineHeightRule.AtLeast, length),+ "BETWEEN_LINES" or "SPACE_ONLY" or "SPACEONLY" => new HLineHeight(HLineHeightRule.BetweenLines, length),+ _ => new HLineHeight(HLineHeightRule.Percent, value),+ };+ return (Length("intent", "indent"), Length("left", "left"), Length("right", "right"), Length("prev", "prev"), Length("next", "next"), lineSpacing, lineHeight);}// ───────────────────────── Tab stops ─────────────────────────diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Objects.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Objects.csindex fb7cd9db..2a611296 100644--- a/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Objects.cs+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxReader.Objects.cs@@ -1,6 +1,8 @@// Objects inside runs: pictures (inline or floating), rectangles / ellipses / lines, text boxes (drawing objects with// hp:drawText), groups (hp:container), equations and other objects that only carry text. Objects the model cannot-// hold (OLE, charts, video, form controls, free-form shapes without text) are skipped and counted.+// hold (OLE, charts, video, form controls, free-form shapes without text) are skipped and counted. Read for layout,+// polygons, curves and arcs become shapes with their outline. Every object keeps its rotation, mirroring and z-order,+// pictures their crop.using System.Globalization;using System.Xml.Linq;@@ -83,6 +85,8 @@ internal sealed partial class HwpxReader// A line runs corner to corner of its box; the end points say which corners.FlipHorizontal = Int(start, "x") > Int(end, "x"),FlipVertical = Int(start, "y") > Int(end, "y"),+ Transform = Transform(element),+ ZOrder = ZOrder(element),};break;}@@ -90,6 +94,17 @@ internal sealed partial class HwpxReaderforeach (var member in Group(element, placement))yield return member;break;+ case "polygon" or "curve" or "arc" when _forLayout:+ {+ var kind = element.Name.LocalName switch+ {+ "polygon" => HShapeKind.Polygon,+ "curve" => HShapeKind.Curve,+ _ => HShapeKind.Arc,+ };+ yield return Box(element, kind, placement, Geometry(element, kind, placement));+ break;+ }default:// Arcs, polygons, curves and connectors: only their text survives, in a box without outline.if (Child(element, "drawText") is not null)@@ -117,12 +132,66 @@ internal sealed partial class HwpxReaderWidth = placement.Width > 0 ? placement.Width : null,Height = placement.Height > 0 ? placement.Height : null,Anchor = placement.Anchor,+ Crop = Crop(pic),+ Transform = Transform(pic),+ ZOrder = ZOrder(pic),}: null;}- /// <summary>A rectangle or ellipse: a text box when it has text (hp:drawText), else a plain shape.</summary>- private HInline Box(XElement element, HShapeKind kind, Placement placement)+ /// <summary>+ /// The part of the picture shown: hp:imgClip is a rectangle in the picture's original size (hp:imgDim), which+ /// spans the whole picture when nothing is cut away. Files from Filee write zeros for both: no crop.+ /// </summary>+ private static HCrop? Crop(XElement pic)+ {+ var clip = Child(pic, "imgClip");+ var dimension = Child(pic, "imgDim");+ var (width, height) = (Int(dimension, "dimwidth"), Int(dimension, "dimheight"));+ var (right, bottom) = (Int(clip, "right"), Int(clip, "bottom"));+ if (clip is null || width <= 0 || height <= 0 || right <= 0 || bottom <= 0)+ return null;+ static double Fraction(int part, int whole) => Math.Clamp(part / (double)whole, 0, 1);+ var crop = new HCrop(Fraction(Int(clip, "left"), width), Fraction(Int(clip, "top"), height), Fraction(width - right, width), Fraction(height - bottom, height));+ return crop.IsEmpty ? null : crop;+ }++ /// <summary>Rotation (hp:rotationInfo) and mirroring (hp:flip) of a drawing object; null when it has neither.</summary>+ private static HTransform? Transform(XElement element)+ {+ var flip = Child(element, "flip");+ var transform = new HTransform(Int(Child(element, "rotationInfo"), "angle"), Flag(flip, "horizontal"), Flag(flip, "vertical"));+ return transform.IsIdentity ? null : transform;+ }++ private static int? ZOrder(XElement element) => Attr(element, "zOrder") is not null ? Int(element, "zOrder") : null;++ /// <summary>Outline of a polygon (hc:pt), curve (hp:seg) or arc (center, ax1, ax2) in its original size (hp:orgSz).</summary>+ private static HGeometry Geometry(XElement element, HShapeKind kind, Placement placement)+ {+ var original = Child(element, "orgSz");+ var (width, height) = (Int(original, "width", placement.Width), Int(original, "height", placement.Height));+ static HPoint Point(XElement? point) => new(Int(point, "x"), Int(point, "y"));+ return kind switch+ {+ HShapeKind.Polygon => new HGeometry(width, height, Points: Children(element, "pt").Select(Point).ToList()),+ HShapeKind.Curve => new HGeometry(width, height, Segments: Children(element, "seg")+ .Select(s => new HCurveSegment(Attr(s, "type") == "CURVE", new HPoint(Int(s, "x1"), Int(s, "y1")), new HPoint(Int(s, "x2"), Int(s, "y2"))))+ .ToList()),+ _ => new HGeometry(width, height, Arc: new HArc(Attr(element, "type") switch+ {+ "PIE" => HArcKind.Pie,+ "CHORD" => HArcKind.Chord,+ _ => HArcKind.Normal,+ }, Point(Child(element, "center")), Point(Child(element, "ax1")), Point(Child(element, "ax2")))),+ };+ }++ /// <summary>+ /// A rectangle or ellipse (read for layout also a polygon, curve or arc with its <paramref name="geometry"/>): a+ /// text box when it has text (hp:drawText), else a plain shape.+ /// </summary>+ private HInline Box(XElement element, HShapeKind kind, Placement placement, HGeometry? geometry = null){var line = LineShape(Child(element, "lineShape"));var (fill, gradient) = FillBrush(Child(element, "fillBrush"));@@ -138,6 +207,9 @@ internal sealed partial class HwpxReaderGradient = gradient,Line = line,CornerRatio = ratio,+ Transform = Transform(element),+ ZOrder = ZOrder(element),+ Geometry = geometry,};}@@ -154,6 +226,9 @@ internal sealed partial class HwpxReaderShape = kind,CornerRatio = ratio,VerticalAlign = VerticalAlign(Attr(subList, "vertAlign")),+ Transform = Transform(element),+ ZOrder = ZOrder(element),+ Geometry = geometry,};if (margin is not null)box.Padding = new HInsets(Int(margin, "left"), Int(margin, "right"), Int(margin, "top"), Int(margin, "bottom"));diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxReader.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxReader.csindex e6b14789..e88e25a1 100644--- a/src/Filee.Engines/Hwp/Hwpx/HwpxReader.cs+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxReader.cs@@ -8,6 +8,10 @@// * HwpxReader.Header.cs header.xml: fonts, character and paragraph shapes, numberings, bullets, borders, tab stops;// * HwpxReader.Body.cs paragraphs, runs, text, fields (hyperlinks), notes, bookmarks and tables;// * HwpxReader.Objects.cs pictures, drawing objects, text boxes, groups and equations.+//+// Read() gives the model the writers expect. ReadForLayout() also keeps what only a renderer uses and that would+// change converted files: runs that differ only in layout detail stay apart, polygons, curves and arcs become shapes,+// and master pages are read. Both fill the rendering detail of formats and objects (HwpxModel.Layout.cs).using System.Globalization;using System.IO.Compression;@@ -23,8 +27,22 @@ internal sealed partial class HwpxReaderprivate const string HwpUnitCharNamespace = "HwpUnitChar";private const string Paragraph2016Namespace = "http://www.hancom.co.kr/hwpml/2016/paragraph";- private readonly ZipArchive _zip;+ /// <summary>+ /// content.hpf metadata (opf:meta with this name and content "estimated") that marks the stored line layouts as+ /// estimated by Filee rather than laid out by 한글. HwpxWriter stores no line segments today; a writer that+ /// estimates them must add this marker so the layout engine does not trust them.+ /// </summary>+ internal const string EstimatedLinesMeta = "FileeLineSegments";++ private readonly ZipArchive? _zip;private readonly string _mediaFolder;+ private readonly bool _forLayout;++ /// <summary>Manifest item id → zip entry (master page parts are found through it).</summary>+ private Dictionary<string, string> _items = new(StringComparer.Ordinal);++ /// <summary>The package says its stored line layouts were estimated by Filee.</summary>+ private bool _estimatedLines;/// <summary>Manifest item id → zip entry of embedded binaries (pictures).</summary>private readonly Dictionary<string, string> _binaryItems = new(StringComparer.Ordinal);@@ -35,19 +53,40 @@ internal sealed partial class HwpxReader/// <summary>Elements the model cannot hold, by local name, with the number of times they were skipped.</summary>private readonly Dictionary<string, int> _skipped = new(StringComparer.Ordinal);- private HwpxReader(ZipArchive zip, string mediaFolder)+ private HwpxReader(ZipArchive? zip, string mediaFolder, bool forLayout){_zip = zip;_mediaFolder = mediaFolder;+ _forLayout = forLayout;}+ private ZipArchive Zip => _zip ?? throw new InvalidOperationException("This reader only has a header.");+// ───────────────────────── Entry points ─────────────────────────/// <summary>Reads <paramref name="path"/>; embedded pictures are extracted into <paramref name="mediaFolder"/>.</summary>public static HDocument Read(string path, string mediaFolder) => Read(path, mediaFolder, null);/// <param name="skipped">Receives the elements that were skipped because the model has no equivalent (local name → count).</param>- public static HDocument Read(string path, string mediaFolder, IDictionary<string, int>? skipped)+ public static HDocument Read(string path, string mediaFolder, IDictionary<string, int>? skipped) =>+ ReadPackage(path, mediaFolder, skipped, forLayout: false);++ /// <summary>+ /// Reads <paramref name="path"/> for the layout engine: like <see cref="Read(string, string, IDictionary{string, int}?)"/>,+ /// plus what only a renderer uses (runs apart by layout detail, polygons / curves / arcs, master pages).+ /// </summary>+ public static HDocument ReadForLayout(string path, string mediaFolder, IDictionary<string, int>? skipped = null) =>+ ReadPackage(path, mediaFolder, skipped, forLayout: true);++ /// <summary>A reader of header.xml alone, for its character and paragraph shapes (see <see cref="StyleResolver"/>).</summary>+ internal static HwpxReader ForHeader(XElement head)+ {+ var reader = new HwpxReader(null, "", forLayout: true);+ reader.LoadHeader(head);+ return reader;+ }++ private static HDocument ReadPackage(string path, string mediaFolder, IDictionary<string, int>? skipped, bool forLayout){ZipArchive zip;try@@ -61,7 +100,7 @@ internal sealed partial class HwpxReaderusing (zip){- var reader = new HwpxReader(zip, mediaFolder);+ var reader = new HwpxReader(zip, mediaFolder, forLayout);var document = reader.ReadDocument();if (skipped is not null){@@ -107,6 +146,8 @@ internal sealed partial class HwpxReaderif (entry.StartsWith("BinData/", StringComparison.OrdinalIgnoreCase) && Attr(item, "isEmbeded") is not "0")_binaryItems[id] = entry;}+ _items = items;+ _estimatedLines = Descendants(package?.Root, "meta").Any(m => Attr(m, "name") == EstimatedLinesMeta && (Attr(m, "content") ?? m.Value) == "estimated");var header = LoadXml(items.Values.FirstOrDefault(p => p.EndsWith("header.xml", StringComparison.OrdinalIgnoreCase)) ?? "Contents/header.xml", required: true)!;LoadHeader(header.Root!);@@ -159,7 +200,7 @@ internal sealed partial class HwpxReaderif (result.Count > 0)return result;- return _zip.Entries+ return Zip.Entries.Where(e => e.FullName.StartsWith("Contents/", StringComparison.OrdinalIgnoreCase) && IsSection(e.FullName)).OrderBy(e => int.TryParse(Path.GetFileNameWithoutExtension(e.Name).AsSpan(7), NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) ? n : int.MaxValue).Select(e => e.FullName)@@ -169,14 +210,14 @@ internal sealed partial class HwpxReaderprivate string? EntryPath(string href, string folder){var path = Uri.UnescapeDataString(href).Replace('\\', '/').TrimStart('/');- if (_zip.GetEntry(path) is not null)+ if (Zip.GetEntry(path) is not null)return path;- return folder.Length > 0 && _zip.GetEntry(folder + path) is not null ? folder + path : path;+ return folder.Length > 0 && Zip.GetEntry(folder + path) is not null ? folder + path : path;}private XDocument? LoadXml(string path, bool required){- var entry = _zip.GetEntry(path);+ var entry = Zip.GetEntry(path);if (entry is null){return required@@ -206,10 +247,10 @@ internal sealed partial class HwpxReader// Without a manifest entry, 한글's naming (BinData/<id>.<ext>) still finds the file.var entryPath = _binaryItems.GetValueOrDefault(itemId)- ?? _zip.Entries.FirstOrDefault(e => e.FullName.StartsWith("BinData/", StringComparison.OrdinalIgnoreCase) &&+ ?? Zip.Entries.FirstOrDefault(e => e.FullName.StartsWith("BinData/", StringComparison.OrdinalIgnoreCase) &&string.Equals(Path.GetFileNameWithoutExtension(e.Name), itemId, StringComparison.OrdinalIgnoreCase))?.FullName;string? path = null;- if (entryPath is not null && _zip.GetEntry(entryPath) is { } entry)+ if (entryPath is not null && Zip.GetEntry(entryPath) is { } entry){Directory.CreateDirectory(_mediaFolder);path = Path.Combine(_mediaFolder, $"hwpx-media-{_media.Count + 1}{Path.GetExtension(entry.Name).ToLowerInvariant()}");@@ -303,12 +344,45 @@ internal sealed partial class HwpxReadervar secPr = Elements(p).Where(e => e.Name.LocalName == "run").SelectMany(Elements).FirstOrDefault(e => e.Name.LocalName == "secPr");if (secPr is not null){- state.Begin(Section(secPr));+ var section = state.Begin(Section(secPr));_outlineNumberingId = Attr(secPr, "outlineShapeIDRef");+ if (_forLayout)+ MasterPages(secPr, section);}ReadParagraph(p, state.Current.Blocks, state);}+ /// <summary>+ /// Master pages (바탕쪽): the secPr refers to them by manifest id (hp:masterPage idRef), each a part of its own+ /// whose root holds the type and a paragraph list.+ /// </summary>+ private void MasterPages(XElement secPr, HSection section)+ {+ foreach (var reference in Descendants(secPr, "masterPage"))+ {+ var root = Attr(reference, "idRef") is { Length: > 0 } id+ ? LoadXml(_items.GetValueOrDefault(id) ?? $"Contents/{id}.xml", required: false)?.Root+ : reference;+ if (root is null)+ continue;+ var page = new HMasterPage(Attr(root, "type") switch+ {+ "EVEN" => HMasterPageKind.Even,+ "ODD" => HMasterPageKind.Odd,+ "LAST_PAGE" => HMasterPageKind.LastPage,+ "OPTIONAL_PAGE" => HMasterPageKind.OptionalPage,+ _ => HMasterPageKind.Both,+ })+ {+ PageNumber = Int(root, "pageNumber"),+ Duplicate = Flag(root, "pageDuplicate"),+ Front = Flag(root, "pageFront"),+ };+ page.Blocks.AddRange(ReadSubList(Child(root, "subList")));+ section.MasterPages.Add(page);+ }+ }+private static HSection Section(XElement secPr){var pagePr = Child(secPr, "pagePr");@@ -321,8 +395,13 @@ internal sealed partial class HwpxReadervar visibility = Child(secPr, "visibility");var start = Int(Child(secPr, "startNum"), "page");+ var grid = Child(secPr, "grid");+ var (lineGrid, charGrid) = (Math.Max(0, Int(grid, "lineGrid")), Math.Max(0, Int(grid, "charGrid")));return new HSection{+ Grid = lineGrid > 0 || charGrid > 0+ ? new HDocumentGrid(charGrid == 0 ? HGridKind.Lines : lineGrid == 0 ? HGridKind.SnapToChars : HGridKind.LinesAndChars, lineGrid, charGrid)+ : null,Page = new HPage(width, height,Left: Int(margin, "left", 7200), Right: Int(margin, "right", 7200),Top: Int(margin, "top", 4255), Bottom: Int(margin, "bottom", 4960),diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Header.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Header.csindex 156add1e..7cdebca4 100644--- a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Header.cs+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Header.cs@@ -53,38 +53,60 @@ internal sealed partial class HwpxWriterrefList.Add(numberings);}- var styles = _head.Descendants(Hh + "style").ToList();- (string, string, string) Ids(XElement style) =>- ((string?)style.Attribute("id") ?? _normalStyleId,- (string?)style.Attribute("paraPrIDRef") ?? _normalParaPrId,- (string?)style.Attribute("charPrIDRef") ?? _normalCharPrId);+ var styles = FindStyles(_head);+ (_normalStyleId, _normalParaPrId, _normalCharPrId) = styles.Normal;+ foreach (var (level, ids) in styles.Headings)+ _headings[level] = ids;+ _footnoteStyle = styles.Footnote;+ }++ /// <summary>The template styles (style, paragraph shape and character shape ids) plain paragraphs, headings and footnotes are written with.</summary>+ internal sealed record TemplateStyles(+ (string StyleId, string ParaPrId, string CharPrId) Normal,+ IReadOnlyDictionary<int, (string StyleId, string ParaPrId, string CharPrId)> Headings,+ (string StyleId, string ParaPrId, string CharPrId)? Footnote);++ /// <summary>+ /// Normal (style 0, else the first), "Heading 1".."Heading 9" by English style name (else by the outline level of+ /// their paragraph shapes) and the footnote style of a header.xml.+ /// </summary>+ internal static TemplateStyles FindStyles(XElement head)+ {+ var styles = head.Descendants(Hh + "style").ToList();+ var normalIds = ("0", "0", "0");+ (string, string, string) Ids(XElement style) => (+ (string?)style.Attribute("id") ?? normalIds.Item1,+ (string?)style.Attribute("paraPrIDRef") ?? normalIds.Item2,+ (string?)style.Attribute("charPrIDRef") ?? normalIds.Item3);var normal = styles.FirstOrDefault(s => (string?)s.Attribute("id") == "0") ?? styles.FirstOrDefault();if (normal is not null)- (_normalStyleId, _normalParaPrId, _normalCharPrId) = Ids(normal);+ normalIds = Ids(normal);- // "Heading 1".."Heading 9" by English style name; fall back to outline levels of paragraph properties.+ var headings = new Dictionary<int, (string StyleId, string ParaPrId, string CharPrId)>();+ (string StyleId, string ParaPrId, string CharPrId)? footnote = null;foreach (var style in styles){var name = (string?)style.Attribute("engName") ?? "";if (name.StartsWith("Heading ", StringComparison.OrdinalIgnoreCase) &&int.TryParse(name.AsSpan(8), out var level) && level is >= 1 and <= 9)- _headings[level] = Ids(style);+ headings[level] = Ids(style);else if (name.Contains("footnote", StringComparison.OrdinalIgnoreCase))- _footnoteStyle = Ids(style);+ footnote = Ids(style);}- if (_headings.Count == 0)+ if (headings.Count == 0){- foreach (var paraPr in _head.Descendants(Hh + "paraPr"))+ foreach (var paraPr in head.Descendants(Hh + "paraPr")){var heading = paraPr.Element(Hh + "heading");if ((string?)heading?.Attribute("type") != "OUTLINE" || !int.TryParse((string?)heading.Attribute("level"), out var outline))continue;var paraPrId = (string?)paraPr.Attribute("id") ?? "0";if (styles.FirstOrDefault(s => (string?)s.Attribute("paraPrIDRef") == paraPrId) is { } style)- _headings.TryAdd(outline + 1, Ids(style));+ headings.TryAdd(outline + 1, Ids(style));}}+ return new TemplateStyles(normalIds, headings, footnote);}private string SerializeHeader(int sectionCount)diff --git a/src/Filee.Engines/Hwp/Hwpx/StyleResolver.cs b/src/Filee.Engines/Hwp/Hwpx/StyleResolver.csnew file mode 100644index 00000000..7afdd824--- /dev/null+++ b/src/Filee.Engines/Hwp/Hwpx/StyleResolver.cs@@ -0,0 +1,173 @@+// Resolves what a document leaves to the 한글 style (null format members = "inherit") into concrete values, so the+// layout engine sees every paragraph and run fully specified.+//+// The values are the ones the document gets when HwpxWriter writes it with the same template and a 한글 reader opens+// the file: a paragraph starts from its style's paragraph shape (Normal, "Heading n", or the footnote style inside+// notes), the members the model sets replace the style's, and list items get the indentation the writer gives them.+// Character formats work the same way on the style's character shape, including links (blue and underlined unless+// coloured) and the per-language slots the writer fills from Font / EastAsianFont / Spacing. Rendering detail the+// source set (HParaLayout, HCharLayout) wins over the style's.++using System.IO.Compression;+using System.Xml.Linq;++namespace Filee.Engines.Hwp.Hwpx;++/// <summary>Where a paragraph sits: notes use the template's footnote style as their plain paragraph style.</summary>+internal enum HStyleContext+{+ Body,+ Note,+}++/// <summary>Resolves inherited format members against an HWPX template's styles.</summary>+internal sealed class StyleResolver+{+ /// <summary>Indentation per list level the writer gives list items without their own (see HwpxWriter.ParaPr).</summary>+ private const int ListIndent = 2000;++ private readonly HwpxReader _shapes;+ private readonly HwpxWriter.TemplateStyles _styles;++ private StyleResolver(XElement head)+ {+ _shapes = HwpxReader.ForHeader(head);+ _styles = HwpxWriter.FindStyles(head);+ }++ /// <summary>A resolver for the styles of <paramref name="template"/>; the built-in blank.hwpx when null.</summary>+ public static StyleResolver FromTemplate(Stream? template = null)+ {+ var stream = template ?? HwpxWriter.OpenBuiltInTemplate();+ try+ {+ using var zip = new ZipArchive(stream, ZipArchiveMode.Read, leaveOpen: true);+ var entry = zip.GetEntry("Contents/header.xml") ?? throw new InvalidDataException("The template has no Contents/header.xml.");+ using var header = entry.Open();+ return new StyleResolver(XDocument.Load(header).Root ?? throw new InvalidDataException("header.xml has no root element."));+ }+ finally+ {+ if (template is null)+ stream.Dispose();+ }+ }++ // ───────────────────────── Paragraphs ─────────────────────────++ /// <summary>The paragraph's format with every member set.</summary>+ public HParaFormat Paragraph(HParagraph paragraph, HStyleContext context = HStyleContext.Body)+ {+ var style = Style(paragraph, context);+ var shape = _shapes.ParagraphShape(style.ParaPrId);+ var format = paragraph.Format;+ var list = paragraph.List;+ var resolved = shape;++ if (!format.IsEmpty || list is not null)+ {+ // Margins go through 한글's storage like the writer writes them: a negative first-line indent ("intent")+ // keeps the first line at "left", so a style's hanging indent shifts what a model left margin means.+ var shapeIntent = shape.FirstLine ?? 0;+ var shapeLeft = (shape.Left ?? 0) + Math.Min(0, shapeIntent);+ var left = format.Left;+ var firstLine = format.FirstLine;+ if (list is not null && left is null)+ {+ left = (list.Level + 1) * ListIndent;+ firstLine ??= list.Numbered ? -ListIndent : 0;+ }+ var intent = firstLine ?? shapeIntent;+ var hwpLeft = left ?? shapeLeft;+ if (left is not null && firstLine is < 0)+ hwpLeft += firstLine.Value;++ resolved = new HParaFormat(+ Align: format.Align ?? shape.Align,+ Left: intent < 0 ? hwpLeft - intent : hwpLeft,+ Right: format.Right ?? shape.Right,+ FirstLine: intent,+ Before: format.Before ?? shape.Before,+ After: format.After ?? shape.After,+ LineSpacing: format.LineSpacing ?? shape.LineSpacing,+ KeepWithNext: format.KeepWithNext ?? shape.KeepWithNext,+ KeepLines: format.KeepLines ?? shape.KeepLines,+ WidowOrphan: format.WidowOrphan ?? shape.WidowOrphan,+ Tabs: format.Tabs is { Count: > 0 } ? format.Tabs : shape.Tabs);+ }++ // The source's own line rule wins; else the one its writer-side spacing stands for; else the style's.+ var layout = (format.Layout ?? new HParaLayout()).Over(shape.Layout);+ if (format.Layout?.LineHeight is null && format.LineSpacing is { } spacing)+ layout = layout with { LineHeight = HLineHeight.From(spacing) };+ return resolved with { RightToLeft = format.RightToLeft ?? false, Layout = layout };+ }++ // ───────────────────────── Characters ─────────────────────────++ /// <summary>The format of text in <paramref name="paragraph"/> with every member set.</summary>+ /// <param name="link">The text is inside a hyperlink (blue and underlined unless it has its own colour).</param>+ public HCharFormat Character(HCharFormat format, HParagraph paragraph, HStyleContext context = HStyleContext.Body, bool link = false)+ {+ var shape = _shapes.CharacterShape(Style(paragraph, context).CharPrId);+ link = link && format.Color is null;+ if (format.IsEmpty && !link)+ return shape with { Layout = format.Layout is { } own ? own.Over(shape.Layout) : shape.Layout };++ var slots = shape.Layout?.Slots ?? HLanguageSlots.All(default);+ string? latin = shape.Font, eastAsian = shape.EastAsianFont;+ if (format.Font is not null || format.EastAsianFont is not null)+ {+ // As the writer fills the slots: the East Asian font for Hangul, Hanja, Japanese and symbols (CJK+ // punctuation), the Latin font for the rest, each standing in for the other when missing.+ foreach (var language in HLanguageSlots.Languages)+ {+ var face = language is HLanguage.Hangul or HLanguage.Hanja or HLanguage.Japanese or HLanguage.Symbol+ ? format.EastAsianFont ?? format.Font+ : format.Font ?? format.EastAsianFont;+ slots = slots.With(language, slots[language] with { Font = face });+ }+ (latin, eastAsian) = (slots.Latin.Font, slots.Hangul.Font);+ }+ if (format.Spacing is { } spacing)+ {+ foreach (var language in HLanguageSlots.Languages)+ slots = slots.With(language, slots[language] with { Spacing = spacing });+ }++ var (superscript, subscript) = format switch+ {+ { Superscript: true } => (true, false),+ { Subscript: true } => (false, true),+ { Superscript: false } or { Subscript: false } => (false, false),+ _ => (shape.Superscript, shape.Subscript),+ };+ var resolved = new HCharFormat(+ Bold: format.Bold ?? shape.Bold,+ Italic: format.Italic ?? shape.Italic,+ Underline: link || format.Underline is not null ? link || format.Underline == true : shape.Underline,+ Strike: format.Strike ?? shape.Strike,+ Superscript: superscript,+ Subscript: subscript,+ Size: format.Size is { } size ? Math.Clamp(size, 100, 409600) : shape.Size,+ Font: latin,+ EastAsianFont: eastAsian,+ Color: link ? "#0000FF" : format.Color ?? shape.Color,+ Shade: format.Shade ?? shape.Shade,+ Spacing: format.Spacing ?? shape.Spacing);+ var styleLayout = (shape.Layout ?? new HCharLayout()) with { Slots = slots };+ return resolved with { Layout = format.Layout is { } layout ? layout.Over(styleLayout) : styleLayout };+ }++ /// <summary>The format of the paragraph mark (the height of an empty paragraph).</summary>+ public HCharFormat Mark(HParagraph paragraph, HStyleContext context = HStyleContext.Body) =>+ Character(paragraph.MarkFormat, paragraph, context);++ /// <summary>The template style a paragraph is written with (see HwpxWriter.Paragraph and HwpxWriter.Note).</summary>+ private (string StyleId, string ParaPrId, string CharPrId) Style(HParagraph paragraph, HStyleContext context)+ {+ if (paragraph.HeadingLevel > 0 && _styles.Headings.TryGetValue(paragraph.HeadingLevel, out var heading))+ return heading;+ return context == HStyleContext.Note && _styles.Footnote is { } footnote ? footnote : _styles.Normal;+ }+}diff --git a/src/Filee.Engines/Hwp/Hwpx/SymbolFonts.cs b/src/Filee.Engines/Hwp/Hwpx/SymbolFonts.csindex b3b5e29d..1b183ea7 100644--- a/src/Filee.Engines/Hwp/Hwpx/SymbolFonts.cs+++ b/src/Filee.Engines/Hwp/Hwpx/SymbolFonts.cs@@ -119,7 +119,12 @@ internal static class SymbolFontspublic static HCharFormat WithoutSymbolFont(HCharFormat format){var eastAsian = IsSymbolFont(format.EastAsianFont) ? null : format.EastAsianFont;- return format with { Font = IsSymbolFont(format.Font) ? eastAsian : format.Font, EastAsianFont = eastAsian };+ // Word's own fonts lose the symbol font too, so the mapped characters are not drawn in it.+ string? Plain(string? font) => IsSymbolFont(font) ? null : font;+ var layout = format.Layout is { WordFonts: { } fonts } detail+ ? detail with { WordFonts = fonts with { Ascii = Plain(fonts.Ascii), HighAnsi = Plain(fonts.HighAnsi), EastAsia = Plain(fonts.EastAsia), ComplexScript = Plain(fonts.ComplexScript) } }+ : format.Layout;+ return format with { Font = IsSymbolFont(format.Font) ? eastAsian : format.Font, EastAsianFont = eastAsian, Layout = layout };}/// <summary>diff --git a/tests/Filee.Engines.Tests/DocumentModelTests.cs b/tests/Filee.Engines.Tests/DocumentModelTests.csnew file mode 100644index 00000000..e7fd13be--- /dev/null+++ b/tests/Filee.Engines.Tests/DocumentModelTests.cs@@ -0,0 +1,605 @@+// The rendering detail of the document model (HwpxModel.Layout.cs): what HwpxReader and DocxReader fill in, that it+// leaves written files alone, and StyleResolver. Every input is generated here.++using System.IO.Compression;+using System.Text;+using Filee.Engines.Hwp.Hwpx;+using Filee.Engines.Hwp.Hwpx.Docx;+using ImageMagick;+using static Filee.Engines.Tests.DocxBuilder;++namespace Filee.Engines.Tests;++public class DocumentModelTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ // ───────────────────────── HWPX packages ─────────────────────────++ private const string Namespaces =+ "xmlns:hp=\"http://www.hancom.co.kr/hwpml/2011/paragraph\" xmlns:hs=\"http://www.hancom.co.kr/hwpml/2011/section\" " ++ "xmlns:hc=\"http://www.hancom.co.kr/hwpml/2011/core\" xmlns:hh=\"http://www.hancom.co.kr/hwpml/2011/head\" " ++ "xmlns:hm=\"http://www.hancom.co.kr/hwpml/2011/master-page\"";++ private const string Case = "<hp:case hp:required-namespace=\"http://www.hancom.co.kr/hwpml/2016/HwpUnitChar\">";++ private static string Margins(int intent = 0, int left = 0) =>+ $"<hh:margin><hc:intent value=\"{intent}\" unit=\"HWPUNIT\"/><hc:left value=\"{left}\" unit=\"HWPUNIT\"/><hc:right value=\"0\" unit=\"HWPUNIT\"/><hc:prev value=\"0\" unit=\"HWPUNIT\"/><hc:next value=\"0\" unit=\"HWPUNIT\"/></hh:margin>";++ private static string LineSpacing(string type, int value) =>+ $"<hp:switch>{Case}{Margins()}<hh:lineSpacing type=\"{type}\" value=\"{value}\" unit=\"HWPUNIT\"/></hp:case>" ++ $"<hp:default>{Margins()}<hh:lineSpacing type=\"{type}\" value=\"{(type == "PERCENT" ? value : value * 2)}\" unit=\"HWPUNIT\"/></hp:default></hp:switch>";++ private static string CharPr(string id, string fontRef = "0", string ratio = "100", string spacing = "0", string relSz = "100", string offset = "0")+ {+ static string Slots(string name, string values)+ {+ var parts = values.Split(',');+ string Value(int i) => parts.Length == 1 ? parts[0] : parts[i];+ return $"<hh:{name} hangul=\"{Value(0)}\" latin=\"{Value(1)}\" hanja=\"{Value(2)}\" japanese=\"{Value(3)}\" other=\"{Value(4)}\" symbol=\"{Value(5)}\" user=\"{Value(6)}\"/>";+ }+ return $"<hh:charPr id=\"{id}\" height=\"1000\" textColor=\"#000000\" shadeColor=\"none\" useFontSpace=\"0\" useKerning=\"0\" symMark=\"NONE\" borderFillIDRef=\"1\">" ++ Slots("fontRef", fontRef) + Slots("ratio", ratio) + Slots("spacing", spacing) + Slots("relSz", relSz) + Slots("offset", offset) ++ "<hh:underline type=\"NONE\" shape=\"SOLID\" color=\"#000000\"/><hh:strikeout shape=\"NONE\" color=\"#000000\"/></hh:charPr>";+ }++ private static string ParaPr(string id, string spacing, string attributes = "condense=\"0\" fontLineHeight=\"0\" snapToGrid=\"1\"",+ string breaks = "breakLatinWord=\"KEEP_WORD\" breakNonLatinWord=\"KEEP_WORD\" lineWrap=\"BREAK\"", string autoSpacing = "eAsianEng=\"0\" eAsianNum=\"0\"",+ string border = "borderFillIDRef=\"1\" offsetLeft=\"0\" offsetRight=\"0\" offsetTop=\"0\" offsetBottom=\"0\" connect=\"0\" ignoreMargin=\"0\"") =>+ $"<hh:paraPr id=\"{id}\" tabPrIDRef=\"0\" {attributes} suppressLineNumbers=\"0\" checked=\"0\"><hh:align horizontal=\"JUSTIFY\" vertical=\"BASELINE\"/>" ++ "<hh:heading type=\"NONE\" idRef=\"0\" level=\"0\"/>" ++ $"<hh:breakSetting {breaks} widowOrphan=\"0\" keepWithNext=\"0\" keepLines=\"0\" pageBreakBefore=\"0\"/>" ++ $"<hh:autoSpacing {autoSpacing}/>{spacing}<hh:border {border}/></hh:paraPr>";++ private static string BorderFill(string id, string edge, string fill = "") =>+ $"<hh:borderFill id=\"{id}\" threeD=\"0\" shadow=\"0\" centerLine=\"NONE\" breakCellSeparateLine=\"0\">" ++ "<hh:slash type=\"NONE\" Crooked=\"0\" isCounter=\"0\"/><hh:backSlash type=\"NONE\" Crooked=\"0\" isCounter=\"0\"/>" ++ $"<hh:leftBorder {edge}/><hh:rightBorder {edge}/><hh:topBorder {edge}/><hh:bottomBorder {edge}/>" ++ $"<hh:diagonal type=\"SOLID\" width=\"0.1 mm\" color=\"#000000\"/>{fill}</hh:borderFill>";++ private static string Hp(string runs, string paraPr = "0", string lines = "") =>+ $"<hp:p id=\"0\" paraPrIDRef=\"{paraPr}\" styleIDRef=\"0\" pageBreak=\"0\" columnBreak=\"0\" merged=\"0\">{runs}{lines}</hp:p>";++ private static string Hr(string content, string charPr = "0") => $"<hp:run charPrIDRef=\"{charPr}\">{content}</hp:run>";++ private static string Ht(string text) => $"<hp:t>{text}</hp:t>";++ private static string SubList(string paragraphs) =>+ $"<hp:subList id=\"\" textDirection=\"HORIZONTAL\" lineWrap=\"BREAK\" vertAlign=\"TOP\" linkListIDRef=\"0\" linkListNextIDRef=\"0\" textWidth=\"0\" textHeight=\"0\" hasTextRef=\"0\" hasNumRef=\"0\">{paragraphs}</hp:subList>";++ private const string FloatingPos =+ "<hp:pos treatAsChar=\"0\" affectLSpacing=\"0\" flowWithText=\"1\" allowOverlap=\"1\" holdAnchorAndSO=\"0\" vertRelTo=\"PARA\" horzRelTo=\"COLUMN\" vertAlign=\"TOP\" horzAlign=\"LEFT\" vertOffset=\"0\" horzOffset=\"0\"/>";++ private const string Outline =+ "<hp:lineShape color=\"#FF0000\" width=\"100\" style=\"SOLID\" endCap=\"FLAT\" headStyle=\"NORMAL\" tailStyle=\"NORMAL\" headfill=\"1\" tailfill=\"1\" headSz=\"MEDIUM_MEDIUM\" tailSz=\"MEDIUM_MEDIUM\" outlineStyle=\"NORMAL\" alpha=\"0\"/>" ++ "<hc:fillBrush><hc:winBrush faceColor=\"#00FF00\" hatchColor=\"#000000\" alpha=\"0\"/></hc:fillBrush>";++ /// <summary>A drawing object (rect, polygon, curve, arc ...) floating at the paragraph, with its own children.</summary>+ private static string Drawing(string name, string attributes, string children, string transform = "<hp:flip horizontal=\"0\" vertical=\"0\"/><hp:rotationInfo angle=\"0\" centerX=\"0\" centerY=\"0\" rotateimage=\"1\"/>", int zOrder = 0) =>+ $"<hp:{name} id=\"1\" zOrder=\"{zOrder}\" numberingType=\"NONE\" textWrap=\"SQUARE\" textFlow=\"BOTH_SIDES\" lock=\"0\" dropcapstyle=\"None\" href=\"\" groupLevel=\"0\" instid=\"2\" {attributes}>" ++ $"<hp:offset x=\"0\" y=\"0\"/><hp:orgSz width=\"4000\" height=\"2000\"/><hp:curSz width=\"8000\" height=\"4000\"/>{transform}{Outline}{children}" ++ $"<hp:sz width=\"8000\" widthRelTo=\"ABSOLUTE\" height=\"4000\" heightRelTo=\"ABSOLUTE\" protect=\"0\"/>{FloatingPos}<hp:outMargin left=\"0\" right=\"0\" top=\"0\" bottom=\"0\"/></hp:{name}>";++ /// <summary>An HWPX package: header.xml from <paramref name="refList"/>, one section, extra parts and manifest items.</summary>+ private static string Package(string path, string refList, string section, string secPrChildren = "", Dictionary<string, string>? parts = null,+ bool estimatedLines = false, byte[]? picture = null)+ {+ var header =+ $"<hh:head {Namespaces} version=\"1.4\" secCnt=\"1\"><hh:refList>" ++ "<hh:fontfaces itemCnt=\"7\">" + string.Concat(new[] { "HANGUL", "LATIN", "HANJA", "JAPANESE", "OTHER", "SYMBOL", "USER" }.Select(lang =>+ $"<hh:fontface lang=\"{lang}\" fontCnt=\"2\"><hh:font id=\"0\" face=\"{lang}-0\" type=\"TTF\" isEmbedded=\"0\"/><hh:font id=\"1\" face=\"{lang}-1\" type=\"TTF\" isEmbedded=\"0\"/></hh:fontface>")) ++ "</hh:fontfaces>" + refList ++ "<hh:styles itemCnt=\"1\"><hh:style id=\"0\" type=\"PARA\" name=\"바탕글\" engName=\"Normal\" paraPrIDRef=\"0\" charPrIDRef=\"0\" nextStyleIDRef=\"0\" langID=\"1042\" lockForm=\"0\"/></hh:styles>" ++ "</hh:refList></hh:head>";+ var secPr =+ "<hp:secPr id=\"\" textDirection=\"HORIZONTAL\" spaceColumns=\"1134\" tabStop=\"8000\" tabStopVal=\"4000\" tabStopUnit=\"HWPUNIT\" outlineShapeIDRef=\"0\" memoShapeIDRef=\"0\" textVerticalWidthHead=\"0\" masterPageCnt=\"0\">" ++ "<hp:pagePr landscape=\"WIDELY\" width=\"59528\" height=\"84188\" gutterType=\"LEFT_ONLY\"><hp:margin header=\"4252\" footer=\"4252\" gutter=\"0\" left=\"8504\" right=\"8504\" top=\"5668\" bottom=\"4252\"/></hp:pagePr>" ++ secPrChildren + "</hp:secPr>";+ var body = $"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><hs:sec {Namespaces}>{Hp(Hr(secPr))}{section}</hs:sec>";++ var items = new StringBuilder("<opf:item id=\"header\" href=\"Contents/header.xml\" media-type=\"application/xml\"/><opf:item id=\"section0\" href=\"Contents/section0.xml\" media-type=\"application/xml\"/>");+ foreach (var name in parts?.Keys.ToList() ?? [])+ items.Append($"<opf:item id=\"{Path.GetFileNameWithoutExtension(name)}\" href=\"{name}\" media-type=\"application/xml\"/>");+ if (picture is not null)+ items.Append("<opf:item id=\"image1\" href=\"BinData/image1.png\" media-type=\"image/png\" isEmbeded=\"1\"/>");+ var meta = estimatedLines ? "<opf:meta name=\"FileeLineSegments\" content=\"estimated\"/>" : "";+ var hpf = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><opf:package xmlns:opf=\"http://www.idpf.org/2007/opf/\"><opf:metadata><opf:title>t</opf:title>" + meta + "</opf:metadata>" ++ $"<opf:manifest>{items}</opf:manifest><opf:spine><opf:itemref idref=\"header\" linear=\"yes\"/><opf:itemref idref=\"section0\" linear=\"yes\"/></opf:spine></opf:package>";++ using var zip = ZipFile.Open(path, ZipArchiveMode.Create);+ void Write(string name, string text)+ {+ using var writer = new StreamWriter(zip.CreateEntry(name).Open(), new UTF8Encoding(false));+ writer.Write(text);+ }+ Write("mimetype", "application/hwp+zip");+ Write("Contents/content.hpf", hpf);+ Write("Contents/header.xml", "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>" + header);+ Write("Contents/section0.xml", body);+ foreach (var (name, xml) in parts ?? [])+ Write(name, xml);+ if (picture is not null)+ {+ using var stream = zip.CreateEntry("BinData/image1.png").Open();+ stream.Write(picture);+ }+ return path;+ }++ /// <summary>borderFill 1 (no lines), charPr 0 and paraPr 0 (160%), plus the given items.</summary>+ private static string RefList(string borderFills = "", string charPrs = "", string paraPrs = "") =>+ $"<hh:borderFills>{BorderFill("1", "type=\"NONE\" width=\"0.1 mm\" color=\"#000000\"")}{borderFills}</hh:borderFills>" ++ $"<hh:charProperties>{CharPr("0")}{charPrs}</hh:charProperties>" ++ "<hh:tabProperties><hh:tabPr id=\"0\" autoTabLeft=\"0\" autoTabRight=\"0\"/></hh:tabProperties>" ++ $"<hh:paraProperties>{ParaPr("0", LineSpacing("PERCENT", 160))}{paraPrs}</hh:paraProperties>";++ private HDocument ReadHwpx(string path, bool forLayout = false, Dictionary<string, int>? skipped = null)+ {+ var media = Path.Combine(Path.GetDirectoryName(path)!, "media");+ return forLayout ? HwpxReader.ReadForLayout(path, media, skipped) : HwpxReader.Read(path, media, skipped);+ }++ private static List<HParagraph> Paragraphs(HDocument document) => document.Sections.SelectMany(s => s.Blocks).OfType<HParagraph>().ToList();++ // ───────────────────────── HWPX: characters ─────────────────────────++ [Fact]+ public void Hwpx_character_shapes_keep_all_seven_language_slots()+ {+ var path = Package(Path.Combine(fx.NewFolder(), "slots.hwpx"),+ RefList(charPrs: CharPr("1", fontRef: "1,0,1,0,1,0,1", ratio: "90,80,100,100,100,100,100", spacing: "-5,10,0,0,0,0,0", relSz: "100,95,100,100,100,100,100", offset: "0,-10,0,0,0,0,0")),+ Hp(Hr(Ht("한글 Latin"), "1")));++ var text = Assert.IsType<HText>(Paragraphs(ReadHwpx(path))[1].Inlines.Single());++ // What the writers use stays as before: the Latin and Hangul faces, the Hangul spacing.+ Assert.Equal(("LATIN-0", "HANGUL-1", -5), (text.Format.Font, text.Format.EastAsianFont, text.Format.Spacing));+ var slots = text.Format.Layout!.Slots!;+ Assert.Equal(new HSlotFormat("HANGUL-1", 90, -5, 100, 0), slots.Hangul);+ Assert.Equal(new HSlotFormat("LATIN-0", 80, 10, 95, -10), slots.Latin);+ Assert.Equal(["HANGUL-1", "LATIN-0", "HANJA-1", "JAPANESE-0", "OTHER-1", "SYMBOL-0", "USER-1"], HLanguageSlots.Languages.Select(l => slots[l].Font));+ }++ [Fact]+ public void Runs_that_differ_only_in_layout_detail_stay_apart_when_read_for_layout()+ {+ var path = Package(Path.Combine(fx.NewFolder(), "runs.hwpx"),+ RefList(charPrs: CharPr("1", ratio: "80")),+ Hp(Hr(Ht("보통")) + Hr(Ht("좁게"), "1")));++ // For the writers the runs look alike and are one text, as before; the layout engine sees both.+ var merged = Paragraphs(ReadHwpx(path))[1].Inlines;+ Assert.Equal("보통좁게", Assert.IsType<HText>(Assert.Single(merged)).Text);+ var apart = Paragraphs(ReadHwpx(path, forLayout: true))[1].Inlines.Cast<HText>().ToList();+ Assert.Equal([("보통", 100), ("좁게", 80)], apart.Select(t => (t.Text, t.Format.Layout!.Slots!.Hangul.Ratio!.Value)));+ Assert.Equal(apart[0].Format, apart[1].Format);+ Assert.False(apart[0].Format.SameLayout(apart[1].Format));+ }++ // ───────────────────────── HWPX: paragraphs ─────────────────────────++ [Fact]+ public void Hwpx_paragraph_shapes_keep_line_rules_borders_and_line_breaking()+ {+ var path = Package(Path.Combine(fx.NewFolder(), "paragraphs.hwpx"),+ RefList(+ borderFills: BorderFill("2", "type=\"SOLID\" width=\"0.4 mm\" color=\"#0000FF\"", "<hc:fillBrush><hc:winBrush faceColor=\"#FFF2CC\" hatchColor=\"#000000\" alpha=\"0\"/></hc:fillBrush>"),+ paraPrs:+ ParaPr("1", LineSpacing("BETWEEN_LINES", 500), "condense=\"25\" fontLineHeight=\"1\" snapToGrid=\"0\"",+ "breakLatinWord=\"HYPHENATION\" breakNonLatinWord=\"BREAK_WORD\" lineWrap=\"SQUEEZE\"", "eAsianEng=\"1\" eAsianNum=\"0\"",+ "borderFillIDRef=\"2\" offsetLeft=\"100\" offsetRight=\"200\" offsetTop=\"300\" offsetBottom=\"400\" connect=\"1\" ignoreMargin=\"1\"") ++ ParaPr("2", LineSpacing("FIXED", 1800))),+ Hp(Hr(Ht("상자")), "1") + Hp(Hr(Ht("고정")), "2"));++ var paragraphs = Paragraphs(ReadHwpx(path));+ var boxed = paragraphs[1].Format;+ // The writers' line spacing is unchanged; the rule keeps 한글's meaning ("space between lines only").+ Assert.Equal(new HLineSpacing(HLineSpacingKind.AtLeast, 1500), boxed.LineSpacing);+ var layout = boxed.Layout!;+ Assert.Equal(new HLineHeight(HLineHeightRule.BetweenLines, 500), layout.LineHeight);+ Assert.Equal((false, true), (layout.SnapToGrid, layout.FontLineHeight));+ Assert.Equal(new HLineBreaking(HLatinBreak.Hyphenation, HNonLatinBreak.BreakWord, HLineWrap.Squeeze, AutoSpaceLatin: true, AutoSpaceDigits: false, Condense: 25), layout.Breaking);+ var border = layout.Border!;+ Assert.Equal(new HBorder(HBorderStyle.Solid, 0.4, "#0000FF"), border.Borders.Top);+ Assert.Equal(("#FFF2CC", new HInsets(100, 200, 300, 400), true, true), (border.Fill, border.Offsets, border.Connect, border.IgnoreMargin));+ Assert.True(border.IsVisible);++ Assert.Equal(new HLineHeight(HLineHeightRule.Exact, 1800), paragraphs[2].Format.Layout!.LineHeight);+ Assert.False(paragraphs[2].Format.Layout!.Border!.IsVisible);+ Assert.Equal(new HLineHeight(HLineHeightRule.Percent, 160), paragraphs[0].Format.Layout!.LineHeight);+ }++ [Fact]+ public void Hwpx_stored_line_layout_is_kept_and_marked_when_Filee_estimated_it()+ {+ const string Lines =+ "<hp:linesegarray><hp:lineseg textpos=\"0\" vertpos=\"0\" vertsize=\"1000\" textheight=\"1000\" baseline=\"850\" spacing=\"600\" horzpos=\"0\" horzsize=\"42520\" flags=\"393216\"/>" ++ "<hp:lineseg textpos=\"12\" vertpos=\"1600\" vertsize=\"1000\" textheight=\"1000\" baseline=\"850\" spacing=\"600\" horzpos=\"100\" horzsize=\"42420\" flags=\"0\"/></hp:linesegarray>";+ var dir = fx.NewFolder();+ var section = Hp(Hr(Ht("두 줄로 나뉜 문단입니다")), lines: Lines) + Hp(Hr(Ht("저장된 줄 없음")));++ var stored = Paragraphs(ReadHwpx(Package(Path.Combine(dir, "stored.hwpx"), RefList(), section)));+ var lines = stored[1].Lines!;+ Assert.False(lines.Estimated);+ Assert.Equal([new HLineSegment(0, 0, 1000, 1000, 850, 600, 0, 42520, 393216), new HLineSegment(12, 1600, 1000, 1000, 850, 600, 100, 42420, 0)], lines.Segments);+ Assert.Null(stored[2].Lines);++ var estimated = Paragraphs(ReadHwpx(Package(Path.Combine(dir, "estimated.hwpx"), RefList(), section, estimatedLines: true)));+ Assert.True(estimated[1].Lines!.Estimated);+ }++ [Fact]+ public void Hwpx_sections_keep_their_grid_and_tables_their_page_break_mode()+ {+ var table =+ "<hp:tbl id=\"20\" zOrder=\"0\" numberingType=\"TABLE\" textWrap=\"TOP_AND_BOTTOM\" textFlow=\"BOTH_SIDES\" lock=\"0\" dropcapstyle=\"None\" pageBreak=\"NONE\" repeatHeader=\"0\" rowCnt=\"1\" colCnt=\"1\" cellSpacing=\"0\" borderFillIDRef=\"1\" noAdjust=\"0\">" ++ "<hp:sz width=\"6000\" widthRelTo=\"ABSOLUTE\" height=\"1000\" heightRelTo=\"ABSOLUTE\" protect=\"0\"/>" + FloatingPos + "<hp:outMargin left=\"0\" right=\"0\" top=\"0\" bottom=\"0\"/>" ++ "<hp:tr><hp:tc name=\"\" header=\"0\" hasMargin=\"0\" protect=\"0\" editable=\"0\" dirty=\"0\" borderFillIDRef=\"1\">" + SubList(Hp(Hr(Ht("칸")))) ++ "<hp:cellAddr colAddr=\"0\" rowAddr=\"0\"/><hp:cellSpan colSpan=\"1\" rowSpan=\"1\"/><hp:cellSz width=\"6000\" height=\"1000\"/><hp:cellMargin left=\"0\" right=\"0\" top=\"0\" bottom=\"0\"/></hp:tc></hp:tr></hp:tbl>";+ var path = Package(Path.Combine(fx.NewFolder(), "grid.hwpx"), RefList(), Hp(Hr(table)), "<hp:grid lineGrid=\"1600\" charGrid=\"0\" wonggojiFormat=\"0\"/>");++ var document = ReadHwpx(path);++ Assert.Equal(new HDocumentGrid(HGridKind.Lines, 1600), document.Sections[0].Grid);+ Assert.Equal(HTablePageBreak.None, document.Sections[0].Blocks.OfType<HTable>().Single().PageBreak);+ }++ [Fact]+ public void Hwpx_master_pages_are_read_for_layout()+ {+ var master =+ $"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><masterPage {Namespaces} id=\"masterpage0\" type=\"EVEN\" pageNumber=\"0\" pageDuplicate=\"1\" pageFront=\"0\">" ++ SubList(Hp(Hr(Ht("바탕쪽 글")))) + "</masterPage>";+ var path = Package(Path.Combine(fx.NewFolder(), "master.hwpx"), RefList(), Hp(Hr(Ht("본문"))),+ "<hp:masterPage idRef=\"masterpage0\"/>", new() { ["Contents/masterpage0.xml"] = master });++ Assert.Empty(ReadHwpx(path).Sections[0].MasterPages);+ var page = Assert.Single(ReadHwpx(path, forLayout: true).Sections[0].MasterPages);+ Assert.Equal((HMasterPageKind.Even, true, false), (page.Kind, page.Duplicate, page.Front));+ Assert.Equal("바탕쪽 글", Assert.IsType<HText>(Assert.IsType<HParagraph>(Assert.Single(page.Blocks)).Inlines.Single()).Text);+ }++ // ───────────────────────── HWPX: objects ─────────────────────────++ [Fact]+ public void Hwpx_pictures_keep_crop_rotation_mirroring_and_z_order()+ {+ using var image = new MagickImage(MagickColors.Teal, 40, 20);+ var picture =+ "<hp:pic id=\"5\" zOrder=\"7\" numberingType=\"PICTURE\" textWrap=\"SQUARE\" textFlow=\"BOTH_SIDES\" lock=\"0\" dropcapstyle=\"None\" href=\"\" groupLevel=\"0\" instid=\"6\" reverse=\"0\">" ++ "<hp:offset x=\"0\" y=\"0\"/><hp:orgSz width=\"3000\" height=\"1500\"/><hp:curSz width=\"3000\" height=\"1500\"/><hp:flip horizontal=\"1\" vertical=\"0\"/>" ++ "<hp:rotationInfo angle=\"30\" centerX=\"1500\" centerY=\"750\" rotateimage=\"1\"/>" ++ "<hp:imgRect><hc:pt0 x=\"0\" y=\"0\"/><hc:pt1 x=\"3000\" y=\"0\"/><hc:pt2 x=\"3000\" y=\"1500\"/><hc:pt3 x=\"0\" y=\"1500\"/></hp:imgRect>" ++ "<hp:imgClip left=\"300\" right=\"2700\" top=\"0\" bottom=\"1200\"/><hp:inMargin left=\"0\" right=\"0\" top=\"0\" bottom=\"0\"/><hp:imgDim dimwidth=\"3000\" dimheight=\"1500\"/>" ++ "<hc:img binaryItemIDRef=\"image1\" bright=\"0\" contrast=\"0\" effect=\"REAL_PIC\" alpha=\"0\"/><hp:effects/>" ++ $"<hp:sz width=\"3000\" widthRelTo=\"ABSOLUTE\" height=\"1500\" heightRelTo=\"ABSOLUTE\" protect=\"0\"/>{FloatingPos}<hp:outMargin left=\"0\" right=\"0\" top=\"0\" bottom=\"0\"/></hp:pic>";+ var path = Package(Path.Combine(fx.NewFolder(), "picture.hwpx"), RefList(), Hp(Hr(picture)), picture: image.ToByteArray(MagickFormat.Png));++ var read = Assert.IsType<HImage>(Paragraphs(ReadHwpx(path))[1].Inlines.Single());++ Assert.Equal(new HCrop(0.1, 0, 0.1, 0.2), read.Crop);+ Assert.Equal(new HTransform(30, FlipHorizontal: true), read.Transform);+ Assert.Equal(7, read.ZOrder);+ }++ [Fact]+ public void Hwpx_polygons_curves_and_arcs_are_shapes_when_read_for_layout()+ {+ var polygon = Drawing("polygon", "", "<hc:pt x=\"0\" y=\"0\"/><hc:pt x=\"4000\" y=\"0\"/><hc:pt x=\"2000\" y=\"2000\"/><hc:pt x=\"0\" y=\"0\"/>", zOrder: 3);+ var curve = Drawing("curve", "", "<hp:seg type=\"CURVE\" x1=\"0\" y1=\"2000\" x2=\"1000\" y2=\"0\"/><hp:seg type=\"LINE\" x1=\"1000\" y1=\"0\" x2=\"4000\" y2=\"2000\"/>",+ "<hp:flip horizontal=\"0\" vertical=\"1\"/><hp:rotationInfo angle=\"90\" centerX=\"0\" centerY=\"0\" rotateimage=\"1\"/>");+ var arc = Drawing("arc", "type=\"PIE\"", "<hc:center x=\"2000\" y=\"1000\"/><hc:ax1 x=\"4000\" y=\"1000\"/><hc:ax2 x=\"2000\" y=\"0\"/>");+ var labelled = Drawing("polygon", "", "<hp:drawText lastWidth=\"4000\" name=\"\" editable=\"0\">" + SubList(Hp(Hr(Ht("다각형 글")))) ++ "<hp:textMargin left=\"0\" right=\"0\" top=\"0\" bottom=\"0\"/></hp:drawText><hc:pt x=\"0\" y=\"0\"/><hc:pt x=\"4000\" y=\"2000\"/><hc:pt x=\"0\" y=\"2000\"/>");+ var path = Package(Path.Combine(fx.NewFolder(), "shapes.hwpx"), RefList(), Hp(Hr(polygon + curve + arc + labelled)));++ // For the writers nothing changes: shapes they cannot draw are skipped, text keeps a box without outline.+ var skipped = new Dictionary<string, int>();+ var plain = Paragraphs(ReadHwpx(path, skipped: skipped))[1].Inlines;+ Assert.Equal((1, 1, 1), (skipped["polygon"], skipped["curve"], skipped["arc"]));+ Assert.Equal(HBorderStyle.None, Assert.IsType<HTextBox>(Assert.Single(plain)).Line.Style);++ var inlines = Paragraphs(ReadHwpx(path, forLayout: true))[1].Inlines;+ var shape = Assert.IsType<HShape>(inlines[0]);+ Assert.Equal((HShapeKind.Polygon, 8000, 4000, 3, "#00FF00", "#FF0000"), (shape.Kind, shape.Width, shape.Height, shape.ZOrder, shape.Fill, shape.Line.Color));+ Assert.Equal((4000, 2000), (shape.Geometry!.Width, shape.Geometry.Height));+ Assert.Equal([new HPoint(0, 0), new HPoint(4000, 0), new HPoint(2000, 2000), new HPoint(0, 0)], shape.Geometry.Points!);++ var curved = Assert.IsType<HShape>(inlines[1]);+ Assert.Equal(HShapeKind.Curve, curved.Kind);+ Assert.Equal([new HCurveSegment(true, new HPoint(0, 2000), new HPoint(1000, 0)), new HCurveSegment(false, new HPoint(1000, 0), new HPoint(4000, 2000))], curved.Geometry!.Segments!);+ Assert.Equal(new HTransform(90, FlipVertical: true), curved.Transform);++ var pie = Assert.IsType<HShape>(inlines[2]);+ Assert.Equal(new HArc(HArcKind.Pie, new HPoint(2000, 1000), new HPoint(4000, 1000), new HPoint(2000, 0)), pie.Geometry!.Arc);++ var box = Assert.IsType<HTextBox>(inlines[3]);+ Assert.Equal((HShapeKind.Polygon, HBorderStyle.Solid, "#00FF00", 3), (box.Shape, box.Line.Style, box.Fill, box.Geometry!.Points!.Count));+ }++ [Fact]+ public void Hwpx_rectangles_keep_rotation_and_z_order()+ {+ var rect = Drawing("rect", "ratio=\"0\"", "<hc:pt0 x=\"0\" y=\"0\"/><hc:pt1 x=\"4000\" y=\"0\"/><hc:pt2 x=\"4000\" y=\"2000\"/><hc:pt3 x=\"0\" y=\"2000\"/>",+ "<hp:flip horizontal=\"1\" vertical=\"0\"/><hp:rotationInfo angle=\"45\" centerX=\"0\" centerY=\"0\" rotateimage=\"1\"/>", zOrder: 9);+ var path = Package(Path.Combine(fx.NewFolder(), "rect.hwpx"), RefList(), Hp(Hr(rect)));++ var shape = Assert.IsType<HShape>(Paragraphs(ReadHwpx(path))[1].Inlines.Single());++ Assert.Equal((new HTransform(45, FlipHorizontal: true), 9), (shape.Transform, shape.ZOrder));+ // The mirroring the writers use is only for lines, whose direction it is.+ Assert.False(shape.FlipHorizontal);+ }++ // ───────────────────────── DOCX ─────────────────────────++ private HDocument ReadDocx(DocxBuilder docx)+ {+ var dir = fx.NewFolder();+ return DocxReader.Read(docx.Save(Path.Combine(dir, "test.docx")), Path.Combine(dir, "media"));+ }++ [Fact]+ public void Docx_line_rules_keep_their_meaning_and_the_document_grid()+ {+ var docx = new DocxBuilder();+ docx.Paragraph(P(R("배수"), "<w:spacing w:line=\"276\" w:lineRule=\"auto\"/>"))+ .Paragraph(P(R("고정"), "<w:spacing w:line=\"360\" w:lineRule=\"exact\"/>"))+ .Paragraph(P(R("최소"), "<w:spacing w:line=\"300\" w:lineRule=\"atLeast\"/>"))+ .Paragraph(P(R("격자"), "<w:spacing w:line=\"240\" w:lineRule=\"auto\"/>"))+ .Paragraph(P(R("격자 무시"), "<w:snapToGrid w:val=\"0\"/>"));+ docx.SectionProperties = DefaultPage + "<w:docGrid w:type=\"lines\" w:linePitch=\"360\" w:charSpace=\"-1024\"/>";++ var document = ReadDocx(docx);+ var paragraphs = Paragraphs(document);++ // 1.15 lines on an 18 pt grid: the writers still get the snapped "at least" height, the rule stays Word's multiple with its grid.+ Assert.Equal(new HDocumentGrid(HGridKind.Lines, 1800, CharSpace: -1024), document.Sections[0].Grid);+ Assert.Equal(new HLineSpacing(HLineSpacingKind.AtLeast, 1800 * 276 / 240), paragraphs[0].Format.LineSpacing);+ Assert.Equal(new HLineHeight(HLineHeightRule.Multiple, 276, GridPitch: 1800), paragraphs[0].Format.Layout!.LineHeight);+ Assert.Equal(new HLineHeight(HLineHeightRule.Exact, 1800), paragraphs[1].Format.Layout!.LineHeight);+ Assert.Equal(new HLineHeight(HLineHeightRule.AtLeast, 1500), paragraphs[2].Format.Layout!.LineHeight);+ Assert.Equal(new HLineHeight(HLineHeightRule.Multiple, 240, GridPitch: 1800), paragraphs[3].Format.Layout!.LineHeight);+ Assert.Equal((new HLineHeight(HLineHeightRule.Multiple, 240), false), (paragraphs[4].Format.Layout!.LineHeight, paragraphs[4].Format.Layout!.SnapToGrid));+ Assert.Equal(new HLineSpacing(HLineSpacingKind.Percent, 130), paragraphs[4].Format.LineSpacing);+ }++ [Fact]+ public void Docx_runs_keep_their_four_fonts_scale_spacing_and_position()+ {+ var docx = new DocxBuilder();+ docx.Paragraph(P(R("글자", "<w:rFonts w:ascii=\"Arial\" w:hAnsi=\"Calibri\" w:eastAsia=\"바탕\" w:cs=\"Arial Unicode MS\" w:hint=\"eastAsia\"/><w:w w:val=\"80\"/><w:spacing w:val=\"40\"/><w:position w:val=\"6\"/>")))+ .Paragraph(P(R("테마", "<w:rFonts w:cstheme=\"minorBidi\"/>")));++ var paragraphs = Paragraphs(ReadDocx(docx));++ var format = Assert.IsType<HText>(paragraphs[0].Inlines.Single()).Format;+ Assert.Equal(("Arial", "바탕"), (format.Font, format.EastAsianFont)); // what the writers use+ Assert.Equal(new HCharLayout(WordFonts: new HWordFonts("Arial", "Calibri", "바탕", "Arial Unicode MS", "eastAsia"), Scale: 80, LetterSpacing: 200, Position: 300), format.Layout);+ // Without a theme part the complex script theme font is unknown; the other fonts come from the defaults.+ Assert.Equal(new HWordFonts("맑은 고딕", "맑은 고딕", "맑은 고딕", null), Assert.IsType<HText>(paragraphs[1].Inlines.Single()).Format.Layout!.WordFonts);+ }++ [Fact]+ public void Docx_paragraphs_keep_borders_shading_and_line_breaking()+ {+ var docx = new DocxBuilder();+ docx.Paragraph(P(R("테두리"),+ "<w:pBdr><w:top w:val=\"single\" w:sz=\"8\" w:space=\"4\" w:color=\"FF0000\"/><w:between w:val=\"dashed\" w:sz=\"4\" w:space=\"0\" w:color=\"auto\"/></w:pBdr>" ++ "<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"DDEEFF\"/><w:kinsoku w:val=\"0\"/><w:wordWrap w:val=\"0\"/><w:overflowPunct w:val=\"0\"/><w:topLinePunct/>" ++ "<w:autoSpaceDE w:val=\"0\"/><w:autoSpaceDN w:val=\"0\"/>"))+ .Paragraph(P(R("기본")));++ var paragraphs = Paragraphs(ReadDocx(docx));++ var border = paragraphs[0].Format.Layout!.Border!;+ Assert.Equal(new HBorder(HBorderStyle.Solid, 8 / 8.0 * 25.4 / 72, "#FF0000"), border.Borders.Top);+ Assert.Equal(HBorderStyle.None, border.Borders.Bottom.Style);+ Assert.Equal((HBorderStyle.Dash, "#DDEEFF", 400, true), (border.Between!.Value.Style, border.Fill, border.Offsets.Top, border.Connect));+ Assert.Equal(new HLineBreaking(HLatinBreak.BreakWord, Kinsoku: false, OverflowPunctuation: false, CompressPunctuation: true, AutoSpaceLatin: false, AutoSpaceDigits: false),+ paragraphs[0].Format.Layout!.Breaking);++ // Word's defaults when nothing is said.+ Assert.Equal(HParaBorder.None, paragraphs[1].Format.Layout!.Border);+ Assert.Equal(new HLineBreaking(HLatinBreak.KeepWord, Kinsoku: true, OverflowPunctuation: true, CompressPunctuation: false, AutoSpaceLatin: true, AutoSpaceDigits: true),+ paragraphs[1].Format.Layout!.Breaking);+ }++ [Fact]+ public void Docx_objects_keep_crop_rotation_mirroring_and_z_order_and_rows_their_split_setting()+ {+ var docx = new DocxBuilder { Settings = "<w:noLineBreaksAfter w:lang=\"ja-JP\" w:val=\"(「\"/><w:noLineBreaksBefore w:lang=\"ja-JP\" w:val=\")」。\"/>" };+ using var image = new MagickImage(MagickColors.Orange, 40, 20);+ var id = docx.Image(image.ToByteArray(MagickFormat.Png));+ var picture = Picture(id, 914400, 457200)+ .Replace("</pic:blipFill>", "<a:srcRect l=\"10000\" t=\"0\" r=\"25000\" b=\"5000\"/></pic:blipFill>", StringComparison.Ordinal)+ .Replace("<a:xfrm>", "<a:xfrm rot=\"5400000\" flipH=\"1\">", StringComparison.Ordinal);+ var position = "<wp:positionH relativeFrom=\"column\"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom=\"paragraph\"><wp:posOffset>0</wp:posOffset></wp:positionV>";+ var shape = "<wps:wsp><wps:spPr><a:xfrm rot=\"-1800000\"><a:off x=\"0\" y=\"0\"/><a:ext cx=\"914400\" cy=\"457200\"/></a:xfrm><a:prstGeom prst=\"rect\"/></wps:spPr><wps:bodyPr/></wps:wsp>";+ docx.Paragraph(P(Anchor(PictureUri, picture, 914400, 457200, position[..position.IndexOf("<wp:positionV", StringComparison.Ordinal)], position[position.IndexOf("<wp:positionV", StringComparison.Ordinal)..])+ .Replace("relativeHeight=\"1\"", "relativeHeight=\"251660288\"", StringComparison.Ordinal)))+ .Paragraph(P(Anchor(ShapeUri, shape, 914400, 457200, position[..position.IndexOf("<wp:positionV", StringComparison.Ordinal)], position[position.IndexOf("<wp:positionV", StringComparison.Ordinal)..])))+ .Paragraph("<w:tbl><w:tblGrid><w:gridCol w:w=\"2000\"/></w:tblGrid><w:tr><w:trPr><w:cantSplit/></w:trPr><w:tc>" + P(R("칸")) + "</w:tc></w:tr><w:tr><w:tc>" + P(R("칸")) + "</w:tc></w:tr></w:tbl>");++ var document = ReadDocx(docx);+ var inlines = Paragraphs(document).SelectMany(p => p.Inlines).ToList();++ var read = inlines.OfType<HImage>().Single();+ Assert.Equal(new HCrop(0.1, 0, 0.25, 0.05), read.Crop);+ Assert.Equal((new HTransform(90, FlipHorizontal: true), 251660288), (read.Transform, read.ZOrder));+ Assert.Equal(new HTransform(-30), inlines.OfType<HShape>().Single().Transform);+ Assert.Equal([true, false], document.Sections[0].Blocks.OfType<HTable>().Single().Rows.Select(r => r.CantSplit));+ Assert.Equal(new HKinsoku("ja-JP", ")」。", "(「"), Assert.Single(document.Kinsoku));+ }++ // ───────────────────────── Writers ─────────────────────────++ /// <summary>The parts of a written package (pictures by name only), to compare two writes.</summary>+ private static Dictionary<string, string> Parts(string package)+ {+ using var zip = ZipFile.OpenRead(package);+ return zip.Entries.ToDictionary(e => e.FullName, e =>+ {+ using var reader = new StreamReader(e.Open());+ return e.FullName.StartsWith("BinData/", StringComparison.Ordinal) || e.FullName.StartsWith("word/media/", StringComparison.Ordinal) ? "" : reader.ReadToEnd();+ });+ }++ [Fact]+ public void Layout_detail_does_not_change_written_files()+ {+ HDocument Build(bool detail)+ {+ var slots = HLanguageSlots.All(new HSlotFormat("궁서", 80, 5, 90, 10));+ HCharFormat Char(HCharFormat format) => detail+ ? format with { Layout = new HCharLayout(slots, new HWordFonts("A", "B", "C", "D"), 90, 100, 50) }+ : format;+ var paraLayout = new HParaLayout(new HLineHeight(HLineHeightRule.Multiple, 276, 1800),+ new HParaBorder(HBorders.Grid, "#FFFF00", new HInsets(1, 2, 3, 4), true), new HLineBreaking(HLatinBreak.BreakWord, Kinsoku: false), true, true);++ var document = new HDocument { Title = "제목" };+ var section = new HSection();+ if (detail)+ {+ section.Grid = new HDocumentGrid(HGridKind.Lines, 1800);+ var master = new HMasterPage(HMasterPageKind.Both);+ master.Blocks.Add(new HParagraph());+ section.MasterPages.Add(master);+ document.Kinsoku.Add(new HKinsoku(null, ")", "("));+ }+ document.Sections.Add(section);+ foreach (var bold in new[] { false, true, false })+ {+ var paragraph = new HParagraph+ {+ Format = new HParaFormat(Align: HAlign.Justify, LineSpacing: new HLineSpacing(HLineSpacingKind.Percent, 150), Layout: detail ? paraLayout : null),+ MarkFormat = Char(new HCharFormat(Size: 1100)),+ Lines = detail ? new HLineLayout([new HLineSegment(0, 0, 1000, 1000, 850, 600, 0, 42520, 0)], Estimated: true) : null,+ };+ paragraph.Inlines.Add(new HText(bold ? "굵게" : "보통", Char(new HCharFormat(Bold: bold, Size: 1100, Font: "Arial"))));+ paragraph.Inlines.Add(new HText(" 이어서", Char(new HCharFormat(Size: 1100))));+ paragraph.Inlines.Add(new HShape(HShapeKind.Rectangle)+ {+ Width = 2000,+ Height = 1000,+ Anchor = new HAnchor("COLUMN", "LEFT", 0, "PARA", "TOP", 0, "SQUARE", true),+ Transform = detail ? new HTransform(30, true) : null,+ ZOrder = detail ? 5 : null,+ });+ section.Blocks.Add(paragraph);+ }+ var table = new HTable { ColumnCount = 1, PageBreak = detail ? HTablePageBreak.None : null };+ var row = new HRow { CantSplit = detail };+ var cell = new HCell();+ cell.Blocks.Add(new HParagraph { Format = new HParaFormat(Layout: detail ? paraLayout : null) });+ row.Cells.Add(cell);+ table.Rows.Add(row);+ section.Blocks.Add(table);+ return document;+ }++ var dir = fx.NewFolder();+ string Write(string name, Action<HDocument, string> writer, bool detail)+ {+ var path = Path.Combine(dir, name);+ writer(Build(detail), path);+ return path;+ }+ Assert.Equal(Parts(Write("plain.hwpx", (d, p) => HwpxWriter.Write(d, p), false)), Parts(Write("detail.hwpx", (d, p) => HwpxWriter.Write(d, p), true)));+ Assert.Equal(Parts(Write("plain.docx", DocxWriter.Write, false)), Parts(Write("detail.docx", DocxWriter.Write, true)));+ Assert.Equal(PlainTextWriter.Write(Build(false)), PlainTextWriter.Write(Build(true)));+ Assert.Equal(MarkdownWriter.Write(Build(false), _ => null), MarkdownWriter.Write(Build(true), _ => null));+ }++ [Fact]+ public void Formats_compare_without_layout_detail_unless_asked()+ {+ var plain = new HCharFormat(Bold: true, Size: 1000);+ var detailed = plain with { Layout = new HCharLayout(Scale: 80) };+ Assert.Equal(plain, detailed);+ Assert.Equal(plain.GetHashCode(), detailed.GetHashCode());+ Assert.Equal(plain.ToString(), detailed.ToString());+ Assert.True(detailed.IsEmpty == plain.IsEmpty && new HCharFormat(Layout: new HCharLayout(Scale: 80)).IsEmpty);+ Assert.False(plain.SameLayout(detailed));+ Assert.True(detailed.SameLayout(detailed with { Layout = new HCharLayout(Scale: 80) }));++ var paragraph = new HParaFormat(Align: HAlign.Center);+ var withRule = paragraph with { Layout = new HParaLayout(new HLineHeight(HLineHeightRule.Multiple, 240)) };+ Assert.Equal(paragraph, withRule);+ Assert.False(paragraph.SameLayout(withRule));+ }++ // ───────────────────────── Style resolver ─────────────────────────++ [Fact]+ public void Style_resolver_gives_the_values_the_written_file_has()+ {+ // A document as the Markdown and HTML readers make it: most members left to the 한글 style.+ var numbering = new HNumbering();+ numbering.Levels.Add(new HNumberingLevel("DIGIT", "^1.", 1, Bullet: false));+ var document = new HDocument();+ var section = new HSection();+ document.Sections.Add(section);+ void Add(HParagraph paragraph, params HInline[] inlines)+ {+ paragraph.Inlines.AddRange(inlines);+ section.Blocks.Add(paragraph);+ }+ Add(new HParagraph(), new HText("기본", default), new HText(" 굵게", new HCharFormat(Bold: true)));+ Add(new HParagraph { HeadingLevel = 1 }, new HText("제목", default));+ Add(new HParagraph { List = new HListRef(numbering, 0, Numbered: true) }, new HText("항목", new HCharFormat(Font: "Arial", Spacing: -3)));+ Add(new HParagraph { Format = new HParaFormat(Align: HAlign.Center, Left: 1000, FirstLine: -500, LineSpacing: new HLineSpacing(HLineSpacingKind.Fixed, 2000)) },+ new HText("가운데", new HCharFormat(Size: 1400, Color: "#123456", Superscript: true)));+ var link = new HLink("https://example.com");+ link.Content.Add(new HText("링크", default));+ Add(new HParagraph(), link);++ var path = Path.Combine(fx.NewFolder(), "resolved.hwpx");+ HwpxWriter.Write(document, path);+ var written = HwpxReader.Read(path, Path.Combine(Path.GetDirectoryName(path)!, "media")).Sections[0].Blocks.Cast<HParagraph>().ToList();++ var resolver = StyleResolver.FromTemplate();+ var paragraphs = section.Blocks.Cast<HParagraph>().ToList();+ for (var i = 0; i < paragraphs.Count; i++)+ {+ var resolved = resolver.Paragraph(paragraphs[i]);+ Assert.Equal(written[i].Format, resolved with { RightToLeft = null }); // HWPX has no right-to-left paragraphs+ Assert.False(resolved.RightToLeft);+ Assert.NotNull(resolved.Layout!.LineHeight);+ Assert.NotNull(resolved.Layout.Breaking);++ var source = paragraphs[i].Inlines.SelectMany(x => x is HLink l ? l.Content.Select(c => (c, true)) : [(x, false)]).ToList();+ var read = written[i].Inlines.SelectMany(x => x is HLink l ? l.Content : [x]).Cast<HText>().ToList();+ Assert.Equal(source.Count, read.Count);+ for (var j = 0; j < source.Count; j++)+ {+ var format = resolver.Character(((HText)source[j].Item1).Format, paragraphs[i], link: source[j].Item2);+ Assert.Equal(read[j].Format, format);+ Assert.True(format.Layout!.Slots!.Hangul.Font is not null && format.Layout.Slots.User.Ratio is not null);+ }+ }+ Assert.Equal("Arial", resolver.Character(new HCharFormat(Font: "Arial"), paragraphs[0]).Layout!.Slots!.Other.Font);+ Assert.Equal(-3, resolver.Character(new HCharFormat(Spacing: -3), paragraphs[0]).Layout!.Slots!.Symbol.Spacing);+ }++ [Fact]+ public void Style_resolver_keeps_the_rules_the_source_set()+ {+ var resolver = StyleResolver.FromTemplate();+ var word = new HParagraph+ {+ Format = new HParaFormat(LineSpacing: new HLineSpacing(HLineSpacingKind.Percent, 150),+ Layout: new HParaLayout(new HLineHeight(HLineHeightRule.Multiple, 276), Breaking: new HLineBreaking(Kinsoku: false))),+ };+ var resolved = resolver.Paragraph(word);+ Assert.Equal(new HLineHeight(HLineHeightRule.Multiple, 276), resolved.Layout!.LineHeight);+ Assert.False(resolved.Layout.Breaking!.Kinsoku);+ Assert.NotNull(resolved.Layout.Breaking.Latin); // the rest from the style++ var fixedOnly = new HParagraph { Format = new HParaFormat(LineSpacing: new HLineSpacing(HLineSpacingKind.Fixed, 1800)) };+ Assert.Equal(new HLineHeight(HLineHeightRule.Exact, 1800), resolver.Paragraph(fixedOnly).Layout!.LineHeight);++ var narrow = new HCharFormat(Layout: new HCharLayout(HLanguageSlots.All(new HSlotFormat(Ratio: 70))));+ var slots = resolver.Character(narrow, fixedOnly).Layout!.Slots!;+ Assert.Equal(70, slots.Latin.Ratio);+ Assert.NotNull(slots.Latin.Font); // the font from the style+ }+}