File size: 13,607 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Documents;
using System.Windows.Media;

namespace Microsoft.Management.UI.Internal
{
    /// <summary>
    /// Builds a paragraph based on Text + Bold + Highlight information.
    /// Bold are the segments of the text that should be bold, and Highlight are
    /// the segments of the text that should be highlighted (like search results).
    /// </summary>
    internal class ParagraphBuilder : INotifyPropertyChanged
    {
        /// <summary>
        /// The text spans that should be bold.
        /// </summary>
        private readonly List<TextSpan> boldSpans;

        /// <summary>
        /// The text spans that should be highlighted.
        /// </summary>
        private readonly List<TextSpan> highlightedSpans;

        /// <summary>
        /// The text displayed.
        /// </summary>
        private readonly StringBuilder textBuilder;

        /// <summary>
        /// Paragraph built in BuildParagraph.
        /// </summary>
        private readonly Paragraph paragraph;

        /// <summary>
        /// Initializes a new instance of the ParagraphBuilder class.
        /// </summary>
        /// <param name="paragraph">Paragraph we will be adding lines to in BuildParagraph.</param>
        internal ParagraphBuilder(Paragraph paragraph)
        {
            ArgumentNullException.ThrowIfNull(paragraph);

            this.paragraph = paragraph;
            this.boldSpans = new List<TextSpan>();
            this.highlightedSpans = new List<TextSpan>();
            this.textBuilder = new StringBuilder();
        }

        #region INotifyPropertyChanged Members
        /// <summary>
        /// Used to notify of property changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion

        /// <summary>
        /// Gets the number of highlights.
        /// </summary>
        internal int HighlightCount
        {
            get { return this.highlightedSpans.Count; }
        }

        /// <summary>
        /// Gets the paragraph built in BuildParagraph.
        /// </summary>
        internal Paragraph Paragraph
        {
            get { return this.paragraph; }
        }

        /// <summary>
        /// Called after all the AddText calls have been made to build the paragraph
        /// based on the current text.
        /// This method goes over 3 collections simultaneously:
        ///    1) characters in this.textBuilder
        ///    2) spans in this.boldSpans
        ///    3) spans in this.highlightedSpans
        /// And adds the minimal number of Inlines to the paragraph so that all
        /// characters that should be bold and/or highlighted are.
        /// </summary>
        internal void BuildParagraph()
        {
            this.paragraph.Inlines.Clear();

            int currentBoldIndex = 0;
            TextSpan? currentBoldSpan = this.boldSpans.Count == 0 ? (TextSpan?)null : this.boldSpans[0];
            int currentHighlightedIndex = 0;
            TextSpan? currentHighlightedSpan = this.highlightedSpans.Count == 0 ? (TextSpan?)null : this.highlightedSpans[0];

            bool currentBold = false;
            bool currentHighlighted = false;

            StringBuilder sequence = new StringBuilder();
            int i = 0;
            foreach (char c in this.textBuilder.ToString())
            {
                bool newBold = false;
                bool newHighlighted = false;

                ParagraphBuilder.MoveSpanToPosition(ref currentBoldIndex, ref currentBoldSpan, i, this.boldSpans);
                newBold = currentBoldSpan == null ? false : currentBoldSpan.Value.Contains(i);

                ParagraphBuilder.MoveSpanToPosition(ref currentHighlightedIndex, ref currentHighlightedSpan, i, this.highlightedSpans);
                newHighlighted = currentHighlightedSpan == null ? false : currentHighlightedSpan.Value.Contains(i);

                if (newBold != currentBold || newHighlighted != currentHighlighted)
                {
                    ParagraphBuilder.AddInline(this.paragraph, currentBold, currentHighlighted, sequence);
                }

                sequence.Append(c);

                currentHighlighted = newHighlighted;
                currentBold = newBold;
                i++;
            }

            ParagraphBuilder.AddInline(this.paragraph, currentBold, currentHighlighted, sequence);
        }

        /// <summary>
        /// Highlights all occurrences of <paramref name="search"/>.
        /// This is called after all calls to AddText have been made.
        /// </summary>
        /// <param name="search">Search string.</param>
        /// <param name="caseSensitive">True if search should be case sensitive.</param>
        /// <param name="wholeWord">True if we should search whole word only.</param>
        internal void HighlightAllInstancesOf(string search, bool caseSensitive, bool wholeWord)
        {
            this.highlightedSpans.Clear();

            if (search == null || search.Trim().Length == 0)
            {
                this.BuildParagraph();
                this.OnNotifyPropertyChanged("HighlightCount");
                return;
            }

            string text = this.textBuilder.ToString();
            StringComparison comparison = caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
            int start = 0;
            int match;
            while ((match = text.IndexOf(search, start, comparison)) != -1)
            {
                // false loop
                do
                {
                    if (wholeWord)
                    {
                        if (match > 0 && char.IsLetterOrDigit(text[match - 1]))
                        {
                            break;
                        }

                        if ((match + search.Length <= text.Length - 1) && char.IsLetterOrDigit(text[match + search.Length]))
                        {
                            break;
                        }
                    }

                    this.AddHighlight(match, search.Length);
                }
                while (false);

                start = match + search.Length;
            }

            this.BuildParagraph();
            this.OnNotifyPropertyChanged("HighlightCount");
        }

