| using System; |
| using System.Text; |
| using System.Windows; |
| using System.Windows.Controls; |
| using System.Windows.Data; |
| using System.Windows.Documents; |
| using System.Windows.Input; |
| using System.Windows.Media; |
| using System.Windows.Media.Imaging; |
| using System.Windows.Navigation; |
| using System.Windows.Shapes; |
| using Microsoft.Win32; |
| using System.Collections.Generic; |
| using System.Linq; |
| using CefSharp; |
| using CefSharp.Wpf; |
| using System.Text.Json; |
| using System.Runtime.InteropServices; |
| using System.Windows.Interop; |
|
|
| namespace Echodict |
| { |
| |
| |
| |
| public partial class EchodictWindow : Window |
| { |
| [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] |
| private static extern uint RegisterWindowMessage(string lpString); |
| private const string UniqueMessageName = "WM_SHOWME_EchoDict_WpfEditor_2025"; |
|
|
| private static EchodictWindow? _instance; |
| public static EchodictWindow Instance |
| { |
| get |
| { |
| if (_instance == null) |
| { |
| _instance = new EchodictWindow(); |
| } |
| return _instance; |
| } |
| } |
|
|
| private List<Dictionary> _dicts = new List<Dictionary>(); |
| private List<string> _sourcePaths = new List<string>(); |
| private List<DictGroup> _groups = new List<DictGroup>(); |
| private string _currentSelectionId = "ALL"; |
| private bool _isReady = false; |
| private string? _startupWord; |
| private bool _forceClose = false; |
| public WindowState LastWindowState { get; private set; } = WindowState.Normal; |
|
|
|
|
| public EchodictWindow() |
| { |
| InitializeComponent(); |
|
|
| |
| |
| |
|
|
| this.StateChanged += (s, e) => |
| { |
| if (this.WindowState != WindowState.Minimized) |
| { |
| LastWindowState = this.WindowState; |
| } |
| }; |
|
|
| Application.Current.Exit += (s, e) => |
| { |
| _forceClose = true; |
| this.Close(); |
| }; |
|
|
| LoadConfig(); |
|
|
| |
| if (_sourcePaths.Count > 0) |
| { |
| Loaded += (s, e) => ScanAndLoadDictionaries(); |
| } |
| else |
| { |
| |
| RefreshDictSelector(); |
| } |
|
|
| Browser.RequestHandler = new DictRequestHandler(_dicts, (query) => |
| { |
| Dispatcher.Invoke(() => |
| { |
| SideSearchBox.Text = query; |
| Search(query, true); |
| }); |
| }); |
|
|
| Browser.MenuHandler = new DictMenuHandler(); |
|
|
| _isReady = true; |
| } |
|
|
| protected override void OnSourceInitialized(EventArgs e) |
| { |
| base.OnSourceInitialized(e); |
| HwndSource source = PresentationSource.FromVisual(this) as HwndSource; |
| source?.AddHook(WndProc); |
| } |
|
|
| private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) |
| { |
| uint wmShowMe = RegisterWindowMessage(UniqueMessageName); |
| if (msg == wmShowMe) |
| { |
| this.Show(); |
| if (this.WindowState == WindowState.Minimized) |
| { |
| this.WindowState = WindowState.Normal; |
| } |
| this.Activate(); |
| this.Topmost = true; |
| |
| handled = true; |
| } |
| return IntPtr.Zero; |
| } |
|
|
| protected override void OnClosing(System.ComponentModel.CancelEventArgs e) |
| { |
| if (_forceClose) |
| { |
| base.OnClosing(e); |
| return; |
| } |
|
|
| e.Cancel = true; |
| this.Hide(); |
| } |
|
|
| public void ShowWord(string word) |
| { |
| if (!this.IsLoaded) |
| { |
| _startupWord = word; |
| } |
| else |
| { |
| SideSearchBox.Text = word; |
| Search(word, true); |
| } |
|
|
|
|
|
|
| if (this.WindowState != WindowState.Maximized) |
| { |
| |
| this.WindowState = WindowState.Normal; |
| } |
| this.Show(); |
| this.Activate(); |
| this.Topmost = true; |
| } |
|
|
| public void OpenUrl(string url) |
| { |
| if (this.WindowState == WindowState.Minimized) |
| { |
| this.WindowState = LastWindowState; |
| } |
| else if (this.WindowState != WindowState.Maximized) |
| { |
| |
| this.WindowState = WindowState.Normal; |
| } |
|
|
| this.Show(); |
| this.Activate(); |
| this.Topmost = true; |
|
|
| |
| bool reuse = false; |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| if (!reuse) |
| { |
| AddNewTab(url); |
| } |
| } |
|
|
| private void AddNewTab(string url) |
| { |
| var browser = new ChromiumWebBrowser(); |
| browser.Address = url; |
|
|
| var tabItem = new TabItem(); |
|
|
| |
| var headerPanel = new DockPanel |
| { |
| Background = Brushes.Transparent |
| }; |
|
|
| var textBlock = new TextBlock |
| { |
| Text = "Loading...", |
| VerticalAlignment = VerticalAlignment.Center |
| }; |
|
|
| var closeButton = new Button |
| { |
| Content = "×", |
| Width = 16, |
| Height = 16, |
| FontSize = 12, |
| Padding = new Thickness(0, -2, 0, 0), |
| BorderThickness = new Thickness(0), |
| Background = Brushes.Transparent, |
| Foreground = Brushes.Red, |
| VerticalAlignment = VerticalAlignment.Center, |
| Margin = new Thickness(5, 0, 0, 0), |
| Visibility = Visibility.Hidden, |
| ToolTip = "Close Tab", |
| FontWeight = FontWeights.Bold |
| }; |
|
|
| |
| closeButton.Click += (s, e) => |
| { |
| try |
| { |
| if (tabItem.Content is ChromiumWebBrowser b) |
| { |
| b.Dispose(); |
| } |
| MainTabControl.Items.Remove(tabItem); |
| e.Handled = true; |
| } |
| catch (Exception ex) |
| { |
| System.Diagnostics.Debug.WriteLine($"Error closing tab: {ex.Message}"); |
| } |
| }; |
|
|
| |
| headerPanel.MouseEnter += (s, e) => closeButton.Visibility = Visibility.Visible; |
| headerPanel.MouseLeave += (s, e) => closeButton.Visibility = Visibility.Hidden; |
|
|
| DockPanel.SetDock(closeButton, Dock.Right); |
| headerPanel.Children.Add(closeButton); |
| headerPanel.Children.Add(textBlock); |
|
|
| tabItem.Header = headerPanel; |
| tabItem.Content = browser; |
|
|
| browser.TitleChanged += (s, e) => |
| { |
| Dispatcher.Invoke(() => textBlock.Text = e.NewValue?.ToString() ?? "New Tab"); |
| }; |
|
|
| MainTabControl.Items.Add(tabItem); |
| MainTabControl.SelectedItem = tabItem; |
| } |
|
|
|
|
|
|
| private void LoadConfig() |
| { |
| try |
| { |
| string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "echodictconfig.json"); |
| if (System.IO.File.Exists(path)) |
| { |
| string json = System.IO.File.ReadAllText(path); |
| var config = JsonSerializer.Deserialize<EchodictConfig>(json); |
| if (config != null) |
| { |
| _sourcePaths = config.SourcePaths ?? new List<string>(); |
| _groups = config.Groups ?? new List<DictGroup>(); |
| _currentSelectionId = config.LastSelectedDictId ?? "ALL"; |
|
|
| if (config.History != null) |
| { |
| foreach (var item in config.History) |
| { |
| HistoryList.Items.Add(item); |
| } |
| } |
| } |
| } |
| } |
| catch (Exception ex) |
| { |
| System.Diagnostics.Debug.WriteLine($"Error loading config: {ex.Message}"); |
| } |
| } |
|
|
| private void SaveConfig() |
| { |
| try |
| { |
| var config = new EchodictConfig |
| { |
| SourcePaths = _sourcePaths, |
| Groups = _groups, |
| LastSelectedDictId = _currentSelectionId, |
| History = HistoryList.Items.Cast<string>().ToList() |
| }; |
| var options = new JsonSerializerOptions |
| { |
| WriteIndented = true, |
| Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping |
| }; |
| string json = JsonSerializer.Serialize(config, options); |
| string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "echodictconfig.json"); |
| System.IO.File.WriteAllText(path, json, Encoding.UTF8); |
| } |
| catch (Exception ex) |
| { |
| System.Diagnostics.Debug.WriteLine($"Error saving config: {ex.Message}"); |
| } |
| } |
|
|
|
|
| private void BtnAddDict_Click(object sender, RoutedEventArgs e) |
| { |
| var dlg = new EditDictionaries(_sourcePaths, _groups, _dicts); |
| dlg.Owner = this; |
| if (dlg.ShowDialog() == true) |
| { |
| _sourcePaths = dlg.SourcePaths; |
| _groups = dlg.Groups; |
|
|
| |
| SaveConfig(); |
|
|
| if (dlg.NeedsRescan) |
| { |
| ScanAndLoadDictionaries(); |
| } |
| else |
| { |
| |
| RefreshDictSelector(); |
| } |
| } |
| } |
|
|
| private void BtnRescan_Click(object sender, RoutedEventArgs e) |
| { |
| bool force = (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control; |
| if (force) |
| { |
| if (MessageBox.Show("Force rebuild all indexes? This may take time.", "Rebuild Indexes", MessageBoxButton.YesNo) != MessageBoxResult.Yes) |
| { |
| return; |
| } |
| } |
| ScanAndLoadDictionaries(force); |
| } |
|
|
| private void ScanAndLoadDictionaries(bool forceRebuild = false) |
| { |
| |
| foreach (var dict in _dicts) |
| { |
| dict.Dispose(); |
| } |
| _dicts.Clear(); |
| DictsList.Items.Clear(); |
|
|
| string cacheDir = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Cache"); |
| if (!System.IO.Directory.Exists(cacheDir)) |
| { |
| System.IO.Directory.CreateDirectory(cacheDir); |
| } |
|
|
| foreach (var path in _sourcePaths) |
| { |
| if (System.IO.Directory.Exists(path)) |
| { |
| try |
| { |
| var files = System.IO.Directory.GetFiles(path, "*.mdx", System.IO.SearchOption.AllDirectories); |
| foreach (var file in files) |
| { |
| try |
| { |
| LoadDictionary(file, cacheDir, forceRebuild); |
| } |
| catch (Exception ex) |
| { |
| System.Diagnostics.Debug.WriteLine($"Failed to load {file}: {ex.Message}"); |
| } |
| } |
| } |
| catch (Exception ex) |
| { |
| System.Diagnostics.Debug.WriteLine($"Failed to scan {path}: {ex.Message}"); |
| } |
| } |
| } |
|
|
| RefreshDictSelector(); |
| SaveConfig(); |
|
|
| |
| if (!string.IsNullOrEmpty(_startupWord)) |
| { |
| |
| SideSearchBox.Text = _startupWord; |
| Search(_startupWord, true); |
| _startupWord = null; |
| } |
|
|
| |
| } |
|
|
| private void RefreshDictSelector() |
| { |
| |
| |
| DictSelector.Items.Clear(); |
|
|
| var allItem = new ComboBoxItem { Content = "All Dictionaries", Tag = "ALL" }; |
| DictSelector.Items.Add(allItem); |
|
|
| |
| foreach (var group in _groups) |
| { |
| DictSelector.Items.Add(new ComboBoxItem { Content = $"[Group] {group.Name}", Tag = group }); |
| } |
|
|
| |
| foreach (var dict in _dicts) |
| { |
| DictSelector.Items.Add(new ComboBoxItem { Content = dict.Name, Tag = dict }); |
| } |
|
|
| |
| bool matched = false; |
| foreach (ComboBoxItem item in DictSelector.Items) |
| { |
| if (GetItemId(item) == _currentSelectionId) |
| { |
| DictSelector.SelectedItem = item; |
| matched = true; |
| break; |
| } |
| } |
|
|
| if (!matched) |
| { |
| DictSelector.SelectedIndex = 0; |
| } |
| } |
|
|
| private string GetItemId(ComboBoxItem item) |
| { |
| if (item.Tag is string s && s == "ALL") return "ALL"; |
| if (item.Tag is DictGroup g) return "GROUP:" + g.Name; |
| if (item.Tag is Dictionary d) return "DICT:" + d.Id; |
| return ""; |
| } |
|
|
| private void BtnClearHistory_Click(object sender, RoutedEventArgs e) |
| { |
| if (MessageBox.Show("Are you sure you want to clear the history?", "Clear History", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) |
| { |
| HistoryList.Items.Clear(); |
| SaveConfig(); |
| } |
| } |
|
|
| private void BtnBack_Click(object sender, RoutedEventArgs e) |
| { |
| if (HistoryList.Items.Count == 0) return; |
|
|
| int newIndex = HistoryList.SelectedIndex + 1; |
|
|
| |
| |
| |
| if (HistoryList.SelectedIndex == -1) |
| { |
| newIndex = 1; |
| } |
|
|
| if (newIndex < HistoryList.Items.Count) |
| { |
| HistoryList.SelectedIndex = newIndex; |
| HistoryList.ScrollIntoView(HistoryList.SelectedItem); |
| } |
| } |
|
|
| private void BtnForward_Click(object sender, RoutedEventArgs e) |
| { |
| if (HistoryList.Items.Count == 0) return; |
|
|
| if (HistoryList.SelectedIndex > 0) |
| { |
| HistoryList.SelectedIndex = HistoryList.SelectedIndex - 1; |
| HistoryList.ScrollIntoView(HistoryList.SelectedItem); |
| } |
| |
| } |
|
|
| private void BtnQuit_Click(object sender, RoutedEventArgs e) |
| { |
| Close(); |
| } |
|
|
| private void LoadDictionary(string path, string cacheDir, bool forceRebuild) |
| { |
| Dictionary dict = new Dictionary(path, cacheDir, forceRebuild); |
| _dicts.Add(dict); |
| } |
|
|
| private void TxtSearch_KeyUp(object sender, KeyEventArgs e) |
| { |
| if (e.Key == Key.Enter) |
| { |
| Search(SideSearchBox.Text.Trim(), true); |
| } |
| } |
|
|
| public void Search(string query, bool updateWordList, bool updateHistory = true) |
| { |
| if (string.IsNullOrEmpty(query)) return; |
|
|
| if (updateWordList) |
| { |
| WordList.Items.Clear(); |
| } |
|
|
| |
| DictsList.Items.Clear(); |
|
|
| StringBuilder sb = new StringBuilder(); |
| sb.Append("<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><style>img { max-width: 100%; }</style></head><body>"); |
|
|
| bool found = false; |
|
|
| |
| List<Dictionary> targetDicts = new List<Dictionary>(); |
|
|
| if (DictSelector.SelectedItem is ComboBoxItem selectedItem) |
| { |
| if (selectedItem.Tag is string s && s == "ALL") |
| { |
| targetDicts = _dicts; |
| } |
| else if (selectedItem.Tag is DictGroup group) |
| { |
| targetDicts = _dicts.Where(d => group.DictionaryPaths.Contains(d.Mdx.Filename)).ToList(); |
| } |
| else if (selectedItem.Tag is Dictionary dict) |
| { |
| targetDicts = new List<Dictionary> { dict }; |
| } |
| } |
| else |
| { |
| |
| targetDicts = _dicts; |
| } |
|
|
| foreach (var dict in targetDicts) |
| { |
| if (dict.Mdx.Index.TryGetValue(query, out List<int> entryIndices)) |
| { |
| string anchorName = $"dict_{dict.Id}"; |
| StringBuilder dictContent = new StringBuilder(); |
| bool hasContent = false; |
| bool hasRedirects = false; |
|
|
| foreach (int index in entryIndices) |
| { |
| var entry = dict.Mdx.Entries[index]; |
| string? def = dict.Mdx.GetDefinition(index, false); |
|
|
| if (string.IsNullOrEmpty(def)) continue; |
|
|
| bool isRedirect = def.StartsWith("@@@LINK="); |
|
|
| |
| if (isRedirect) |
| { |
| if (updateWordList) |
| { |
| var links = def.Split(new[] { "@@@LINK=" }, StringSplitOptions.RemoveEmptyEntries); |
| foreach (var link in links) |
| { |
| string target = link.Trim(); |
| int nullIndex = target.IndexOf('\0'); |
| if (nullIndex != -1) target = target.Substring(0, nullIndex); |
| target = target.Trim(); |
| if (!string.IsNullOrEmpty(target) && !WordList.Items.Contains(target)) |
| { |
| WordList.Items.Add(target); |
| } |
| } |
| } |
| } |
|
|
| |
| if (entry.Headword.Equals(query, StringComparison.Ordinal)) |
| { |
| if (isRedirect) |
| { |
| |
| |
| string? resolvedDef = dict.Mdx.GetDefinition(index, true); |
| if (!string.IsNullOrEmpty(resolvedDef) && !resolvedDef.StartsWith("@@@LINK=")) |
| { |
| |
| |
| string pattern = @"(?i)(src|href)=[""'](?!http|https|data:|#|entry:)([^""']+)[""']"; |
| string replacement = $"$1=\"http://custom-rendering/{dict.Id}/$2\""; |
| resolvedDef = System.Text.RegularExpressions.Regex.Replace(resolvedDef, pattern, replacement); |
|
|
| dictContent.Append(resolvedDef); |
| dictContent.Append("<br/>"); |
| hasContent = true; |
| } |
| else |
| { |
| hasRedirects = true; |
| } |
| } |
| else |
| { |
| |
| |
| string pattern = @"(?i)(src|href)=[""'](?!http|https|data:|#|entry:)([^""']+)[""']"; |
| string replacement = $"$1=\"http://custom-rendering/{dict.Id}/$2\""; |
| def = System.Text.RegularExpressions.Regex.Replace(def, pattern, replacement); |
|
|
| dictContent.Append(def); |
| dictContent.Append("<br/>"); |
| hasContent = true; |
| } |
| } |
| } |
|
|
| if (hasContent) |
| { |
| found = true; |
|
|
| |
| ListBoxItem resultItem = new ListBoxItem(); |
| resultItem.Content = dict.Name; |
| resultItem.Tag = anchorName; |
| resultItem.MouseDoubleClick += ResultItem_MouseDoubleClick; |
| DictsList.Items.Add(resultItem); |
|
|
| sb.Append($"<a name=\"{anchorName}\"></a>"); |
| sb.Append($"<h3>{query} <small>({dict.Name})</small></h3>"); |
| sb.Append("<hr/>"); |
| sb.Append(dictContent.ToString()); |
| sb.Append("<br/><br/>"); |
| } |
| else if (hasRedirects) |
| { |
| |
| found = true; |
|
|
| ListBoxItem resultItem = new ListBoxItem(); |
| resultItem.Content = dict.Name; |
| resultItem.Tag = anchorName; |
| resultItem.MouseDoubleClick += ResultItem_MouseDoubleClick; |
| DictsList.Items.Add(resultItem); |
|
|
| sb.Append($"<a name=\"{anchorName}\"></a>"); |
| sb.Append($"<h3>{query} <small>({dict.Name})</small></h3>"); |
| sb.Append("<p><i>Multiple candidates found. Please select from the list.</i></p>"); |
| sb.Append("<hr/>"); |
| } |
| } |
| } |
|
|
| if (found && updateHistory) |
| { |
| AddToHistory(query); |
| } |
|
|
| if (!found) |
| { |
| sb.Append($"<h3>No results found for '{query}'</h3>"); |
| } |
|
|
| sb.Append("</body></html>"); |
|
|
| |
| |
| MainTabControl.SelectedIndex = 0; |
|
|
| if (Browser.RequestHandler is DictRequestHandler handler) |
| { |
| handler.SetSearchHtml(sb.ToString()); |
| Browser.Load("http://custom-rendering/result.html"); |
| } |
| else |
| { |
| |
| Browser.LoadHtml(sb.ToString(), "http://custom-rendering/"); |
| } |
| } |
|
|
| private void DictSelector_SelectionChanged(object sender, SelectionChangedEventArgs e) |
| { |
| if (!_isReady) return; |
|
|
| if (DictSelector.SelectedItem is ComboBoxItem item) |
| { |
| _currentSelectionId = GetItemId(item); |
| SaveConfig(); |
| } |
|
|
| |
| if (SideSearchBox == null) return; |
|
|
| |
| if (!string.IsNullOrEmpty(SideSearchBox.Text)) |
| { |
| Search(SideSearchBox.Text, false); |
| } |
| } |
|
|
| private void WordList_SelectionChanged(object sender, SelectionChangedEventArgs e) |
| { |
| if (WordList.SelectedItem != null) |
| { |
| Search(WordList.SelectedItem.ToString(), false); |
| } |
| } |
|
|
| private void ResultItem_MouseDoubleClick(object sender, MouseButtonEventArgs e) |
| { |
| if (sender is ListBoxItem item && item.Tag is string anchorName) |
| { |
| |
| string script = $@" |
| var element = document.getElementsByName('{anchorName}')[0]; |
| if (element) {{ |
| element.scrollIntoView({{ behavior: 'smooth', block: 'start' }}); |
| }} |
| "; |
| Browser.ExecuteScriptAsync(script); |
| } |
| } |
|
|
| private void AddToHistory(string query) |
| { |
| if (HistoryList.Items.Contains(query)) |
| { |
| HistoryList.Items.Remove(query); |
| } |
| HistoryList.Items.Insert(0, query); |
|
|
| |
| while (HistoryList.Items.Count > 100) |
| { |
| HistoryList.Items.RemoveAt(HistoryList.Items.Count - 1); |
| } |
|
|
| SaveConfig(); |
| } |
|
|
| private void HistoryList_SelectionChanged(object sender, SelectionChangedEventArgs e) |
| { |
| if (HistoryList.SelectedItem != null) |
| { |
| string? query = HistoryList.SelectedItem.ToString(); |
| if (!string.IsNullOrEmpty(query)) |
| { |
| SideSearchBox.Text = query; |
| |
| Search(query, true, false); |
| } |
| } |
| } |
| } |
| } |
|
|