imradv3 / src /WpfEditor /EchoDictWindow.xaml.cs
fasdfsa's picture
双开程序时仅拉起已有实例
1045b8e
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
{
/// <summary>
/// Interaction logic for EchodictWindow.xaml
/// </summary>
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();
// Default hidden and minimized
//this.Visibility = Visibility.Hidden;
//this.WindowState = WindowState.Minimized;
this.StateChanged += (s, e) =>
{
if (this.WindowState != WindowState.Minimized)
{
LastWindowState = this.WindowState;
}
};
Application.Current.Exit += (s, e) =>
{
_forceClose = true;
this.Close();
};
LoadConfig();
// Initial scan if we have paths but no dicts loaded yet
if (_sourcePaths.Count > 0)
{
Loaded += (s, e) => ScanAndLoadDictionaries();
}
else
{
// Initialize empty selector
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;
// Optional: Briefly flash or focus
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 = LastWindowState;
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 = LastWindowState;
this.WindowState = WindowState.Normal;
}
this.Show();
this.Activate();
this.Topmost = true;
// Check if we should use the existing browser or create a new tab
bool reuse = false;
//if (MainTabControl.Items.Count == 1)
//{
// var tab = MainTabControl.Items[0] as TabItem;
// if (tab != null && tab.Content is ChromiumWebBrowser browser)
// {
// // If address is empty or about:blank, reuse
// if (string.IsNullOrEmpty(browser.Address) || browser.Address == "about:blank")
// {
// browser.Address = url;
// reuse = true;
// }
// }
//}
if (!reuse)
{
AddNewTab(url);
}
}
private void AddNewTab(string url)
{
var browser = new ChromiumWebBrowser();
browser.Address = url;
var tabItem = new TabItem();
// Custom header with close button
var headerPanel = new DockPanel
{
Background = Brushes.Transparent // Ensure hit testing works on the whole panel
};
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, // Initially hidden
ToolTip = "Close Tab",
FontWeight = FontWeights.Bold
};
// Close tab logic
closeButton.Click += (s, e) =>
{
try
{
if (tabItem.Content is ChromiumWebBrowser b)
{
b.Dispose();
}
MainTabControl.Items.Remove(tabItem);
e.Handled = true; // Prevent tab selection
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error closing tab: {ex.Message}");
}
};
// Toggle visibility on hover
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;
// Save immediately
SaveConfig();
if (dlg.NeedsRescan)
{
ScanAndLoadDictionaries();
}
else
{
// If groups changed but no rescan needed, just refresh selector
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)
{
// Dispose existing dictionaries
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(); // Save to persist any state if needed, though mostly redundant here
// Handle startup word
if (!string.IsNullOrEmpty(_startupWord))
{
// Ensure UI is updated before searching (though Search method handles it)
SideSearchBox.Text = _startupWord;
Search(_startupWord, true);
_startupWord = null; // Consume it
}
// MessageBox.Show($"Loaded {_dicts.Count} dictionaries.", "Scan Complete");
}
private void RefreshDictSelector()
{
// Preserve selection if possible?
// For now reset to All
DictSelector.Items.Clear();
var allItem = new ComboBoxItem { Content = "All Dictionaries", Tag = "ALL" };
DictSelector.Items.Add(allItem);
// Groups
foreach (var group in _groups)
{
DictSelector.Items.Add(new ComboBoxItem { Content = $"[Group] {group.Name}", Tag = group });
}
// Individual Dictionaries
foreach (var dict in _dicts)
{
DictSelector.Items.Add(new ComboBoxItem { Content = dict.Name, Tag = dict });
}
// Restore selection
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 nothing is selected, we assume we are at the "latest" state (conceptually index 0 is current),
// so Back should go to index 1.
// Note: If we just added an item, it is at index 0 but typically not selected.
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);
}
// If SelectedIndex is -1 or 0, we are already at the latest, so do nothing.
}
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();
}
// Clear the dictionary list in the result panel
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;
// Determine which dictionaries to search
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
{
// Fallback
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); // Get raw definition (no redirect following)
if (string.IsNullOrEmpty(def)) continue;
bool isRedirect = def.StartsWith("@@@LINK=");
// Check for redirects to populate suggestion list
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);
}
}
}
}
// Check for Exact Match to display content
if (entry.Headword.Equals(query, StringComparison.Ordinal))
{
if (isRedirect)
{
// It's a redirect that exactly matches the query.
// Resolve and display the content
string? resolvedDef = dict.Mdx.GetDefinition(index, true);
if (!string.IsNullOrEmpty(resolvedDef) && !resolvedDef.StartsWith("@@@LINK="))
{
// Rewrite relative links to include dictionary ID for isolation
// Matches src="..." or href="..." where value doesn't start with http, https, data:, #, or entry:
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
{
// Rewrite relative links to include dictionary ID for isolation
// Matches src="..." or href="..." where value doesn't start with http, https, data:, #, or entry:
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;
// Add dictionary to the result panel list
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 only redirects for this query in this dictionary
found = true; // Still consider it found
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>");
// Use RequestHandler to serve the content
// Switch to the first tab (default browser)
MainTabControl.SelectedIndex = 0;
if (Browser.RequestHandler is DictRequestHandler handler)
{
handler.SetSearchHtml(sb.ToString());
Browser.Load("http://custom-rendering/result.html");
}
else
{
// Fallback (should not happen if initialized correctly)
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();
}
// Check if SideSearchBox is initialized (FIX for NRE)
if (SideSearchBox == null) return;
// Re-search if we have a query
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)
{
// Execute JavaScript to scroll to the anchor
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);
// Limit history size to prevent config bloat
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;
// Do not update history (reorder) when navigating history
Search(query, true, false);
}
}
}
}
}