        /// <summary>
        /// Adds text to the paragraph later build with BuildParagraph.
        /// </summary>
        /// <param name="str">Text to be added.</param>
        /// <param name="bold">True if the text should be bold.</param>
        internal void AddText(string str, bool bold)
        {
            ArgumentNullException.ThrowIfNull(str);

            if (str.Length == 0)
            {
                return;
            }

            if (bold)
            {
                this.boldSpans.Add(new TextSpan(this.textBuilder.Length, str.Length));
            }

            this.textBuilder.Append(str);
        }

        /// <summary>
        /// Called before a derived class starts adding text
        /// to reset the current content.
        /// </summary>
        internal void ResetAllText()
        {
            this.boldSpans.Clear();
            this.highlightedSpans.Clear();
            this.textBuilder.Clear();
        }

        /// <summary>
        /// Adds an inline to <paramref name="currentParagraph"/> based on the remaining parameters.
        /// </summary>
        /// <param name="currentParagraph">Paragraph to add Inline to.</param>
        /// <param name="currentBold">True if text should be added in bold.</param>
        /// <param name="currentHighlighted">True if the text should be added with highlight.</param>
        /// <param name="sequence">The text to add and clear.</param>
        private static void AddInline(Paragraph currentParagraph, bool currentBold, bool currentHighlighted, StringBuilder sequence)
        {
            if (sequence.Length == 0)
            {
                return;
            }

            Run run = new Run(sequence.ToString());
            if (currentHighlighted)
            {
                run.Background = ParagraphSearcher.HighlightBrush;
            }

            Inline inline = currentBold ? (Inline)new Bold(run) : run;
            currentParagraph.Inlines.Add(inline);
            sequence.Clear();
        }

        /// <summary>
        /// This is an auxiliar method in BuildParagraph to move the current bold or highlighted spans
        /// according to the <paramref name="caracterPosition"/>
        /// The current bold and highlighted span should be ending ahead of the current position.
        /// Moves <paramref name="currentSpanIndex"/> and <paramref name="currentSpan"/> to the
        /// proper span in <paramref name="allSpans"/> according to the <paramref name="caracterPosition"/>
        /// This is an auxiliar method in BuildParagraph.
        /// </summary>
        /// <param name="currentSpanIndex">Current index within <paramref name="allSpans"/>.</param>
        /// <param name="currentSpan">Current span within <paramref name="allSpans"/>.</param>
        /// <param name="caracterPosition">Character position. This comes from a position within this.textBuilder.</param>
        /// <param name="allSpans">The collection of spans. This is either this.boldSpans or this.highlightedSpans.</param>
        private static void MoveSpanToPosition(ref int currentSpanIndex, ref TextSpan? currentSpan, int caracterPosition, List<TextSpan> allSpans)
        {
            if (currentSpan == null || caracterPosition <= currentSpan.Value.End)
            {
                return;
            }

            for (int newBoldIndex = currentSpanIndex + 1; newBoldIndex < allSpans.Count; newBoldIndex++)
            {
                TextSpan newBoldSpan = allSpans[newBoldIndex];
                if (caracterPosition <= newBoldSpan.End)
                {
                    currentSpanIndex = newBoldIndex;
                    currentSpan = newBoldSpan;
                    return;
                }
            }

            // there is no span ending ahead of current position, so
            // we set the current span to null to prevent unnecessary comparisons against the currentSpan
            currentSpan = null;
        }

        /// <summary>
        /// Adds one individual text highlight
        /// This is called after all calls to AddText have been made.
        /// </summary>
        /// <param name="start">Highlight start.</param>
        /// <param name="length">Highlight length.</param>
        private void AddHighlight(int start, int length)
        {
            ArgumentOutOfRangeException.ThrowIfNegative(start);
            ArgumentOutOfRangeException.ThrowIfGreaterThan(start + length, this.textBuilder.Length, nameof(length));

            this.highlightedSpans.Add(new TextSpan(start, length));
        }

        /// <summary>
        /// Called internally to notify when a property changed.
        /// </summary>
        /// <param name="propertyName">Property name.</param>
        private void OnNotifyPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        /// A text span used to mark bold and highlighted segments.
        /// </summary>
        internal struct TextSpan
        {
            /// <summary>
            /// Index of the first character in the span.
            /// </summary>
            private readonly int start;

            /// <summary>
            /// Index of the last character in the span.
            /// </summary>
            private readonly int end;

            /// <summary>
            /// Initializes a new instance of the TextSpan struct.
            /// </summary>
            /// <param name="start">Index of the first character in the span.</param>
            /// <param name="length">Index of the last character in the span.</param>
            internal TextSpan(int start, int length)
            {
                ArgumentOutOfRangeException.ThrowIfNegative(start);
                ArgumentOutOfRangeException.ThrowIfLessThan(length, 1);

                this.start = start;
                this.end = start + length - 1;
            }

            /// <summary>
            /// Gets the index of the first character in the span.
            /// </summary>
            internal int Start
            {
                get { return this.start; }
            }

            /// <summary>
            /// Gets the index of the first character in the span.
            /// </summary>
            internal int End
            {
                get
                {
                    return this.end;
                }
            }

            /// <summary>
            /// Returns true if the <paramref name="position"/> is between start and end (inclusive).
            /// </summary>
            /// <param name="position">Position to verify if is in the span.</param>
            /// <returns>True if the <paramref name="position"/> is between start and end (inclusive).</returns>
            internal bool Contains(int position)
            {
                return (position >= this.start) && (position <= this.end);
            }
        }
    }
}