// 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 { /// /// ViewModel for the . /// /// public class DictionaryController : System.ComponentModel.INotifyPropertyChanged { private Settings _settings = new Settings(); private HtmlToFlowDocument.Converter _converter = new HtmlToFlowDocument.Converter(); /// /// The currently loaded dictionaries. /// private List _dictionaries = new List(); 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 /// /// Occurs when a property value changes. /// public event PropertyChangedEventHandler PropertyChanged; private string[] _keys; private ObservableCollection _keysColl; /// /// Gets or sets the keys. This list contains the collected keys of all dictionaries currently loaded. Used for data binding to the key list. /// /// /// The keys. /// public ObservableCollection 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; /// /// Gets or sets the selected search text (used for binding to the search text TextBox). /// /// /// The selected search text. /// public string SelectedKeyInKeyList { get { return _selectedKeyInKeyList; } set { if (!(_selectedKeyInKeyList == value)) { _selectedKeyInKeyList = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedKeyInKeyList))); } } } private List _bestMatchesList; /// /// 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. /// /// /// The best matches list. /// public List BestMatchesList { get { return _bestMatchesList; } set { if (!object.ReferenceEquals(_bestMatchesList, value)) { _bestMatchesList = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BestMatchesList))); } } } private FlowDocument _flowDocument; /// /// Gets or sets the flow document (used for data binding to the FlowDocumentViewer). /// /// /// The flow document. /// public FlowDocument FlowDocument { get { return _flowDocument; } set { if (!object.ReferenceEquals(_flowDocument, value)) { _flowDocument = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FlowDocument))); } } } private string _searchText; /// /// Gets or sets the selected search text (used for binding to the search text TextBox). /// /// /// The selected search text. /// 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 /// /// Gets the currently loaded dictionaries. /// /// /// The currently loaded dictionaries. /// public IList 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); } } /// /// Loads a Slob dictionary. /// /// Name of the dictionary file. The dictionary must be in SLOB format. /// If set to true, 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. 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(); } } } /// /// Collects the keys of all loaded dictionaries and sorts them alphabetically. The list of keys is then published in . /// public void CollectAndSortKeys() { var hashSet = new HashSet(); 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(_keys); } /// /// Given the search key , 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 . /// /// The search text. 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(_bestMatches.BestMatches.Select(x => x.Phrase).Take(Math.Min(100, _keys.Length))); } }, token ); } public int SearchListLock { get; private set; } = 0; /// /// Given the key , 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. /// /// The untrimmed key. 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; } /// /// Given the key , this function enumerates through all currently loaded dictionaries, /// collects the content found for this key, and finally shows the collected content in a FlowDocument. /// /// The original search text. 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); } /// /// Converts plain text to a . /// /// The key. It is neccessary here because text files do not neccessarily contain the key, so that the key is used as title here. /// The content in plain text format. /// A that represents the plain text content. 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; } /// /// Converts TEI XML content to a . /// /// The content to convert. It must be in TEI XML format (see README.md of ). /// A that represents the TEI XML content. 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; } /// /// Converts HTML content returned by a dictionary to a . /// /// The dictionary. It is neccessary to retrieve CSS files referenced by the HTML content. /// The HTML to convert. /// A that represents the HTML content. public Section ConvertHtmlContentToSection(IWordDictionary dictionary, string htmlContent) { Func 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; } /// /// Converts HTML content returned by a dictionary to a . /// /// The dictionary. It is neccessary to retrieve CSS files referenced by the HTML content. /// The HTML to convert. /// A that represents the HTML content. public Section ConvertXHtmlContentToSection(IWordDictionary dictionary, string htmlContent) { Func 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; } """; /// /// Tries to find the key in the dictionary. /// /// The text to search. If this original text was not found, on return, the parameter contains the key for which the content is returned. /// The dictionary. /// 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 contains the search text that was found. 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; } } }