File size: 20,186 Bytes
fab29d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
// Copyright (c) Dr. Dirk Lellinger. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using HtmlToFlowDocument.Dom;
using SlobViewer.Common;
using SlobViewer.Slob;

namespace SlobViewer.Gui
{
  /// <summary>
  /// ViewModel for the <see cref="DictionaryControl"/>.
  /// </summary>
  /// <seealso cref="System.ComponentModel.INotifyPropertyChanged" />
  public class DictionaryController : System.ComponentModel.INotifyPropertyChanged
  {
    private Settings _settings = new Settings();
    private HtmlToFlowDocument.Converter _converter = new HtmlToFlowDocument.Converter();

    /// <summary>
    /// The currently loaded dictionaries.
    /// </summary>
    private List<IWordDictionary> _dictionaries = new List<IWordDictionary>();
    private SortKey[] _sortKeys;
    private CompareInfo _compareInfo;
    private Collections.Text.LongestCommonSubstringsOfStringAndStringArray _bestMatches = new Collections.Text.LongestCommonSubstringsOfStringAndStringArray().Preallocate(255, 255);
    private CancellationTokenSource _bestMatchesCancellationTokenSource = new CancellationTokenSource();
    private static readonly char[] _wordTrimChars = new char[] { ' ', '\t', '\r', '\n', ',', '.', '!', '?', ';', ':', '-', '+', '\"', '\'', '(', ')', '[', ']', '{', '}', '<', '>', '|', '=' };


    #region Bindable Properties

    /// <summary>
    /// Occurs when a property value changes.
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

    private string[] _keys;
    private ObservableCollection<string> _keysColl;

