ROTATES 2

This commit is contained in:
melekhin
2026-08-10 13:58:11 +07:00
parent 265bfc7419
commit 9c81a084f1
3 changed files with 452 additions and 268 deletions
+397 -182
View File
@@ -2,10 +2,7 @@
/// <summary> /// <summary>
/// Выполняет замену всех вхождений ключей из словаря на соответствующие массивы значений. /// Выполняет замену всех вхождений ключей из словаря на соответствующие массивы значений.
/// Каждое значение из массива помещается в отдельный параграф, причём первое значение /// Поддерживает разрывы страниц и смену ориентации (альбомная/книжная) через <see cref="ReplaceItem"/>.
/// остаётся в текущем параграфе, а последующие создают новые.
/// Текст между вхождениями и после последнего сохраняется в соответствующих параграфах.
/// Поддерживает разрывы страниц и смену ориентации (альбомная/книжная) через <see cref="ReplaceItem.SplitValue"/>.
/// </summary> /// </summary>
internal static class MultiReplaceExt internal static class MultiReplaceExt
{ {
@@ -16,13 +13,15 @@ internal static class MultiReplaceExt
internal static void Replace(this Body body, string oldValue, IEnumerable<string> newValues, StringComparison comparisonType) internal static void Replace(this Body body, string oldValue, IEnumerable<string> newValues, StringComparison comparisonType)
{ {
if (body is null || string.IsNullOrEmpty(oldValue) || newValues is null) return; if (body is null || string.IsNullOrEmpty(oldValue) || newValues is null) return;
body.Replace(new Dictionary<string, IEnumerable<string>> { { oldValue, newValues } }, comparisonType); var dict = new Dictionary<string, IEnumerable<string>> { { oldValue, newValues } };
body.Replace(dict, comparisonType);
} }
internal static void Replace(this Body body, string oldValue, IEnumerable<ReplaceItem> newValues, StringComparison comparisonType) internal static void Replace(this Body body, string oldValue, IEnumerable<ReplaceItem> newValues, StringComparison comparisonType)
{ {
if (body is null || string.IsNullOrEmpty(oldValue) || newValues is null) return; if (body is null || string.IsNullOrEmpty(oldValue) || newValues is null) return;
body.Replace(new Dictionary<string, IEnumerable<ReplaceItem>> { { oldValue, newValues } }, comparisonType); var dict = new Dictionary<string, IEnumerable<ReplaceItem>> { { oldValue, newValues } };
body.Replace(dict, comparisonType);
} }
#endregion #endregion
@@ -32,29 +31,27 @@ internal static class MultiReplaceExt
internal static void Replace(this Body body, IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements, StringComparison comparisonType) internal static void Replace(this Body body, IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements, StringComparison comparisonType)
{ {
if (body is null || replacements is null) return; if (body is null || replacements is null) return;
ReplaceInBody(body, replacements, null, comparisonType);
}
internal static void Replace(this Body body, IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>> replacements, StringComparison comparisonType)
{
if (body is null || replacements is null) return;
ReplaceInBody(body, null, replacements, comparisonType);
}
private static void ReplaceInBody(
Body body,
IEnumerable<KeyValuePair<string, IEnumerable<string>>>? stringReplacements,
IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>>? itemReplacements,
StringComparison comparisonType)
{
var paragraphs = body.Elements<Paragraph>().ToList(); var paragraphs = body.Elements<Paragraph>().ToList();
for (int i = paragraphs.Count - 1; i >= 0; i--) for (int i = paragraphs.Count - 1; i >= 0; i--)
{ {
var p = paragraphs[i]; var p = paragraphs[i];
if (p?.Parent is null) continue; if (p?.Parent is null) continue;
var newParas = ProcessMultiReplacements(p, replacements, null, comparisonType);
if (newParas is not null && newParas.Count > 0)
ParagraphReplacer.ReplaceParagraph(p, newParas);
}
}
var newParas = ProcessMultiReplacements(p, stringReplacements, itemReplacements, comparisonType); internal static void Replace(this Body body, IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>> replacements, StringComparison comparisonType)
if (newParas is { Count: > 0 }) {
if (body is null || replacements is null) return;
var paragraphs = body.Elements<Paragraph>().ToList();
for (int i = paragraphs.Count - 1; i >= 0; i--)
{
var p = paragraphs[i];
if (p?.Parent is null) continue;
var newParas = ProcessMultiReplacements(p, null, replacements, comparisonType);
if (newParas is not null && newParas.Count > 0)
ParagraphReplacer.ReplaceParagraph(p, newParas); ParagraphReplacer.ReplaceParagraph(p, newParas);
} }
} }
@@ -65,13 +62,14 @@ internal static class MultiReplaceExt
internal static bool ReplaceWithMultiple(this Paragraph? paragraph, string oldValue, IEnumerable<string> newValues, StringComparison comparisonType) internal static bool ReplaceWithMultiple(this Paragraph? paragraph, string oldValue, IEnumerable<string> newValues, StringComparison comparisonType)
{ {
if (paragraph?.Parent is null || string.IsNullOrEmpty(oldValue) || newValues is null || !newValues.Any()) if (paragraph is null || string.IsNullOrEmpty(oldValue) || newValues is null || newValues.Count() == 0)
return false; return false;
var dict = new Dictionary<string, IEnumerable<string>> { { oldValue, newValues } }; var dict = new Dictionary<string, IEnumerable<string>> { { oldValue, newValues } };
var newParas = ProcessMultiReplacements(paragraph, dict, null, comparisonType); var newParas = ProcessMultiReplacements(paragraph, dict, null, comparisonType);
if (newParas is null || newParas.Count == 0) return false;
if (newParas is { Count: > 0 }) if (paragraph.Parent is not null)
{ {
ParagraphReplacer.ReplaceParagraph(paragraph, newParas); ParagraphReplacer.ReplaceParagraph(paragraph, newParas);
return true; return true;
@@ -81,13 +79,14 @@ internal static class MultiReplaceExt
internal static bool ReplaceWithMultiple(this Paragraph? paragraph, string oldValue, IEnumerable<ReplaceItem> newValues, StringComparison comparisonType) internal static bool ReplaceWithMultiple(this Paragraph? paragraph, string oldValue, IEnumerable<ReplaceItem> newValues, StringComparison comparisonType)
{ {
if (paragraph?.Parent is null || string.IsNullOrEmpty(oldValue) || newValues is null || !newValues.Any()) if (paragraph is null || string.IsNullOrEmpty(oldValue) || newValues is null || newValues.Count() == 0)
return false; return false;
var dict = new Dictionary<string, IEnumerable<ReplaceItem>> { { oldValue, newValues } }; var dict = new Dictionary<string, IEnumerable<ReplaceItem>> { { oldValue, newValues } };
var newParas = ProcessMultiReplacements(paragraph, null, dict, comparisonType); var newParas = ProcessMultiReplacements(paragraph, null, dict, comparisonType);
if (newParas is null || newParas.Count == 0) return false;
if (newParas is { Count: > 0 }) if (paragraph.Parent is not null)
{ {
ParagraphReplacer.ReplaceParagraph(paragraph, newParas); ParagraphReplacer.ReplaceParagraph(paragraph, newParas);
return true; return true;
@@ -103,23 +102,26 @@ internal static class MultiReplaceExt
Paragraph paragraph, Paragraph paragraph,
IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements, IEnumerable<KeyValuePair<string, IEnumerable<string>>> replacements,
StringComparison comparisonType) StringComparison comparisonType)
=> ProcessMultiReplacements(paragraph, replacements, null, comparisonType); {
return ProcessMultiReplacements(paragraph, replacements, null, comparisonType);
}
internal static List<Paragraph>? ProcessParagraphWithAllReplacements( internal static List<Paragraph>? ProcessParagraphWithAllReplacements(
Paragraph paragraph, Paragraph paragraph,
IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>> replacements, IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>> replacements,
StringComparison comparisonType) StringComparison comparisonType)
=> ProcessMultiReplacements(paragraph, null, replacements, comparisonType); {
return ProcessMultiReplacements(paragraph, null, replacements, comparisonType);
}
internal static List<Paragraph>? ProcessParagraphWithAllReplacements( internal static List<Paragraph>? ProcessParagraphWithAllReplacements(
Paragraph paragraph, Paragraph paragraph,
IEnumerable<KeyValuePair<string, string>> replacements, IEnumerable<KeyValuePair<string, string>> replacements,
StringComparison comparisonType) StringComparison comparisonType)
{ {
var dict = replacements Dictionary<string, IEnumerable<string>> dict = replacements
.Where(kvp => !string.IsNullOrEmpty(kvp.Key)) .Where(kvp => !string.IsNullOrEmpty(kvp.Key))
.ToDictionary(kvp => kvp.Key, kvp => (IEnumerable<string>)[kvp.Value]); .ToDictionary(kvp => kvp.Key, kvp => (IEnumerable<string>)[kvp.Value]);
return ProcessMultiReplacements(paragraph, dict, null, comparisonType); return ProcessMultiReplacements(paragraph, dict, null, comparisonType);
} }
@@ -135,9 +137,9 @@ internal static class MultiReplaceExt
private class Match private class Match
{ {
public MatchDefinition Definition { get; init; } = null!; public MatchDefinition Definition { get; set; } = null!;
public int Start { get; init; } public int Start { get; set; }
public int End { get; init; } public int End { get; set; }
} }
private class RunSegment(Run run, string text, int start, int end) private class RunSegment(Run run, string text, int start, int end)
@@ -156,15 +158,13 @@ internal static class MultiReplaceExt
private static ParagraphStructure AnalyzeParagraphStructure(List<Run> runs) private static ParagraphStructure AnalyzeParagraphStructure(List<Run> runs)
{ {
var segments = new List<RunSegment>(runs.Count); var segments = new List<RunSegment>();
var sb = new StringBuilder(); var sb = new StringBuilder();
int pos = 0; int pos = 0;
foreach (var run in runs) foreach (var run in runs)
{ {
string text = GetRunText(run); string text = GetRunText(run);
if (string.IsNullOrEmpty(text)) continue; if (string.IsNullOrEmpty(text)) continue;
segments.Add(new RunSegment(run, text, pos, pos + text.Length)); segments.Add(new RunSegment(run, text, pos, pos + text.Length));
sb.Append(text); sb.Append(text);
pos += text.Length; pos += text.Length;
@@ -184,18 +184,16 @@ internal static class MultiReplaceExt
private static Paragraph CloneParagraphWithoutSection(Paragraph original) private static Paragraph CloneParagraphWithoutSection(Paragraph original)
{ {
var newPara = new Paragraph(); var newPara = new Paragraph();
if (original.ParagraphProperties is null) return newPara; if (original.ParagraphProperties is not null)
{
var newProps = new ParagraphProperties(); var newProps = new ParagraphProperties();
foreach (var child in original.ParagraphProperties.ChildElements) foreach (var child in original.ParagraphProperties.ChildElements)
{ {
if (child is not SectionProperties and not PageBreakBefore) if (child is not SectionProperties && child is not PageBreakBefore)
newProps.AppendChild(child.CloneNode(true)); newProps.AppendChild(child.CloneNode(true));
} }
if (newProps.HasChildren)
newPara.ParagraphProperties = newProps; newPara.ParagraphProperties = newProps;
}
return newPara; return newPara;
} }
@@ -207,29 +205,28 @@ internal static class MultiReplaceExt
foreach (var seg in structure.Segments) foreach (var seg in structure.Segments)
{ {
if (seg.End <= position) continue; if (seg.End <= position) continue;
if (seg.Start >= position) if (seg.Start >= position)
{ {
newPara.AppendChild(seg.Run.CloneNode(true)); newPara.AppendChild(seg.Run.CloneNode(true));
} }
else else if (seg.End > position)
{ {
var runClone = (Run)seg.Run.CloneNode(true); var runClone = (Run)seg.Run.CloneNode(true);
runClone.RemoveAllChildren<Text>(); // Упрощенная очистка foreach (var t in runClone.Elements<Text>().ToList()) t.Remove();
int offset = position - seg.Start; int offset = position - seg.Start;
runClone.AppendChild(new Text(seg.Text.Substring(offset))); string newText = seg.Text.Substring(offset);
runClone.AppendChild(new Text(newText));
newPara.AppendChild(runClone); newPara.AppendChild(runClone);
} }
} }
foreach (var run in newPara.Descendants<Run>().Where(r => !r.HasChildren).ToList())
// Удаляем пустые Run-ы без вложений run.Remove();
newPara.Elements<Run>().Where(r => !r.HasChildren).ToList().ForEach(r => r.Remove()); if (!newPara.ChildElements.OfType<Run>().Any() && newPara.ParagraphProperties is null)
return null;
return !newPara.Elements<Run>().Any() && newPara.ParagraphProperties is null ? null : newPara; return newPara;
} }
private static void InsertFormattedRun(Paragraph para, ReplaceItem item, ParagraphStructure structure, int position) private static void InsertFormattedRun(Paragraph para, string text, ParagraphStructure structure, int position)
{ {
var seg = structure.Segments.FirstOrDefault(s => position >= s.Start && position < s.End); var seg = structure.Segments.FirstOrDefault(s => position >= s.Start && position < s.End);
if (seg is null) return; if (seg is null) return;
@@ -237,87 +234,176 @@ internal static class MultiReplaceExt
var textRun = new Run(); var textRun = new Run();
if (seg.Run.RunProperties is not null) if (seg.Run.RunProperties is not null)
textRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true); textRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true);
textRun.AppendChild(new Text(text));
textRun.AppendChild(new Text(item.Text ?? string.Empty));
para.AppendChild(textRun); para.AppendChild(textRun);
} }
/// <summary> /// <summary>
/// Добавляет SectionProperties к параграфу. Все значения (PageSize, PageMargin) берутся из документа. /// Добавляет SectionProperties к параграфу. Все значения (PageSize, PageMargin) берутся из документа.
/// Для книжных секций (addPageSize=false) Orient не устанавливается (not set).
/// </summary> /// </summary>
private static void AddSectionProperties(Paragraph para, PageBreakType splitValue, bool addPageSize, SectionProperties? sourceSection, SectionProperties? portraitSection) private static void AddSectionProperties(
Paragraph para,
BreakType splitValue,
bool addPageSize,
SectionProperties sourceSection,
SectionProperties portraitSection)
{ {
if (para is null) return; if (para is null) return;
// Удаляем существующие секции и разрывы
if (para.ParagraphProperties is not null) if (para.ParagraphProperties is not null)
{ {
para.ParagraphProperties.RemoveAllChildren<SectionProperties>(); var sections = para.ParagraphProperties.Elements<SectionProperties>().ToList();
para.ParagraphProperties.RemoveAllChildren<PageBreakBefore>(); foreach (var sec in sections) sec.Remove();
var pageBreaks = para.ParagraphProperties.Elements<PageBreakBefore>().ToList();
foreach (var pb in pageBreaks) pb.Remove();
} }
para.ParagraphProperties ??= new ParagraphProperties(); para.ParagraphProperties ??= new ParagraphProperties();
var sectionProps = new SectionProperties(); var sectionProps = new SectionProperties();
// Добавляем PageSize var pageSizeClone = CreatePageSizeClone(addPageSize, splitValue, sourceSection, portraitSection);
var sizeSource = addPageSize ? sourceSection : portraitSection; if (pageSizeClone is not null)
var sourcePageSize = sizeSource?.GetFirstChild<PageSize>() sectionProps.AppendChild(pageSizeClone);
?? portraitSection?.GetFirstChild<PageSize>()
?? sourceSection?.GetFirstChild<PageSize>();
if (sourcePageSize is not null) var marginClone = CreateMarginClone(addPageSize, splitValue, sourceSection, portraitSection);
if (marginClone is not null)
sectionProps.AppendChild(marginClone);
sectionProps.AppendChild(new SectionType { Val = SectionMarkValues.NextPage });
para.ParagraphProperties.AppendChild(sectionProps);
}
private static PageSize? CreatePageSizeClone(
bool addPageSize,
BreakType splitValue,
SectionProperties sourceSection,
SectionProperties portraitSection)
{ {
var pageSizeClone = (PageSize)sourcePageSize.CloneNode(true); if (!addPageSize && splitValue != BreakType.NewLandscapeSection)
bool sourceIsLandscape = pageSizeClone.Orient?.Value == PageOrientationValues.Landscape || return null;
pageSizeClone.Width?.Value > pageSizeClone.Height?.Value;
bool targetIsLandscape = addPageSize && splitValue == PageBreakType.NewLandscapeSection; SectionProperties? sizeSource = addPageSize ? sourceSection : portraitSection;
var sourcePageSize = sizeSource?.GetFirstChild<PageSize>()
?? portraitSection.GetFirstChild<PageSize>()
?? sourceSection.GetFirstChild<PageSize>();
if (sourcePageSize is null)
return null;
var clone = (PageSize)sourcePageSize.CloneNode(true);
bool sourceIsLandscape = clone.Orient?.Value == PageOrientationValues.Landscape ||
(clone.Width?.Value > clone.Height?.Value);
bool targetIsLandscape = addPageSize && splitValue == BreakType.NewLandscapeSection;
if (targetIsLandscape && !sourceIsLandscape) if (targetIsLandscape && !sourceIsLandscape)
{
clone.SwapValues();
clone.Orient = PageOrientationValues.Landscape;
}
else if (!targetIsLandscape && sourceIsLandscape)
{
clone.SwapValues();
clone.Orient = addPageSize ? PageOrientationValues.Portrait : null;
}
else
{
clone.Orient = targetIsLandscape ? PageOrientationValues.Landscape :
addPageSize ? PageOrientationValues.Portrait : null;
}
return clone;
}
private static PageMargin? CreateMarginClone(
bool addPageSize,
BreakType splitValue,
SectionProperties sourceSection,
SectionProperties portraitSection)
{
PageMargin? marginToUse = null;
if (addPageSize)
{
var sourceMargin = sourceSection?.GetFirstChild<PageMargin>()
?? portraitSection?.GetFirstChild<PageMargin>();
if (sourceMargin is not null)
{
var clone = (PageMargin)sourceMargin.CloneNode(true);
var sourceOrient = sourceSection?.GetFirstChild<PageSize>()?.Orient;
bool sourceIsLandscape = sourceOrient?.Value == PageOrientationValues.Landscape ||
(sourceSection?.GetFirstChild<PageSize>()?.Width?.Value > sourceSection?.GetFirstChild<PageSize>()?.Height?.Value);
if ((splitValue == BreakType.NewLandscapeSection && !sourceIsLandscape) ||
(splitValue == BreakType.NewPortraitSection && sourceIsLandscape))
{
clone.SwapBottomRight();
}
marginToUse = clone;
}
}
else
{
var portraitMargin = portraitSection?.GetFirstChild<PageMargin>();
if (portraitMargin is not null)
marginToUse = (PageMargin)portraitMargin.CloneNode(true);
}
return marginToUse;
}
private static void EnsureBodyLandscapeSection(
Body body,
SectionProperties sourceSection,
bool sectionChangeInsideGroup,
BreakType? lastOrientation)
{
if (body is null || sourceSection is null) return;
var sourcePageSize = sourceSection.GetFirstChild<PageSize>();
if (sourcePageSize is null) return;
bool sourceIsLandscape = sourcePageSize.Orient?.Value == PageOrientationValues.Landscape ||
(sourcePageSize.Width?.Value > sourcePageSize.Height?.Value);
bool lastIsPortrait = lastOrientation.HasValue && lastOrientation.Value == BreakType.NewPortraitSection;
if (!(sourceIsLandscape && sectionChangeInsideGroup && lastIsPortrait))
return;
foreach (var bodySec in body.Elements<SectionProperties>())
{
var ps = bodySec.GetFirstChild<PageSize>();
if (ps is not null && ps.Orient?.Value == PageOrientationValues.Landscape)
return;
}
var bodySection = new SectionProperties();
var pageSizeClone = (PageSize)sourcePageSize.CloneNode(true);
if (pageSizeClone.Orient?.Value != PageOrientationValues.Landscape)
{ {
pageSizeClone.SwapValues(); pageSizeClone.SwapValues();
pageSizeClone.Orient = PageOrientationValues.Landscape; pageSizeClone.Orient = PageOrientationValues.Landscape;
} }
else if (!targetIsLandscape && sourceIsLandscape) bodySection.AppendChild(pageSizeClone);
{
pageSizeClone.SwapValues();
pageSizeClone.Orient = addPageSize ? PageOrientationValues.Portrait : null;
}
else
{
pageSizeClone.Orient = targetIsLandscape ? PageOrientationValues.Landscape : (addPageSize ? PageOrientationValues.Portrait : null);
}
sectionProps.AppendChild(pageSizeClone);
}
// Копируем PageMargin var sourceMargin = sourceSection.GetFirstChild<PageMargin>();
PageMargin? marginToUse = null;
if (addPageSize)
{
var sourceMargin = sourceSection?.GetFirstChild<PageMargin>() ?? portraitSection?.GetFirstChild<PageMargin>();
if (sourceMargin is not null) if (sourceMargin is not null)
{ {
var marginClone = (PageMargin)sourceMargin.CloneNode(true); var marginClone = (PageMargin)sourceMargin.CloneNode(true);
var sourceIsLndscape = sourceSection?.GetFirstChild<PageSize>()?.Orient?.Value == PageOrientationValues.Landscape || if (sourceSection.GetFirstChild<PageSize>()?.Orient?.Value != PageOrientationValues.Landscape)
sourceSection?.GetFirstChild<PageSize>()?.Width?.Value > sourceSection?.GetFirstChild<PageSize>()?.Height?.Value;
if ((splitValue == PageBreakType.NewLandscapeSection && !sourceIsLndscape) ||
(splitValue == PageBreakType.NewPortraitSection && sourceIsLndscape))
{
marginClone.SwapBottomRight(); marginClone.SwapBottomRight();
bodySection.AppendChild(marginClone);
} }
marginToUse = marginClone;
bodySection.AppendChild(new SectionType { Val = SectionMarkValues.NextPage });
body.AppendChild(bodySection);
} }
}
else if (portraitSection?.GetFirstChild<PageMargin>() is { } portraitMargin) private static void MergeParagraph(Paragraph target, Paragraph source)
{ {
marginToUse = (PageMargin)portraitMargin.CloneNode(true); foreach (var child in source.ChildElements)
} target.AppendChild(child.CloneNode(true));
if (marginToUse is not null)
sectionProps.AppendChild(marginToUse);
sectionProps.AppendChild(new SectionType { Val = SectionMarkValues.NextPage });
para.ParagraphProperties.AppendChild(sectionProps);
} }
/// <summary>Основной алгоритм множественной замены с поддержкой разрывов и смены ориентации.</summary> /// <summary>Основной алгоритм множественной замены с поддержкой разрывов и смены ориентации.</summary>
@@ -327,61 +413,89 @@ internal static class MultiReplaceExt
IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>>? itemReplacements, IEnumerable<KeyValuePair<string, IEnumerable<ReplaceItem>>>? itemReplacements,
StringComparison comparisonType) StringComparison comparisonType)
{ {
var definitions = new List<MatchDefinition>(); var body = original.Ancestors<Body>().FirstOrDefault();
// 1. Сбор определений
var definitions = new List<MatchDefinition>();
if (stringReplacements is not null) if (stringReplacements is not null)
{ {
definitions.AddRange(stringReplacements foreach (var kvp in stringReplacements)
.Where(kvp => !string.IsNullOrEmpty(kvp.Key) && kvp.Value != null && kvp.Value.Any()) {
.Select(kvp => new MatchDefinition(kvp.Key, kvp.Value.Select(v => new ReplaceItem(v, PageBreakType.None))))); if (string.IsNullOrEmpty(kvp.Key) || kvp.Value is null || kvp.Value.Count() == 0) continue;
var items = kvp.Value.Select(v => new ReplaceItem(v));
definitions.Add(new MatchDefinition(kvp.Key, items));
}
} }
if (itemReplacements is not null) if (itemReplacements is not null)
{ {
definitions.AddRange(itemReplacements foreach (var kvp in itemReplacements)
.Where(kvp => !string.IsNullOrEmpty(kvp.Key) && kvp.Value != null && kvp.Value.Any()) {
.Select(kvp => new MatchDefinition(kvp.Key, kvp.Value))); if (string.IsNullOrEmpty(kvp.Key) || kvp.Value is null || kvp.Value.Count() == 0) continue;
definitions.Add(new MatchDefinition(kvp.Key, kvp.Value));
}
} }
if (definitions.Count == 0) return null; if (definitions.Count == 0) return null;
var runs = original.Elements<Run>().ToList(); // 2. Анализ структуры параграфа
var runs = original.Descendants<Run>().ToList();
if (runs.Count == 0) return null; if (runs.Count == 0) return null;
var structure = AnalyzeParagraphStructure(runs); var structure = AnalyzeParagraphStructure(runs);
string fullText = structure.FullText; string fullText = structure.FullText;
if (fullText.Length == 0) return null; if (fullText.Length == 0) return null;
// 3. Поиск всех вхождений
var matches = new List<Match>(); var matches = new List<Match>();
foreach (var def in definitions) foreach (var def in definitions)
{ {
int pos = 0; int pos = 0;
while ((pos = fullText.IndexOf(def.Key, pos, comparisonType)) != -1) while ((pos = fullText.IndexOf(def.Key, pos, comparisonType)) != -1)
{ {
matches.Add(new Match { Definition = def, Start = pos, End = pos + def.Key.Length }); matches.Add(new Match
{
Definition = def,
Start = pos,
End = pos + def.Key.Length
});
pos += def.Key.Length; pos += def.Key.Length;
} }
} }
if (matches.Count == 0) return null; if (matches.Count == 0) return null;
matches.Sort((a, b) => a.Start.CompareTo(b.Start)); matches.Sort((a, b) => a.Start.CompareTo(b.Start));
var body = original.Ancestors<Body>().FirstOrDefault(); // 4. Получаем исходную секцию для копирования (из original или из документа)
var sourceSection = original.ParagraphProperties?.GetFirstChild<SectionProperties>()?.CloneNode(true) as SectionProperties SectionProperties? sourceSection = original.ParagraphProperties?.GetFirstChild<SectionProperties>()?.CloneNode(true) as SectionProperties;
?? body?.Elements<SectionProperties>().LastOrDefault()?.CloneNode(true) as SectionProperties if (sourceSection is null && body is not null)
?? new SectionProperties(); {
sourceSection = body.Elements<SectionProperties>().LastOrDefault()?.CloneNode(true) as SectionProperties;
}
sourceSection ??= new SectionProperties();
var portraitSection = body?.Elements<SectionProperties>().FirstOrDefault()?.CloneNode(true) as SectionProperties SectionProperties? portraitSection = null;
?? new SectionProperties(); if (body is not null)
{
portraitSection = body.Elements<SectionProperties>().FirstOrDefault()?.CloneNode(true) as SectionProperties;
}
portraitSection ??= new SectionProperties();
// 5. Построение результата
var resultParas = new List<Paragraph>(); var resultParas = new List<Paragraph>();
Paragraph? currentPara = null; Paragraph? currentPara = null;
int currentPos = 0; int currentPos = 0;
bool sectionChangeInsideGroup = false; bool sectionChangeInsideGroup = false;
PageBreakType? lastOrientation = null; BreakType? lastOrientation = null;
foreach (var match in matches) // Состояние обработки группы
bool pageBreakBeforeNext = false;
BreakType? pendingOrientation = null;
bool firstSplitMarkerHandled = false;
int textCount = 0;
Paragraph? lastTextPara = null;
for (int i = 0; i < matches.Count; i++)
{ {
var match = matches[i];
// Текст перед совпадением
if (currentPos < match.Start) if (currentPos < match.Start)
{ {
var beforePara = CloneParagraphWithoutSection(original); var beforePara = CloneParagraphWithoutSection(original);
@@ -389,7 +503,6 @@ internal static class MultiReplaceExt
{ {
if (seg.End <= currentPos) continue; if (seg.End <= currentPos) continue;
if (seg.Start >= match.Start) break; if (seg.Start >= match.Start) break;
if (seg.Start >= currentPos && seg.End <= match.Start) if (seg.Start >= currentPos && seg.End <= match.Start)
{ {
beforePara.AppendChild(seg.Run.CloneNode(true)); beforePara.AppendChild(seg.Run.CloneNode(true));
@@ -398,99 +511,201 @@ internal static class MultiReplaceExt
{ {
int startOffset = Math.Max(0, currentPos - seg.Start); int startOffset = Math.Max(0, currentPos - seg.Start);
int endOffset = Math.Min(seg.Text.Length, match.Start - seg.Start); int endOffset = Math.Min(seg.Text.Length, match.Start - seg.Start);
var runClone = (Run)seg.Run.CloneNode(true); var runClone = (Run)seg.Run.CloneNode(true);
runClone.RemoveAllChildren<Text>(); foreach (var t in runClone.Elements<Text>().ToList()) t.Remove();
runClone.AppendChild(new Text(seg.Text.Substring(startOffset, endOffset - startOffset))); string textPart = seg.Text.Substring(startOffset, endOffset - startOffset);
runClone.AppendChild(new Text(textPart));
beforePara.AppendChild(runClone); beforePara.AppendChild(runClone);
} }
} }
if (beforePara.Elements<Run>().Any()) if (beforePara.ChildElements.OfType<Run>().Any())
{ {
resultParas.Add(beforePara); resultParas.Add(beforePara);
currentPara = beforePara; currentPara = beforePara;
lastTextPara = beforePara;
} }
} }
var values = match.Definition.Values.ToList(); var values = match.Definition.Values.ToList();
if (values.Count == 0) continue; if (values.Count == 0) continue;
for (int vIdx = 0; vIdx < values.Count; vIdx++) // Сбрасываем флаги для новой группы
pageBreakBeforeNext = false;
pendingOrientation = null;
firstSplitMarkerHandled = false;
textCount = 0;
lastTextPara = null;
foreach (var item in values)
{ {
var item = values[vIdx]; if (!string.IsNullOrEmpty(item.Text))
currentPara = CloneParagraphWithoutSection(original);
resultParas.Add(currentPara);
InsertFormattedRun(currentPara, item, structure, match.Start);
if (item.SplitValue is PageBreakType.NewLandscapeSection or PageBreakType.NewPortraitSection)
{ {
bool addPageSize = vIdx != 0; // Если есть отложенная ориентация — применяем её
var orientation = vIdx != 0 ? PageBreakType.NewLandscapeSection : item.SplitValue; if (pendingOrientation.HasValue)
{
var newPara = CloneParagraphWithoutSection(original);
resultParas.Add(newPara);
currentPara = newPara;
AddSectionProperties(currentPara, orientation, addPageSize, sourceSection, portraitSection); bool addPageSize = (pendingOrientation.Value == BreakType.NewLandscapeSection);
lastOrientation = item.SplitValue; AddSectionProperties(currentPara, pendingOrientation.Value, addPageSize, sourceSection, portraitSection);
lastOrientation = pendingOrientation;
sectionChangeInsideGroup = true; sectionChangeInsideGroup = true;
} pendingOrientation = null;
else if (item.SplitValue == PageBreakType.PageBreak) textCount++;
lastTextPara = currentPara;
if (pageBreakBeforeNext)
{ {
var seg = structure.Segments.FirstOrDefault(s => match.Start >= s.Start && match.Start < s.End);
var breakRun = new Run(new Break { Type = BreakValues.Page }); var breakRun = new Run(new Break { Type = BreakValues.Page });
if (seg?.Run.RunProperties is not null) currentPara.InsertAt(breakRun, 0);
breakRun.RunProperties = (RunProperties)seg.Run.RunProperties.CloneNode(true); pageBreakBeforeNext = false;
}
InsertFormattedRun(currentPara, item.Text, structure, match.Start);
}
else
{
var newPara = CloneParagraphWithoutSection(original);
resultParas.Add(newPara);
currentPara = newPara;
textCount++;
lastTextPara = currentPara;
if (pageBreakBeforeNext)
{
var breakRun = new Run(new Break { Type = BreakValues.Page });
currentPara.InsertAt(breakRun, 0);
pageBreakBeforeNext = false;
}
InsertFormattedRun(currentPara, item.Text, structure, match.Start);
}
}
else if (item.BreakValue.HasValue)
{
var breakType = item.BreakValue.Value;
if (breakType == BreakType.PageBreak)
{
if (currentPara is not null)
{
var breakRun = new Run(new Break { Type = BreakValues.Page });
var lastRun = currentPara.Descendants<Run>().LastOrDefault();
if (lastRun?.RunProperties is not null)
breakRun.RunProperties = (RunProperties)lastRun.RunProperties.CloneNode(true);
currentPara.AppendChild(breakRun); currentPara.AppendChild(breakRun);
} }
else
{
pageBreakBeforeNext = true;
}
}
else if (breakType == BreakType.NewLandscapeSection || breakType == BreakType.NewPortraitSection)
{
if (currentPara is null)
{
var newPara = CloneParagraphWithoutSection(original);
resultParas.Add(newPara);
currentPara = newPara;
AddSectionProperties(currentPara, breakType, false, sourceSection, portraitSection);
lastOrientation = breakType;
sectionChangeInsideGroup = true;
firstSplitMarkerHandled = true;
pendingOrientation = null;
textCount = 0;
lastTextPara = null;
}
else
{
if (!firstSplitMarkerHandled)
{
if (lastTextPara is not null)
{
if (lastTextPara.ParagraphProperties?.GetFirstChild<SectionProperties>() is null)
{
lastTextPara.ParagraphProperties ??= new ParagraphProperties();
var sourcePageSize = sourceSection.GetFirstChild<PageSize>();
if (sourcePageSize is not null)
{
lastTextPara.ParagraphProperties.AppendChild(sourceSection.CloneNode(true));
}
else
{
AddSectionProperties(lastTextPara, breakType, false, sourceSection, portraitSection);
}
lastOrientation = breakType;
sectionChangeInsideGroup = true;
}
firstSplitMarkerHandled = true;
pendingOrientation = null;
}
else
{
AddSectionProperties(currentPara, breakType, false, sourceSection, portraitSection);
lastOrientation = breakType;
sectionChangeInsideGroup = true;
firstSplitMarkerHandled = true;
pendingOrientation = null;
}
}
else
{
pendingOrientation = breakType;
}
}
}
}
} }
if (sectionChangeInsideGroup && lastOrientation.HasValue && currentPara?.ParagraphProperties?.GetFirstChild<SectionProperties>() is null) // Закрываем секцию, если была смена
if (sectionChangeInsideGroup && lastOrientation.HasValue && currentPara is not null)
{ {
AddSectionProperties(currentPara!, lastOrientation.Value, lastOrientation.Value == PageBreakType.NewLandscapeSection, sourceSection, portraitSection); if (currentPara.ParagraphProperties?.GetFirstChild<SectionProperties>() is null)
{
bool addPageSize = (lastOrientation.Value == BreakType.NewLandscapeSection);
AddSectionProperties(currentPara, lastOrientation.Value, addPageSize, sourceSection, portraitSection);
}
} }
if (body is not null && sourceSection.GetFirstChild<PageSize>() is { } sourcePageSize) EnsureBodyLandscapeSection(body!, sourceSection, sectionChangeInsideGroup, lastOrientation);
{
bool sourceIsLandscape = sourcePageSize.Orient?.Value == PageOrientationValues.Landscape || sourcePageSize.Width?.Value > sourcePageSize.Height?.Value;
bool lastIsPortrait = lastOrientation == PageBreakType.NewPortraitSection;
if (sourceIsLandscape && sectionChangeInsideGroup && lastIsPortrait && !body.Elements<SectionProperties>().Any(s => s.GetFirstChild<PageSize>()?.Orient?.Value == PageOrientationValues.Landscape))
{
var bodySection = new SectionProperties();
var pageSizeClone = (PageSize)sourcePageSize.CloneNode(true);
if (pageSizeClone.Orient?.Value != PageOrientationValues.Landscape)
{
pageSizeClone.SwapValues();
pageSizeClone.Orient = PageOrientationValues.Landscape;
}
bodySection.AppendChild(pageSizeClone);
if (sourceSection.GetFirstChild<PageMargin>() is { } sourceMargin)
{
var marginClone = (PageMargin)sourceMargin.CloneNode(true);
if (sourceSection.GetFirstChild<PageSize>()?.Orient?.Value != PageOrientationValues.Landscape)
{
marginClone.SwapBottomRight();
}
bodySection.AppendChild(marginClone);
}
bodySection.AppendChild(new SectionType { Val = SectionMarkValues.NextPage });
body.AppendChild(bodySection);
}
}
currentPos = match.End; currentPos = match.End;
} }
if (currentPos < fullText.Length && BuildRemainderParagraph(original, structure, currentPos) is { } remainderPara) // 6. Обработка остатка текста
if (currentPos < fullText.Length)
{ {
if (sectionChangeInsideGroup && lastOrientation.HasValue) var remainderPara = BuildRemainderParagraph(original, structure, currentPos);
if (remainderPara is not null)
{ {
remainderPara.InsertAt(new Run(new Break { Type = BreakValues.Page }), 0); if (pendingOrientation.HasValue)
AddSectionProperties(remainderPara, lastOrientation.Value, lastOrientation.Value == PageBreakType.NewLandscapeSection, sourceSection, portraitSection); {
var breakRun = new Run(new Break { Type = BreakValues.Page });
remainderPara.InsertAt(breakRun, 0);
bool addPageSize = (pendingOrientation.Value == BreakType.NewLandscapeSection);
AddSectionProperties(remainderPara, pendingOrientation.Value, addPageSize, sourceSection, portraitSection);
pendingOrientation = null;
}
else if (sectionChangeInsideGroup && lastOrientation.HasValue)
{
var breakRun = new Run(new Break { Type = BreakValues.Page });
remainderPara.InsertAt(breakRun, 0);
bool addPageSize = (lastOrientation.Value == BreakType.NewLandscapeSection);
AddSectionProperties(remainderPara, lastOrientation.Value, addPageSize, sourceSection, portraitSection);
} }
resultParas.Add(remainderPara); resultParas.Add(remainderPara);
} }
}
// 7. Очистка пустых параграфов
for (int i = resultParas.Count - 1; i >= 0; i--)
{
var p = resultParas[i];
if (!p.ChildElements.OfType<Run>().Any() && p.ParagraphProperties is null)
resultParas.RemoveAt(i);
}
resultParas.RemoveAll(p => !p.Elements<Run>().Any() && p.ParagraphProperties is null);
return resultParas.Count > 0 ? resultParas : null; return resultParas.Count > 0 ? resultParas : null;
} }
} }
+24 -55
View File
@@ -1,70 +1,39 @@
namespace QWERTYkez.WordProcessor; namespace QWERTYkez.WordProcessor;
/// <summary> /// <summary> Определяет тип разрыва или смены ориентации страницы </summary>
/// Определяет тип разрыва или смены ориентации страницы, применяется к элементам следующим после замены public enum BreakType
/// </summary>
public enum PageBreakType
{ {
/// <summary>Без разрыва или смены ориентации.</summary>
None,
/// <summary>Обычный разрыв страницы (новый лист).</summary> /// <summary>Обычный разрыв страницы (новый лист).</summary>
PageBreak, PageBreak,
/// <summary>Начать новую секцию с альбомной ориентацией страницы.</summary> /// <summary>Начать новую секцию с альбомной ориентацией страницы.</summary>
NewLandscapeSection, NewLandscapeSection,
/// <summary>Начать новую секцию с книжной ориентацией страницы.</summary> /// <summary>Начать новую секцию с книжной ориентацией страницы.</summary>
NewPortraitSection, NewPortraitSection,
} }
/// <summary> public class ReplaceItem
/// Представляет элемент замены текста, содержащий сам текст и указание
/// на тип разрыва или смены ориентации, который должен быть применён
/// после вставки этого текста.
/// </summary>
/// <remarks>
/// Используется в методах множественной замены, например,
/// <see cref="IWordWriter.ReplaceItem(string, IEnumerable{ReplaceItem})"/>.
/// </remarks>
public readonly struct ReplaceItem
{ {
/// <summary> private ReplaceItem() { }
/// Инициализирует новый экземпляр <see cref="ReplaceItem"/> с пустым текстом public ReplaceItem(string text) => _Text = text;
/// и типом разрыва <see cref="PageBreakType.None"/>. public ReplaceItem(BreakType item) => _BreakValue = item;
/// </summary>
public ReplaceItem() { }
/// <summary>
/// Инициализирует новый экземпляр <see cref="ReplaceItem"/> с указанным текстом public static implicit operator ReplaceItem(string text) => new(text);
/// и типом разрыва/смены ориентации. public static implicit operator ReplaceItem(BreakType item) => item switch
/// </summary>
/// <param name="text">Текст, который будет вставлен вместо плейсхолдера.</param>
/// <param name="splitValue">
/// Тип разрыва или смены ориентации, который будет применён после вставки текста.
/// По умолчанию <see cref="PageBreakType.None"/>.
/// </param>
public ReplaceItem(string text, PageBreakType splitValue = PageBreakType.None)
{ {
Text = text; BreakType.PageBreak => PageBreak,
SplitValue = splitValue; BreakType.NewLandscapeSection => NewLandscapeSection,
} BreakType.NewPortraitSection => NewPortraitSection,
_ => throw new NotImplementedException()
/// <summary> };
/// Получает текст, который будет вставлен вместо плейсхолдера.
/// </summary> public static ReplaceItem PageBreak { get; } = new() { _BreakValue = BreakType.PageBreak };
public string Text { get; init; } = string.Empty; public static ReplaceItem NewLandscapeSection { get; } = new() { _BreakValue = BreakType.NewLandscapeSection };
public static ReplaceItem NewPortraitSection { get; } = new() { _BreakValue = BreakType.NewPortraitSection };
/// <summary>
/// Получает тип разрыва или смены ориентации, который будет применён public string Text => _Text;
/// после вставки текста. public string _Text = string.Empty;
/// </summary>
public PageBreakType SplitValue { get; init; } = PageBreakType.None; public BreakType? BreakValue => _BreakValue;
public BreakType? _BreakValue;
/// <summary>
/// Определяет явное преобразование из строки в <see cref="ReplaceItem"/>.
/// </summary>
/// <param name="text">Строка текста.</param>
/// <returns>Новый экземпляр <see cref="ReplaceItem"/> с указанным текстом и <see cref="PageBreakType.None"/>.</returns>
public static explicit operator ReplaceItem(string text) => new() { Text = text };
} }
+12 -12
View File
@@ -77,7 +77,7 @@ internal static class SimplyReplaceExt
} }
} }
internal static bool SimpleReplace(this Paragraph? paragraph, string oldValue, string newValue, StringComparison comparisonType, PageBreakType splitValue = PageBreakType.None) internal static bool SimpleReplace(this Paragraph? paragraph, string oldValue, string newValue, StringComparison comparisonType, BreakType? splitValue = null)
{ {
if (paragraph is null || string.IsNullOrEmpty(oldValue)) if (paragraph is null || string.IsNullOrEmpty(oldValue))
return false; return false;
@@ -108,7 +108,7 @@ internal static class SimplyReplaceExt
} }
internal static bool SimpleReplace(this Paragraph? paragraph, string oldValue, string newValue, StringComparison comparisonType, bool breakPage) internal static bool SimpleReplace(this Paragraph? paragraph, string oldValue, string newValue, StringComparison comparisonType, bool breakPage)
=> SimpleReplace(paragraph, oldValue, newValue, comparisonType, breakPage ? PageBreakType.PageBreak : PageBreakType.None); => SimpleReplace(paragraph, oldValue, newValue, comparisonType, breakPage ? BreakType.PageBreak : null);
internal static void Replace(this Paragraph paragraph, IEnumerable<KeyValuePair<string, string>> replacements, StringComparison comparisonType) internal static void Replace(this Paragraph paragraph, IEnumerable<KeyValuePair<string, string>> replacements, StringComparison comparisonType)
{ {
@@ -139,7 +139,7 @@ internal static class SimplyReplaceExt
OldValue = kvp.Key, OldValue = kvp.Key,
NewValue = kvp.Value ?? string.Empty, NewValue = kvp.Value ?? string.Empty,
Index = pos, Index = pos,
SplitValue = PageBreakType.None BreakValue = null
}); });
pos += kvp.Key.Length; pos += kvp.Key.Length;
} }
@@ -159,7 +159,7 @@ internal static class SimplyReplaceExt
var nodesToReplace = FindNodesToReplace(structure, matchIndex, matchEnd); var nodesToReplace = FindNodesToReplace(structure, matchIndex, matchEnd);
if (nodesToReplace.Count > 0) if (nodesToReplace.Count > 0)
{ {
ExecuteReplacement(nodesToReplace, matchIndex, matchEnd, replacement.NewValue, replacement.SplitValue); ExecuteReplacement(nodesToReplace, matchIndex, matchEnd, replacement.NewValue, replacement.BreakValue);
} }
} }
} }
@@ -193,7 +193,7 @@ internal static class SimplyReplaceExt
OldValue = kvp.Key, OldValue = kvp.Key,
NewValue = kvp.Value.Text ?? string.Empty, NewValue = kvp.Value.Text ?? string.Empty,
Index = pos, Index = pos,
SplitValue = kvp.Value.SplitValue BreakValue = kvp.Value.BreakValue
}); });
pos += kvp.Key.Length; pos += kvp.Key.Length;
} }
@@ -213,7 +213,7 @@ internal static class SimplyReplaceExt
var nodesToReplace = FindNodesToReplace(structure, matchIndex, matchEnd); var nodesToReplace = FindNodesToReplace(structure, matchIndex, matchEnd);
if (nodesToReplace.Count > 0) if (nodesToReplace.Count > 0)
{ {
ExecuteReplacement(nodesToReplace, matchIndex, matchEnd, replacement.NewValue, replacement.SplitValue); ExecuteReplacement(nodesToReplace, matchIndex, matchEnd, replacement.NewValue, replacement.BreakValue);
} }
} }
} }
@@ -223,7 +223,7 @@ internal static class SimplyReplaceExt
internal string OldValue { get; set; } = null!; internal string OldValue { get; set; } = null!;
internal string NewValue { get; set; } = null!; internal string NewValue { get; set; } = null!;
internal int Index { get; set; } internal int Index { get; set; }
internal PageBreakType SplitValue { get; set; } = PageBreakType.None; internal BreakType? BreakValue { get; set; } = null;
} }
private static ParagraphStructure AnalyzeParagraphStructure(IEnumerable<Run> runs) private static ParagraphStructure AnalyzeParagraphStructure(IEnumerable<Run> runs)
@@ -287,7 +287,7 @@ internal static class SimplyReplaceExt
int matchStart, int matchStart,
int matchEnd, int matchEnd,
string newValue, string newValue,
PageBreakType splitValue) BreakType? splitValue)
{ {
if (nodesToReplace.Count == 0) return; if (nodesToReplace.Count == 0) return;
@@ -312,7 +312,7 @@ internal static class SimplyReplaceExt
nodesToReplace[i].Text.Text = string.Empty; nodesToReplace[i].Text.Text = string.Empty;
} }
if (splitValue == PageBreakType.PageBreak) if (splitValue == BreakType.PageBreak)
{ {
if (nodesToReplace[0].Text.Parent is Run run && run.Parent is Paragraph para) if (nodesToReplace[0].Text.Parent is Run run && run.Parent is Paragraph para)
{ {
@@ -322,7 +322,7 @@ internal static class SimplyReplaceExt
para.AppendChild(breakRun); para.AppendChild(breakRun);
} }
} }
else if (splitValue == PageBreakType.NewLandscapeSection || splitValue == PageBreakType.NewPortraitSection) else if (splitValue == BreakType.NewLandscapeSection || splitValue == BreakType.NewPortraitSection)
{ {
var firstText = nodesToReplace[0].Text; var firstText = nodesToReplace[0].Text;
if (firstText.Parent is Run run && run.Parent is Paragraph para) if (firstText.Parent is Run run && run.Parent is Paragraph para)
@@ -332,10 +332,10 @@ internal static class SimplyReplaceExt
} }
} }
private static void AddSectionProperties(Paragraph para, PageBreakType splitValue) private static void AddSectionProperties(Paragraph para, BreakType? splitValue)
{ {
if (para is null) return; if (para is null) return;
PageOrientationValues orientation = splitValue == PageBreakType.NewLandscapeSection PageOrientationValues orientation = splitValue == BreakType.NewLandscapeSection
? PageOrientationValues.Landscape ? PageOrientationValues.Landscape
: PageOrientationValues.Portrait; : PageOrientationValues.Portrait;