using System.IO.Compression;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Xml.Linq;
namespace MiniSoftware;
///
/// Reads basic content from Word (.docx) files.
/// Supports reading paragraphs, tables, and embedded images without external dependencies.
///
internal static class DocxReader
{
private static readonly string[] VietnameseToneCompositions =
[
"aàáảãạ", "AÀÁẢÃẠ", "ăằắẳẵặ", "ĂẰẮẲẴẶ", "âầấẩẫậ", "ÂẦẤẨẪẬ",
"eèéẻẽẹ", "EÈÉẺẼẸ", "êềếểễệ", "ÊỀẾỂỄỆ", "iìíỉĩị", "IÌÍỈĨỊ",
"oòóỏõọ", "OÒÓỎÕỌ", "ôồốổỗộ", "ÔỒỐỔỖỘ", "ơờớởỡợ", "ƠỜỚỞỠỢ",
"uùúủũụ", "UÙÚỦŨỤ", "ưừứửữự", "ƯỪỨỬỮỰ", "yỳýỷỹỵ", "YỲÝỶỸỴ",
];
private static readonly XNamespace W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
private static readonly XNamespace R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
private static readonly XNamespace WP = "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing";
private static readonly XNamespace A = "http://schemas.openxmlformats.org/drawingml/2006/main";
private static readonly XNamespace PIC = "http://schemas.openxmlformats.org/drawingml/2006/picture";
private static readonly XNamespace REL = "http://schemas.openxmlformats.org/package/2006/relationships";
private static readonly XNamespace WPS = "http://schemas.microsoft.com/office/word/2010/wordprocessingShape";
private static readonly XNamespace WPG = "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup";
private static readonly XNamespace WP14 = "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing";
private static readonly XNamespace V = "urn:schemas-microsoft-com:vml";
private static readonly XNamespace MC = "http://schemas.openxmlformats.org/markup-compatibility/2006";
private static readonly XNamespace M = "http://schemas.openxmlformats.org/officeDocument/2006/math";
///
/// Per-document context for resolving SDT (content control) data bindings and
/// glossary placeholder doc-parts. Loaded once per Read() call.
///
private sealed class SdtContext
{
// storeItemID (with braces, upper-case GUID) -> custom XML data store
public Dictionary XmlStores { get; } = new(StringComparer.OrdinalIgnoreCase);
// glossary docPart name -> inline runs extracted from its docPartBody paragraphs
public Dictionary> InlinePlaceholders { get; } = new(StringComparer.OrdinalIgnoreCase);
}
[ThreadStatic] private static SdtContext? _sdtContext;
private static SdtContext LoadSdtContext(ZipArchive archive)
{
var ctx = new SdtContext();
// docProps/core.xml uses a reserved storeItemID for SDT data-binding.
var coreEntry = archive.GetEntry("docProps/core.xml");
if (coreEntry != null)
{
try
{
using var s = coreEntry.Open();
ctx.XmlStores["{6C3C8BC8-F283-45AE-878A-BAB7291924A1}"] = XDocument.Load(s);
}
catch { /* ignore malformed core.xml */ }
}
// customXml/itemPropsN.xml -> ds:datastoreItem ds:itemID maps to customXml/itemN.xml
XNamespace dsNs = "http://schemas.openxmlformats.org/officeDocument/2006/customXml";
foreach (var e in archive.Entries)
{
var path = e.FullName.Replace('\\', '/');
if (!path.StartsWith("customXml/itemProps", StringComparison.OrdinalIgnoreCase) ||
!path.EndsWith(".xml", StringComparison.OrdinalIgnoreCase))
continue;
try
{
XDocument props;
using (var s = e.Open())
props = XDocument.Load(s);
var item = props.Descendants(dsNs + "datastoreItem").FirstOrDefault();
var id = item?.Attribute(dsNs + "itemID")?.Value;
if (string.IsNullOrEmpty(id)) continue;
var itemPath = System.Text.RegularExpressions.Regex.Replace(
path, "itemProps", "item", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
var itemEntry = archive.GetEntry(itemPath);
if (itemEntry == null) continue;
using var s2 = itemEntry.Open();
ctx.XmlStores[id!] = XDocument.Load(s2);
}
catch { /* ignore individual store failures */ }
}
// Glossary docParts provide placeholder text shown when a bound SDT resolves to empty.
var glossaryEntry = archive.GetEntry("word/glossary/document.xml");
if (glossaryEntry != null)
{
try
{
XDocument glossDoc;
using (var s = glossaryEntry.Open())
glossDoc = XDocument.Load(s);
foreach (var dp in glossDoc.Descendants(W + "docPart"))
{
var name = dp.Element(W + "docPartPr")?.Element(W + "name")?.Attribute(W + "val")?.Value;
if (string.IsNullOrEmpty(name)) continue;
var body = dp.Element(W + "docPartBody");
if (body == null) continue;
var runs = new List();
foreach (var p in body.Elements(W + "p"))
{
foreach (var r in p.Elements(W + "r"))
runs.Add(r);
}
if (runs.Count > 0)
ctx.InlinePlaceholders[name!] = runs;
}
}
catch { /* ignore malformed glossary */ }
}
return ctx;
}
private static string? ResolveSdtBoundValue(XElement sdtPr)
{
var ctx = _sdtContext;
if (ctx == null) return null;
var dataBinding = sdtPr.Element(W + "dataBinding");
if (dataBinding == null) return null;
var storeItemID = dataBinding.Attribute(W + "storeItemID")?.Value;
var xpath = dataBinding.Attribute(W + "xpath")?.Value;
var prefixMappings = dataBinding.Attribute(W + "prefixMappings")?.Value ?? "";
if (string.IsNullOrEmpty(storeItemID) || string.IsNullOrEmpty(xpath)) return null;
if (!ctx.XmlStores.TryGetValue(storeItemID, out var doc) || doc.Root == null) return null;
var nsMgr = new System.Xml.XmlNamespaceManager(new System.Xml.NameTable());
foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(
prefixMappings, @"xmlns:([\w-]+)\s*=\s*['""]([^'""]+)['""]"))
{
try { nsMgr.AddNamespace(m.Groups[1].Value, m.Groups[2].Value); } catch { }
}
try
{
var node = System.Xml.XPath.Extensions.XPathEvaluate(doc, xpath, nsMgr);
if (node is IEnumerable