HighlightTextBlock.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Data;
  8. using System.Windows.Documents;
  9. using System.Windows.Media;
  10. namespace HandyControl.Controls;
  11. public class HighlightTextBlock : TextBlock
  12. {
  13. public static readonly DependencyProperty SourceTextProperty =
  14. DependencyProperty.Register(nameof(SourceText), typeof(string), typeof(HighlightTextBlock),
  15. new PropertyMetadata(null, OnSourceTextChanged));
  16. public static readonly DependencyProperty QueriesTextProperty =
  17. DependencyProperty.Register(nameof(QueriesText), typeof(string), typeof(HighlightTextBlock),
  18. new PropertyMetadata(null, OnQueriesTextChanged));
  19. public static readonly DependencyProperty HighlightBrushProperty =
  20. DependencyProperty.Register(nameof(HighlightBrush), typeof(Brush), typeof(HighlightTextBlock));
  21. public static readonly DependencyProperty HighlightTextBrushProperty =
  22. DependencyProperty.Register(nameof(HighlightTextBrush), typeof(Brush), typeof(HighlightTextBlock));
  23. private static void OnSourceTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) =>
  24. ((HighlightTextBlock) d).RefreshInlines();
  25. private static void OnQueriesTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) =>
  26. ((HighlightTextBlock) d).RefreshInlines();
  27. /// <summary>
  28. /// Replace the original property Text for binding text.
  29. /// </summary>
  30. /// <remarks>
  31. /// Don't use the <see cref="TextBlock.Text"/> property!
  32. /// Because the <see cref="TextBlock.Text"/> has some unique behaviors
  33. /// that is not needed at <see cref="HighlightTextBlock"/> at <see cref="TextBlock"/>,
  34. /// which will cause some unexpected issue.
  35. /// </remarks>
  36. public string SourceText
  37. {
  38. get => (string) GetValue(SourceTextProperty);
  39. set => SetValue(SourceTextProperty, value);
  40. }
  41. /// <summary>
  42. /// Gets or sets the text that need to be highlighted.
  43. /// It can be an array of text separated by spaces.
  44. /// </summary>
  45. public string QueriesText
  46. {
  47. get => (string) GetValue(QueriesTextProperty);
  48. set => SetValue(QueriesTextProperty, value);
  49. }
  50. /// <summary>
  51. /// Gets or sets the <see cref="Brush"/> of the background of the highlight text.
  52. /// </summary>
  53. public Brush HighlightBrush
  54. {
  55. get => (Brush) GetValue(HighlightBrushProperty);
  56. set => SetValue(HighlightBrushProperty, value);
  57. }
  58. public Brush HighlightTextBrush
  59. {
  60. get => (Brush) GetValue(HighlightTextBrushProperty);
  61. set => SetValue(HighlightTextBrushProperty, value);
  62. }
  63. private void RefreshInlines()
  64. {
  65. Inlines.Clear();
  66. if (string.IsNullOrEmpty(SourceText)) return;
  67. if (string.IsNullOrEmpty(QueriesText))
  68. {
  69. Inlines.Add(SourceText);
  70. return;
  71. }
  72. var sourceText = SourceText;
  73. var queries = QueriesText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  74. var intervals = from query in queries.Distinct()
  75. from interval in GetQueryIntervals(sourceText, query)
  76. select interval;
  77. var mergedIntervals = MergeIntervals(intervals.ToList());
  78. var fragments = SplitTextByOrderedDisjointIntervals(sourceText, mergedIntervals);
  79. Inlines.AddRange(GenerateRunElement(fragments));
  80. }
  81. private IEnumerable GenerateRunElement(IEnumerable<Fragment> fragments)
  82. {
  83. return from item in fragments
  84. select item.IsQuery
  85. ? GetHighlightRun(item.Text)
  86. : new Run(item.Text);
  87. }
  88. private Run GetHighlightRun(string highlightText)
  89. {
  90. var run = new Run(highlightText);
  91. run.SetBinding(TextElement.BackgroundProperty, new Binding(nameof(HighlightBrush)) { Source = this });
  92. run.SetBinding(TextElement.ForegroundProperty, new Binding(nameof(HighlightTextBrush)) { Source = this });
  93. return run;
  94. }
  95. private static IEnumerable<Fragment> SplitTextByOrderedDisjointIntervals(string sourceText, List<Range> mergedIntervals)
  96. {
  97. if (string.IsNullOrEmpty(sourceText)) yield break;
  98. if (!mergedIntervals?.Any() ?? true)
  99. {
  100. yield return new Fragment { Text = sourceText, IsQuery = false };
  101. yield break;
  102. }
  103. var range0 = mergedIntervals.First();
  104. int start0 = range0.Start;
  105. int end0 = range0.End;
  106. if (start0 > 0) yield return new Fragment { Text = sourceText.Substring(0, start0), IsQuery = false };
  107. yield return new Fragment { Text = sourceText.Substring(start0, end0 - start0), IsQuery = true };
  108. int previousEnd = end0;
  109. foreach (var range in mergedIntervals.Skip(1))
  110. {
  111. int start = range.Start;
  112. int end = range.End;
  113. yield return new Fragment { Text = sourceText.Substring(previousEnd, start - previousEnd), IsQuery = false };
  114. yield return new Fragment { Text = sourceText.Substring(start, end - start), IsQuery = true };
  115. previousEnd = end;
  116. }
  117. if (previousEnd < sourceText.Length)
  118. yield return new Fragment { Text = sourceText.Substring(previousEnd), IsQuery = false };
  119. }
  120. private static List<Range> MergeIntervals(List<Range> intervals)
  121. {
  122. if (!intervals?.Any() ?? true) return new List<Range>();
  123. intervals.Sort((x, y) => x.Start != y.Start ? x.Start - y.Start : x.End - y.End);
  124. var pointer = intervals[0];
  125. int startPointer = pointer.Start;
  126. int endPointer = pointer.End;
  127. var result = new List<Range>();
  128. foreach (var range in intervals.Skip(1))
  129. {
  130. int start = range.Start;
  131. int end = range.End;
  132. if (start <= endPointer)
  133. {
  134. if (endPointer < end)
  135. {
  136. endPointer = end;
  137. }
  138. }
  139. else
  140. {
  141. result.Add(new Range { Start = startPointer, End = endPointer });
  142. startPointer = start;
  143. endPointer = end;
  144. }
  145. }
  146. result.Add(new Range { Start = startPointer, End = endPointer });
  147. return result;
  148. }
  149. private static IEnumerable<Range> GetQueryIntervals(string sourceText, string query)
  150. {
  151. if (string.IsNullOrEmpty(sourceText) || string.IsNullOrEmpty(query)) yield break;
  152. int nextStartIndex = 0;
  153. while (nextStartIndex < sourceText.Length)
  154. {
  155. int index = sourceText.IndexOf(query, nextStartIndex, StringComparison.CurrentCultureIgnoreCase);
  156. if (index == -1) yield break;
  157. nextStartIndex = index + query.Length;
  158. yield return new Range { Start = index, End = nextStartIndex };
  159. }
  160. }
  161. private struct Fragment
  162. {
  163. public string Text { get; set; }
  164. public bool IsQuery { get; set; }
  165. }
  166. private struct Range
  167. {
  168. public int Start { get; set; }
  169. public int End { get; set; }
  170. }
  171. }