    /// <summary>
    /// Gets or sets the keys. This list contains the collected keys of all dictionaries currently loaded. Used for data binding to the key list.
    /// </summary>
    /// <value>
    /// The keys.
    /// </value>
    public ObservableCollection<string> KeyList
    {
      get
      {
        return _keysColl;
      }
      set
      {
        if (!object.ReferenceEquals(_keys, value))
        {
          _keysColl = value;
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(KeyList)));
        }
      }
    }

    internal void Action_ShowSecondaryWord(string text)
    {
      if (!string.IsNullOrEmpty(text))
      {
        ShowContentForUntrimmedKey(text);
      }
    }

    private string _selectedKeyInKeyList;

    /// <summary>
    /// Gets or sets the selected search text (used for binding to the search text TextBox).
    /// </summary>
    /// <value>
    /// The selected search text.
    /// </value>
    public string SelectedKeyInKeyList
    {
      get
      {
        return _selectedKeyInKeyList;
      }
      set
      {
        if (!(_selectedKeyInKeyList == value))
        {
          _selectedKeyInKeyList = value;
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedKeyInKeyList)));
        }
      }
    }

    private List<string> _bestMatchesList;

    /// <summary>
    /// Gets or sets the list of best matches (key words that are most similar to the original key). Used for data binding to the best matches list.
    /// </summary>
    /// <value>
    /// The best matches list.
    /// </value>
    public List<string> BestMatchesList
    {
      get { return _bestMatchesList; }
      set
      {
        if (!object.ReferenceEquals(_bestMatchesList, value))
        {
          _bestMatchesList = value;
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BestMatchesList)));
        }
      }
    }

    private FlowDocument _flowDocument;

    /// <summary>
    /// Gets or sets the flow document (used for data binding to the FlowDocumentViewer).
    /// </summary>
    /// <value>
    /// The flow document.
    /// </value>
    public FlowDocument FlowDocument
    {
      get
      {
        return _flowDocument;
      }
      set
      {
        if (!object.ReferenceEquals(_flowDocument, value))
        {
          _flowDocument = value;
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FlowDocument)));
        }
      }
    }

    private string _searchText;

    /// <summary>
    /// Gets or sets the selected search text (used for binding to the search text TextBox).
    /// </summary>
    /// <value>
    /// The selected search text.
    /// </value>
    public string SearchText
    {
      get
      {
        return _searchText;
      }
      set
      {
        if (!(_searchText == value))
        {
          _searchText = value;
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SearchText)));
          ShowContentForKey(_searchText);
          UpdateBestMatches(_searchText);
        }
      }
    }

    private bool _isInDarkMode;

    public bool IsInDarkMode
    {
      get
      {
        return _isInDarkMode;
      }
      set
      {
        if (!(_isInDarkMode == value))
        {
          _isInDarkMode = value;
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsInDarkMode)));
        }
      }
    }

    #endregion

    /// <summary>
    /// Gets the currently loaded dictionaries.
    /// </summary>
    /// <value>
    /// The currently loaded dictionaries.
    /// </value>
    public IList<IWordDictionary> Dictionaries { get { return _dictionaries; } }


    public void LoadDictionariesUsingSettings(Settings settings)
    {
      if (settings.DictionaryFileNames.Count >= 1)
      {
        for (int i = settings.DictionaryFileNames.Count - 1; i >= 0; --i)
          LoadDictionary(settings.DictionaryFileNames[i], i == 0);
      }
    }



    /// <summary>
    /// Loads a Slob dictionary.
    /// </summary>
    /// <param name="fileName">Name of the dictionary file. The dictionary must be in SLOB format.</param>
    /// <param name="collectKeys">If set to <c>true</c>, the keys of all dictionaries will be collected. When loading multiple dictionaries subsequently, you should set this parameter to true only for the last dictionary loaded.</param>
    public void LoadDictionary(string fileName, bool collectKeys = true)
    {
      var extension = System.IO.Path.GetExtension(fileName).ToLowerInvariant();

      IWordDictionary dictionary = null;

      switch (extension)
      {
        case ".ifo":
          {
            var starDict = new StarDict.StarDictionaryInMemory();
            starDict.Open(fileName);
            dictionary = starDict;
          }
          break;
        case ".slob":
          {
            var slobReader = new SlobReaderWriter(fileName);
            dictionary = slobReader.Read();
            dictionary.FileName = fileName;
          }
          break;
      }


      if (null != dictionary)
      {
        _dictionaries.Add(dictionary);

        if (collectKeys)
        {
          CollectAndSortKeys();
        }
      }
    }

    /// <summary>
    /// Collects the keys of all loaded dictionaries and sorts them alphabetically. The list of keys is then published in <see cref="KeyList"/>.
    /// </summary>
    public void CollectAndSortKeys()
    {
      var hashSet = new HashSet<string>();

      foreach (var dict in _dictionaries)
      {
        hashSet.UnionWith(dict.GetKeys());
      }

      _keys = hashSet.ToArray();

      _compareInfo = new CultureInfo("en-US", false).CompareInfo;

      _sortKeys = _keys.Select(x => _compareInfo.GetSortKey(x)).ToArray();
      Array.Sort(_sortKeys, _keys, new UnicodeStringSorter());

      KeyList = new ObservableCollection<string>(_keys);
    }

    /// <summary>
    /// Given the search key <paramref name="searchText"/>, the function looks out for other keys that have the most number of chars in common with the orignal key.
    /// The first 100 best matches are then put into the list <see cref="BestMatchesList"/>.
    /// </summary>
    /// <param name="searchText">The search text.</param>
    public void UpdateBestMatches(string searchText)
    {
      _bestMatchesCancellationTokenSource.Cancel();
      _bestMatchesCancellationTokenSource.Dispose();

      _bestMatchesCancellationTokenSource = new CancellationTokenSource();

      var token = _bestMatchesCancellationTokenSource.Token;

      System.Threading.Tasks.Task.Run(
          () =>
          {
            _bestMatches.Evaluate(searchText, _keys, token);

            if (!token.IsCancellationRequested)
            {
              BestMatchesList = new List<string>(_bestMatches.BestMatches.Select(x => x.Phrase).Take(Math.Min(100, _keys.Length)));
            }
          }, token
          );
    }

    public int SearchListLock { get; private set; } = 0;

    /// <summary>
    /// Given the key <paramref name="untrimmedSearchText"/>, this function first of all trims the key a the start and end from unwanted characters. Then it enumerates through all currently loaded dictionaries, 
    /// collects the content found for this key, and finally shows the collected content in a FlowDocument.
    /// </summary>
    /// <param name="untrimmedSearchText">The untrimmed key.</param>
    public void ShowContentForUntrimmedKey(string untrimmedSearchText)
    {
      SearchText = TrimKeyString(untrimmedSearchText);
    }

    private string TrimKeyString(string untrimmedSearchText)
    {
      var idxStart = 0;
      var idxEnd = untrimmedSearchText.Length - 1;

      for (; idxEnd >= 0; --idxEnd)
        if (char.IsLetterOrDigit(untrimmedSearchText[idxEnd]))
          break;

      for (; idxStart <= idxEnd; ++idxStart)
        if (char.IsLetterOrDigit(untrimmedSearchText[idxStart]))
          break;

      return idxStart <= idxEnd ? untrimmedSearchText.Substring(idxStart, idxEnd - idxStart + 1) : string.Empty;

    }

    /// <summary>
    /// Given the key <paramref name="originalSearchText"/>, this function enumerates through all currently loaded dictionaries, 
    /// collects the content found for this key, and finally shows the collected content in a FlowDocument.
    /// </summary>
    /// <param name="originalSearchText">The original search text.</param>
    public void ShowContentForKey(string originalSearchText)
    {
      if (string.IsNullOrEmpty(originalSearchText))
        return;

      (IWordDictionary Dictionary, string Content, string ContentId, string SearchText)? firstResult = null;

      var listDirect = new List<(IWordDictionary Dictionary, string Content, string ContentId, string SearchText)>();
      var listVerb = new List<(IWordDictionary Dictionary, string Content, string ContentId, string SearchText)>();

      var originalSearchTexts = char.IsUpper(originalSearchText[0]) ? new[] { originalSearchText, originalSearchText.ToLowerInvariant() } : new[] { originalSearchText };

      foreach (var originalSearchTextVariant in originalSearchTexts)
      {
        foreach (var dictionary in _dictionaries)
        {
          var searchText1 = originalSearchTextVariant;
          var (result1, result1Id, found1) = GetResult(ref searchText1, dictionary);

          if (null == firstResult)
            firstResult = (dictionary, result1, result1Id, searchText1);

          if (found1)
            listDirect.Add((dictionary, result1, result1Id, searchText1));

          var searchText2 = "to " + originalSearchText;
          var (result2, result2Id, found2) = GetResult(ref searchText2, dictionary);

          if (found2)
            listVerb.Add((dictionary, result2, result2Id, searchText2));
        }

        if (listDirect.Count != 0 || listVerb.Count != 0)
          break;

      }

      string searchText = listDirect.Count > 0 ? listDirect[0].SearchText : listVerb.Count > 0 ? listVerb[0].SearchText : firstResult?.SearchText;

      try
      {
        ++SearchListLock;
        SelectedKeyInKeyList = searchText;
      }
      finally
      {
        --SearchListLock;
      }


      if (listDirect.Count > 0 && listVerb.Count > 0)
        ShowContent(listDirect.Concat(listVerb).ToArray());
      else if (listDirect.Count > 0)
        ShowContent(listDirect.ToArray());
      else if (listVerb.Count > 0)
        ShowContent(listVerb.ToArray());
      else if (firstResult.HasValue)
        ShowContent(firstResult.Value);
    }


    /// <summary>
    /// Converts plain text to a <see cref="Section"/>.
    /// </summary>
    /// <param name="key">The key. It is neccessary here because text files do not neccessarily contain the key, so that the key is used as title here.</param>
    /// <param name="content">The content in plain text format.</param>
    /// <returns>A <see cref="Section"/> that represents the plain text content.</returns>
    public Section ConvertTextContentToSection(string key, string content)
    {
      var doc = new Section();

      var para = new Paragraph();
      var run = new Run(key);
      run.FontSize = 22;

      para.AppendChild(run);
      doc.AppendChild(para);

      para = new Paragraph();
      run = new Run(content);

      para.AppendChild(run);
      doc.AppendChild(para);

      return doc;
    }

    /// <summary>
    /// Converts TEI XML content to a <see cref="Section"/>.
    /// </summary>
    /// <param name="content">The content to convert. It must be in TEI XML format (see README.md of <see href="https://github.com/freedict/fd-dictionaries"/>).</param>
    /// <returns>A <see cref="Section"/> that represents the TEI XML content.</returns>
    public Section ConvertTeiContentToSection(string content)
    {
      var doc = new Section();


      using (var tr = System.Xml.XmlReader.Create(new StringReader(content)))
      {
        tr.MoveToContent();
        tr.ReadToDescendant("orth");
        var orth = tr.ReadElementContentAsString();

        if (null != orth)
        {
          var para = new Paragraph();
          para.AppendChild(new Run(orth) { FontSize = 23 });
          doc.AppendChild(para);
        }

        if (tr.Name == "pron")
        {
          var pron = tr.ReadElementContentAsString();
          var para = new Paragraph();
          para.AppendChild(new Run(pron) { FontSize = 18 });
          doc.AppendChild(para);
        }

        tr.ReadToFollowing("sense");
        tr.ReadStartElement("sense");

        var sensePara = new Paragraph();
        doc.AppendChild(sensePara);

        while (tr.Name == "cit")
        {
          string quote = null;

          tr.ReadStartElement("cit");
          if (tr.Name == "quote")
          {
            quote = tr.ReadElementContentAsString();
          }

          if (null != quote)
          {
            if (sensePara.Childs.Count != 0)
            {
              sensePara.AppendChild(new Run("; ") { FontSize = 15 });
            }
            sensePara.AppendChild(new Run(quote) { FontSize = 15 });
          }

          tr.ReadToFollowing("cit");
        }

      }


      return doc;
    }

    /// <summary>
    /// Converts HTML content returned by a dictionary to a <see cref="Section"/>.
    /// </summary>
    /// <param name="dictionary">The dictionary. It is neccessary to retrieve CSS files referenced by the HTML content.</param>
    /// <param name="htmlContent">The HTML to convert.</param>
    /// <returns>A <see cref="Section"/> that represents the HTML content.</returns>
    public Section ConvertHtmlContentToSection(IWordDictionary dictionary, string htmlContent)
    {
      Func<string, string, string> cssStyleSheetProvider = (cssFileName, refFileName) =>
      {
        if (dictionary.TryGetValue(cssFileName, out var entry))
        {
          return entry.Content;
        }
        else
        {
          return null;
        }
      };

      try
      {
        var section = (Section)_converter.Convert(htmlContent, false, cssStyleSheetProvider, null);
        return section;
      }
      catch (Exception ex)
      {

      }


      return null;

    }

    /// <summary>
    /// Converts HTML content returned by a dictionary to a <see cref="Section"/>.
    /// </summary>
    /// <param name="dictionary">The dictionary. It is neccessary to retrieve CSS files referenced by the HTML content.</param>
    /// <param name="htmlContent">The HTML to convert.</param>
    /// <returns>A <see cref="Section"/> that represents the HTML content.</returns>
    public Section ConvertXHtmlContentToSection(IWordDictionary dictionary, string htmlContent)
    {
      Func<string, string, string> cssStyleSheetProvider = (cssFileName, refFileName) =>
      {
        if (dictionary.TryGetValue(cssFileName, out var entry))
        {
          return entry.Content;
        }
        else
        {
          return DefaultStyleSheet;
        }
      };

      try
      {
        var section = (Section)_converter.ConvertXHtml(htmlContent, false, cssStyleSheetProvider, null);
        return section;
      }
      catch (Exception ex)
      {

      }


      return null;

    }

    const string DefaultStyleSheet =
    """
    body {
      font-family: Arial, sans-serif;
      font-size: 14px;
      line-height: 1.5;
    }
    
    h1 {
      font-size: 24px;
      margin-bottom: 2px;
    }
    
    h2 {
      font-size: 20px;
      margin-top: 10px;
      margin-bottom: 10px;
    }
    
    h3 {
      font-size: 17px;
      margin-bottom: 7px;
    }
    
    p {
      font-size: 14px;
    }
    """;


    /// <summary>
    /// Tries to find the key <paramref name="searchText"/> in the dictionary.
    /// </summary>
    /// <param name="searchText">The text to search. If this original text was not found, on return, the parameter contains the key for which the content is returned.</param>
    /// <param name="dictionary">The dictionary.</param>
    /// <returns>A tuple consisting of the content, the content identifer, and a boolean. The boolean is true if the original search text was found in the dictionary.
    /// If the original search text was not found, the boolean is false, and <paramref name="searchText"/>contains the search text that was found.</returns>
    private (string Content, string ContentId, bool foundOriginal) GetResult(ref string searchText, IWordDictionary dictionary)
    {
      var searchKey = _compareInfo.GetSortKey(searchText);
      var index = Array.BinarySearch(_sortKeys, searchKey, new UnicodeStringSorter());


      (string Content, string ContentId) result = (null, null);
      bool found = false;

      if (index >= 0)
      {
        result = dictionary[searchText];
        found = true;
      }
      else
      {
        index = ~index;

        if (index < _keys.Length)
        {
          searchText = _keys[index];
          result = dictionary[searchText];
        }
      }

      return (result.Content, result.ContentId, found);
    }

    public FlowDocument ShowContent(params (IWordDictionary Dictionary, string ContentText, string ContentID, string SearchKey)[] contents)
    {
      var doc = new FlowDocument();

      foreach (var (Dictionary, ContentText, ContentID, SearchKey) in contents)
      {
        if (string.IsNullOrEmpty(ContentID) || string.IsNullOrEmpty(ContentText) || string.IsNullOrEmpty(SearchKey))
          continue;

        if (ContentID.StartsWith("text/html"))
        {
          var section = ConvertHtmlContentToSection(Dictionary, ContentText);
          if (null != section)
            doc.AppendChild(section);

        }
        if (ContentID.StartsWith("text/xhtml"))
        {
          var section = ConvertXHtmlContentToSection(Dictionary, ContentText);
          if (null != section)
            doc.AppendChild(section);

        }
        else if (ContentID.StartsWith("text/plain"))
        {
          var section = ConvertTextContentToSection(SearchKey, ContentText);
          if (null != section)
            doc.AppendChild(section);

        }
        else if (ContentID.StartsWith("application/tei+xml"))
        {
          var section = ConvertTeiContentToSection(ContentText);
          doc.AppendChild(section);
        }
      }

      FlowDocument = doc;
      return doc;
    }




  }
}