using Echodict; using Microsoft.Win32; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OpenCvSharp; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Printing; using System.Runtime.ConstrainedExecution; using System.Runtime.Serialization.Formatters.Binary; using System.Security.Cryptography; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Shapes; using static System.Net.Mime.MediaTypeNames; using Path = System.IO.Path; using Point = System.Windows.Point; using Rect = System.Windows.Rect; using Size = System.Windows.Size; using Window = System.Windows.Window; namespace WpfEditor { public class TextEditorControl : Control { private Window _imageWindow = null; private bool _isCut = false; public EditorMode _mode = EditorMode.ImageOCR; // 默认模式为图片OCR public JObject _jsn_OpenImg; // for 校对 public string _md5_OpenImg; public Dictionary _dic_deleted_char = new Dictionary(); // 被删除的字符存它的 guid,保存的时侯标记它逻辑删除 public string _pthimg; // 当前打开的图片路径 // 添加MainWindow引用 public MainWindow _mainWindow; public static BitmapSource MatToBitmapSource(Mat mat) { // Detect pixel format (BGR24 for color, Gray8 for grayscale) var pixelFormat = mat.Channels() == 1 ? PixelFormats.Gray8 : PixelFormats.Bgr24; // Create BitmapSource with stride = mat.Step (handles 4-byte alignment) return BitmapSource.Create( mat.Width, mat.Height, 96, 96, // Default DPI pixelFormat, null, mat.Data, (int)mat.Step() * mat.Height, // Buffer size (int)mat.Step() // Stride (critical for alignment) ); } public void ShowDraggableImageControl(Mat image, Mat image_orig) { var mainWindow = Window.GetWindow(this) as MainWindow; // 将Mat转换为BitmapSource BitmapSource bitmapSource = MatToBitmapSource(image); // OpenCvSharp.Extensions.BitmapSourceConverter.ToBitmapSource(image); BitmapSource bitmapSource2 = MatToBitmapSource(image_orig); // 如果窗口已存在,则更新图片内容 if (_imageWindow != null) // && _imageWindow.IsLoaded { var brdr = _imageWindow.Content as Border; var stckpnl = brdr.Child as StackPanel; // as System.Windows.Controls.Image; var img_ctl = stckpnl.Children[1] as System.Windows.Controls.Image; //var img_ctl = _imageWindow.Content as System.Windows.Controls.Image; if (img_ctl != null) { img_ctl.Source = bitmapSource; // 根据新图片调整窗口大小 AdjustWindowSizeBasedOnImage(_imageWindow, bitmapSource.PixelWidth, bitmapSource.PixelHeight); mainWindow?.ShowImageInPanel(bitmapSource2); } return; } // 创建一个新窗口 _imageWindow = new Window { WindowStyle = WindowStyle.None, AllowsTransparency = true, Background = Brushes.Transparent, ShowInTaskbar = false, Topmost = true, Focusable = false, ResizeMode = ResizeMode.NoResize, SizeToContent = SizeToContent.WidthAndHeight, Owner = Window.GetWindow(this) // 设置主窗口为所有者,这样主窗口关闭时,图片窗口也会关闭 }; // 创建一个边框和图片控件 Border border = new Border { Background = new SolidColorBrush(Color.FromArgb(200, 30, 30, 30)), BorderBrush = Brushes.LightGray, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(3), Padding = new Thickness(5) }; // 创建一个StackPanel来包含图片和标题栏 StackPanel stackPanel = new StackPanel { HorizontalAlignment = HorizontalAlignment.Left }; // 添加一个简单的标题栏 Grid titleBar = new Grid { Height = 20, Margin = new Thickness(0, 0, 0, 5) }; titleBar.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); titleBar.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); TextBlock titleText = new TextBlock { Text = "图片预览", Foreground = Brushes.White, VerticalAlignment = VerticalAlignment.Center }; Button closeButton = new Button { Content = "X", Width = 20, Height = 20, Padding = new Thickness(0), Background = Brushes.Transparent, Foreground = Brushes.White, BorderThickness = new Thickness(0) }; closeButton.Click += (s, e) => _imageWindow.Close(); Grid.SetColumn(titleText, 0); Grid.SetColumn(closeButton, 1); titleBar.Children.Add(titleText); titleBar.Children.Add(closeButton); // 创建图片控件 System.Windows.Controls.Image imageControl = new System.Windows.Controls.Image { Source = bitmapSource, Stretch = Stretch.None, HorizontalAlignment = HorizontalAlignment.Left }; // 添加到StackPanel stackPanel.Children.Add(titleBar); stackPanel.Children.Add(imageControl); // 设置边框内容 border.Child = stackPanel; // 设置窗口内容 _imageWindow.Content = border; // 添加拖动功能 border.MouseLeftButtonDown += (s, e) => { if (e.ClickCount == 1) { _imageWindow.DragMove(); } }; // 添加右键菜单 ContextMenu contextMenu = new ContextMenu(); MenuItem closeMenuItem = new MenuItem { Header = "关闭" }; closeMenuItem.Click += (s, e) => _imageWindow.Close(); contextMenu.Items.Add(closeMenuItem); border.ContextMenu = contextMenu; // 显示窗口 _imageWindow.Show(); // 单行文本图 // 根据图片大小调整窗口尺寸 AdjustWindowSizeBasedOnImage(_imageWindow, bitmapSource.PixelWidth, bitmapSource.PixelHeight); // 设置初始位置(居中显示) if (mainWindow != null) { _imageWindow.Left = 0; // mainWindow.Left + (mainWindow.Width - _imageWindow.ActualWidth) / 2; _imageWindow.Top = mainWindow.Top + (mainWindow.Height - _imageWindow.ActualHeight) / 2; } if (mainWindow != null) { //if (true || mainWindow.ImageViewer.Source == null) //{ // mainWindow.ShowImageInPanel(bitmapSource2); // 全图 //} } } // 根据图片大小调整窗口尺寸的辅助方法 private void AdjustWindowSizeBasedOnImage(Window window, int imageWidth, int imageHeight) { // 获取当前屏幕的工作区大小 double screenWidth = SystemParameters.WorkArea.Width; double screenHeight = SystemParameters.WorkArea.Height; // 设置窗口最大尺寸(考虑到标题栏、边框等UI元素的额外空间) double maxWidth = screenWidth * 0.8; // 最大宽度为屏幕工作区的80% double maxHeight = screenHeight * 0.8; // 最大高度为屏幕工作区的80% // 计算额外UI元素的空间(标题栏、边框、内边距等) const double uiExtraWidth = 30; // 估计的水平方向额外空间 const double uiExtraHeight = 50; // 估计的垂直方向额外空间(包括标题栏) // 计算实际需要的窗口尺寸 double requiredWidth = imageWidth + uiExtraWidth; double requiredHeight = imageHeight + uiExtraHeight; // 如果图片尺寸超过最大限制,则应用缩放 if (requiredWidth > maxWidth || requiredHeight > maxHeight) { // 计算需要的缩放比例 double scaleX = maxWidth / requiredWidth; double scaleY = maxHeight / requiredHeight; double scale = Math.Min(scaleX, scaleY); // 取较小的缩放比例,确保完全适应 // 应用缩放 var image = ((window.Content as Border).Child as StackPanel).Children[1] as System.Windows.Controls.Image; if (image != null) { // 更改图片的缩放模式 image.Stretch = Stretch.Uniform; image.MaxWidth = maxWidth - uiExtraWidth; image.MaxHeight = maxHeight - uiExtraHeight; } } // 更新窗口布局 window.UpdateLayout(); } #region 依赖属性 public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(TextEditorControl), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnTextChanged)); public static readonly DependencyProperty IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(TextEditorControl), new PropertyMetadata(false)); public static readonly DependencyProperty TabSizeProperty = DependencyProperty.Register("TabSize", typeof(int), typeof(TextEditorControl), new PropertyMetadata(4)); public static readonly DependencyProperty LineNumbersVisibleProperty = DependencyProperty.Register("LineNumbersVisible", typeof(bool), typeof(TextEditorControl), new PropertyMetadata(true)); public static readonly DependencyProperty ShowWhitespacesProperty = DependencyProperty.Register("ShowWhitespaces", typeof(bool), typeof(TextEditorControl), new PropertyMetadata(true)); public static readonly DependencyProperty HighlightCurrentLineProperty = DependencyProperty.Register("HighlightCurrentLine", typeof(bool), typeof(TextEditorControl), new PropertyMetadata(true)); #endregion // 创建右键菜单的方法 private void CreateContextMenu() { ContextMenu = new ContextMenu(); // 复制菜单项 MenuItem copyMenuItem = new MenuItem { Header = "复制", Command = ApplicationCommands.Copy }; ContextMenu.Items.Add(copyMenuItem); // 剪切菜单项 MenuItem cutMenuItem = new MenuItem { Header = "剪切", Command = ApplicationCommands.Cut }; ContextMenu.Items.Add(cutMenuItem); // 粘贴菜单项 MenuItem pasteMenuItem = new MenuItem { Header = "粘贴", Command = ApplicationCommands.Paste }; ContextMenu.Items.Add(pasteMenuItem); // 分隔符 ContextMenu.Items.Add(new Separator()); // 全选菜单项 MenuItem selectAllMenuItem = new MenuItem { Header = "全选", Command = ApplicationCommands.SelectAll }; ContextMenu.Items.Add(selectAllMenuItem); // jisho查询菜单项 MenuItem jishoMenuItem = new MenuItem { Header = "jisho" }; jishoMenuItem.Click += OnjishoMenuItemClick; ContextMenu.Items.Add(jishoMenuItem); // naverja查询菜单项 MenuItem naverjaMenuItem = new MenuItem { Header = "naverja" }; naverjaMenuItem.Click += OnnaverjaMenuItemMenuItemClick; ContextMenu.Items.Add(naverjaMenuItem); // 查询菜单项 MenuItem QeryMenuItem = new MenuItem { Header = "查询" }; QeryMenuItem.Click += OnQueryMenuItemClick; ContextMenu.Items.Add(QeryMenuItem); // 翻译菜单项 MenuItem translateMenuItem = new MenuItem { Header = "翻译" }; translateMenuItem.Click += OnTranslateMenuItemClick; ContextMenu.Items.Add(translateMenuItem); // 设置菜单打开前的事件处理,用于控制菜单项的可用性 ContextMenu.Opened += OnContextMenuOpened; } // 右键菜单打开时的事件处理 private void OnContextMenuOpened(object sender, RoutedEventArgs e) { bool hasSelection = HasSelection(); bool hasClipboardText = Clipboard.ContainsText() || Clipboard.ContainsData("TextEditorCustomFormat"); // 根据当前状态设置菜单项的可用性 foreach (var item in ContextMenu.Items) { if (item is MenuItem menuItem) { if (menuItem.Command == ApplicationCommands.Copy || menuItem.Command == ApplicationCommands.Cut) { menuItem.IsEnabled = hasSelection; } else if (menuItem.Command == ApplicationCommands.Paste) { menuItem.IsEnabled = !IsReadOnly && hasClipboardText; } else if (menuItem.Command == ApplicationCommands.SelectAll) { menuItem.IsEnabled = _lines.Count > 0 && _lines.Any(line => line.Characters.Count > 0); } } } } // "翻译"菜单项点击事件处理 private async void OnTranslateMenuItemClick(object sender, RoutedEventArgs e) { if (HasSelection()) { string text = GetSelectedText(); string res = await DeepSeek.translate(text); if (res != "") { JObject jsn = Newtonsoft.Json.JsonConvert.DeserializeObject(res); string zh = jsn["choices"][0]["message"]["content"].Value(); var win = new TranslationResultWindow(zh); win.Owner = Window.GetWindow(this); win.WindowStartupLocation = WindowStartupLocation.CenterOwner; win.ShowDialog(); } } } private async void OnjishoMenuItemClick(object sender, RoutedEventArgs e) { if (HasSelection()) { string text = GetSelectedText(); var content = System.Web.HttpUtility.UrlEncode(text); String url = $"https://jisho.org/search/{content}"; var win = Echodict.EchodictWindow.Instance; win.WindowStartupLocation = WindowStartupLocation.CenterScreen; win.OpenUrl(url); } } private async void OnnaverjaMenuItemMenuItemClick(object sender, RoutedEventArgs e) { if (HasSelection()) { string text = GetSelectedText(); var content = System.Web.HttpUtility.UrlEncode(text); String url = $"https://ja.dict.naver.com/#/search?query={content}&range=all"; var win = Echodict.EchodictWindow.Instance; win.WindowStartupLocation = WindowStartupLocation.CenterScreen; win.OpenUrl(url); } } // "查询"菜单项点击事件处理 private async void OnQueryMenuItemClick(object sender, RoutedEventArgs e) { if (HasSelection()) { string text = GetSelectedText(); //var win = Echodict.EchodictWindow.Instance; //win.Owner = Window.GetWindow(this); //win.WindowStartupLocation = WindowStartupLocation.CenterOwner; //win.ShowWord(text); var win = Echodict.EchodictWindow.Instance; // Without an Owner, CenterOwner behaves like Manual. Use CenterScreen instead. win.WindowStartupLocation = WindowStartupLocation.CenterScreen; win.ShowWord(text); } } #region 属性 public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public bool IsReadOnly { get { return (bool)GetValue(IsReadOnlyProperty); } set { SetValue(IsReadOnlyProperty, value); } } public int TabSize { get { return (int)GetValue(TabSizeProperty); } set { SetValue(TabSizeProperty, value); } } public bool LineNumbersVisible { get { return (bool)GetValue(LineNumbersVisibleProperty); } set { SetValue(LineNumbersVisibleProperty, value); } } public bool ShowWhitespaces { get { return (bool)GetValue(ShowWhitespacesProperty); } set { SetValue(ShowWhitespacesProperty, value); } } public bool HighlightCurrentLine { get { return (bool)GetValue(HighlightCurrentLineProperty); } set { SetValue(HighlightCurrentLineProperty, value); } } #endregion #region 内部数据结构 public List _lines = new List(); public int _cursorLine = 0; public int _cursorColumn = 0; public int _selectionStartLine = -1; public int _selectionStartColumn = -1; public int _selectionEndLine = -1; public int _selectionEndColumn = -1; public List _undoBuffer = new List(); public int _undoIndex = -1; public bool _textChanged = false; public int _scrollOffset = 0; // 添加滚动偏移量变量 // 查找相关字段 private FindDialog _findDialog = null; private string _lastSearchText = ""; private bool _lastMatchCase = false; private bool _lastWholeWord = false; private int _lastFoundLine = -1; private int _lastFoundColumn = -1; private List<(int line, int column, int length)> _findResults = new List<(int, int, int)>(); private int _currentFindIndex = -1; #endregion #region 构造函数 static TextEditorControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(TextEditorControl), new FrameworkPropertyMetadata(typeof(TextEditorControl))); } public TextEditorControl() { this.Focusable = true; this.FocusVisualStyle = null; this.ClipToBounds = true; // 设置MainWindow引用 //_mainWindow = mainWindow; // 初始化一个空行 _lines.Add(new TextLine()); // 注册命令绑定 CommandBindings.Add(new CommandBinding(ApplicationCommands.Copy, OnCopy)); CommandBindings.Add(new CommandBinding(ApplicationCommands.Cut, OnCut)); CommandBindings.Add(new CommandBinding(ApplicationCommands.Paste, OnPaste)); CommandBindings.Add(new CommandBinding(ApplicationCommands.Undo, OnUndo)); CommandBindings.Add(new CommandBinding(ApplicationCommands.Redo, OnRedo)); CommandBindings.Add(new CommandBinding(ApplicationCommands.SelectAll, OnSelectAll)); // 创建右键菜单 CreateContextMenu(); } #endregion #region 事件处理 public static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = (TextEditorControl)d; if (e.NewValue is string) { //control.SetText((string)e.NewValue); } else if (e.NewValue is JObject) { //control.SetText((JObject)e.NewValue, ""); } } protected override void OnRender(DrawingContext drawingContext) { base.OnRender(drawingContext); RenderEditor(drawingContext); } protected override void OnMouseWheel(MouseWheelEventArgs e) { base.OnMouseWheel(e); // 计算字体度量 double lineHeight = FontSize * 1.2; // 根据滚轮方向调整滚动偏移量 // 向上滚动(e.Delta > 0)时,减小偏移量,向下滚动时增加偏移量 int scrollLines = e.Delta > 0 ? -3 : 3; _scrollOffset += scrollLines; // 限制滚动范围 int maxVisibleLines = (int)(ActualHeight / lineHeight); int maxScrollOffset = Math.Max(0, _lines.Count - maxVisibleLines + 1); _scrollOffset = Math.Max(0, Math.Min(_scrollOffset, maxScrollOffset)); // 完全移除对光标位置的限制,允许自由滚动查看文档 e.Handled = true; InvalidateVisual(); } protected override void OnTextInput(TextCompositionEventArgs e) { base.OnTextInput(e); if (!IsReadOnly) { //InsertText(e.Text); InsertTextCharacters(e.Text); // 标记文本已更改 _textChanged = true; // 触发文本改变事件 OnTextChanged(); // 触发光标位置改变事件 OnCursorPositionChanged(_cursorLine, _cursorColumn); // 重绘编辑器 InvalidateVisual(); e.Handled = true; } } protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); HandleKeyDown(e); } public void showCurrChar() { TextCharacter chr = GetCharacterAfterCursor(); if (chr != null) { string m5 = chr.ImageMD5; if (m5 != "") { //var (pth_img, pth_json) = Global.get_img_json_pth(m5); var (pth_img, pth_json) = Global.get_img_json_pthv2(_pthimg); if (Path.Exists(pth_json) && Path.Exists(pth_img)) { string jsn_str = File.ReadAllText(pth_json, Encoding.UTF8); JObject jsn = (JObject)JsonConvert.DeserializeObject(jsn_str); string b64_str = File.ReadAllText(pth_img, Encoding.UTF8); byte[] img_bytes = Base64.Base64Decode(b64_str); Mat im_orig = Cv2.ImDecode(img_bytes, ImreadModes.Color); int width = jsn.Value("width"); int height = jsn.Value("height"); var prism_wordsInfo = jsn["prism_wordsInfo"].Value(); bool found = false; foreach (var item in prism_wordsInfo) { JArray charInfo = item["charInfo"].Value(); string line_word = item["word"].Value(); int line_x = item["x"].Value(); int line_y = item["y"].Value(); int line_width = item["width"].Value(); int line_height = item["height"].Value(); foreach (var item2 in charInfo) { string oneChar = item2["word"].Value(); int x = item2["x"].Value(); int y = item2["y"].Value(); int w = item2["w"].Value(); int h = item2["h"].Value(); //if (oneChar == chr.Character.ToString()) if (true) // 修改字符后它就可以不等了。有相同坐标宽高的字符只有一种情况,就是它们都是某个“单词”的一部分 { if (chr.x == x) { if (chr.y == y) { Cv2.Rectangle(im_orig, new OpenCvSharp.Rect(chr.x, chr.y, chr.w, chr.h), new OpenCvSharp.Scalar(0, 0, 255)); Mat cut = im_orig.Clone(new OpenCvSharp.Rect(0, line_y, im_orig.Width, line_height)); // 显示图片预览窗口 ShowDraggableImageControl(cut, im_orig); // 转换坐标到显示坐标系 var displayPos = ConvertOriginalToDisplayCoordinates(chr.x, chr.y); var displaySize = ConvertOriginalToDisplaySize(chr.w, chr.h); var x_y_ = ConvertDisplayToOriginalCoordinates(displayPos.X, displayPos.Y); var w_h_ = ConvertDisplayToOriginalSize(displaySize.Width, displaySize.Height); // 调用MainWindow显示选框 _mainWindow?.ShowCharacterSelection(displayPos.X, displayPos.Y, displaySize.Width, displaySize.Height); found = true; break; } } } } if (found) { break; } } } } System.Diagnostics.Debug.WriteLine($"光标后字符: {chr.Character}"); } } protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { base.OnMouseLeftButtonDown(e); Focus(); Point position = e.GetPosition(this); SetCursorPositionFromPoint(position); if (Keyboard.Modifiers != ModifierKeys.Shift) { ClearSelection(); } else { UpdateSelection(); } // 图片中框选光标后面的第一个字符 if (e.ChangedButton == MouseButton.Left && e.ButtonState == MouseButtonState.Pressed) { showCurrChar(); } e.Handled = true; InvalidateVisual(); } // 重写右键按下事件 protected override void OnMouseRightButtonDown(MouseButtonEventArgs e) { base.OnMouseRightButtonDown(e); // 设置焦点 Focus(); // 获取鼠标位置并设置光标位置 Point position = e.GetPosition(this); // 如果右键点击的位置不在当前选择区域内,则移动光标到点击位置 // 但不清除选择区域,这样在选中文本上右键点击时不会丢失选择 if (!IsPositionInSelection(position)) { //SetCursorPositionFromPoint(position); // 移除以下行,不再清除选择区域 // ClearSelection(); InvalidateVisual(); } e.Handled = true; } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (e.LeftButton == MouseButtonState.Pressed) { Point position = e.GetPosition(this); SetCursorPositionFromPoint(position); UpdateSelection(); InvalidateVisual(); } } #endregion #region 命令处理 // 将原图坐标转换为显示坐标 public Point ConvertOriginalToDisplayCoordinates(int originalX, int originalY) { if (_mainWindow?.ViewModel?.Image == null) return new Point(originalX, originalY); // 获取图片控件 var imageElement = _mainWindow.image; if (imageElement == null) return new Point(originalX, originalY); // 获取原图尺寸 double originalWidth = _mainWindow.ViewModel.Image.PixelWidth; double originalHeight = _mainWindow.ViewModel.Image.PixelHeight; // 获取显示尺寸 double displayWidth = imageElement.ActualWidth; double displayHeight = imageElement.ActualHeight; // 计算缩放比例 double scaleX = displayWidth / originalWidth; double scaleY = displayHeight / originalHeight; // 转换坐标 double displayX = originalX * scaleX; double displayY = originalY * scaleY; return new Point(displayX, displayY); } // 将显示坐标转换为原图坐标 public Point ConvertDisplayToOriginalCoordinates(double displayX, double displayY) { if (_mainWindow?.ViewModel?.Image == null) return new Point(displayX, displayY); // 获取图片控件 var imageElement = _mainWindow.image; if (imageElement == null) return new Point(displayX, displayY); // 获取原图尺寸 double originalWidth = _mainWindow.ViewModel.Image.PixelWidth; double originalHeight = _mainWindow.ViewModel.Image.PixelHeight; // 获取显示尺寸 double displayWidth = imageElement.ActualWidth; double displayHeight = imageElement.ActualHeight; // 计算缩放比例 double scaleX = displayWidth / originalWidth; double scaleY = displayHeight / originalHeight; // 反向转换坐标(除法操作) double originalX = displayX / scaleX; double originalY = displayY / scaleY; return new Point(originalX, originalY); } // 将原图尺寸转换为显示尺寸 public Size ConvertOriginalToDisplaySize(int originalWidth, int originalHeight) { if (_mainWindow?.ViewModel?.Image == null) return new Size(originalWidth, originalHeight); // 获取图片控件 var imageElement = _mainWindow.image; if (imageElement == null) return new Size(originalWidth, originalHeight); // 获取原图尺寸 double imgOriginalWidth = _mainWindow.ViewModel.Image.PixelWidth; double imgOriginalHeight = _mainWindow.ViewModel.Image.PixelHeight; // 获取显示尺寸 double displayWidth = imageElement.ActualWidth; double displayHeight = imageElement.ActualHeight; // 计算缩放比例 double scaleX = displayWidth / imgOriginalWidth; double scaleY = displayHeight / imgOriginalHeight; // 转换尺寸 double scaledWidth = originalWidth * scaleX; double scaledHeight = originalHeight * scaleY; return new Size(scaledWidth, scaledHeight); } // 将显示尺寸转换为原图尺寸 public Size ConvertDisplayToOriginalSize(double displayWidth, double displayHeight) { if (_mainWindow?.ViewModel?.Image == null) return new Size(displayWidth, displayHeight); // 获取图片控件 var imageElement = _mainWindow.image; if (imageElement == null) return new Size(displayWidth, displayHeight); // 获取原图尺寸 double imgOriginalWidth = _mainWindow.ViewModel.Image.PixelWidth; double imgOriginalHeight = _mainWindow.ViewModel.Image.PixelHeight; // 获取显示尺寸 double imgDisplayWidth = imageElement.ActualWidth; double imgDisplayHeight = imageElement.ActualHeight; // 计算缩放比例 double scaleX = imgDisplayWidth / imgOriginalWidth; double scaleY = imgDisplayHeight / imgOriginalHeight; // 反向转换尺寸(除法操作) double originalWidth = displayWidth / scaleX; double originalHeight = displayHeight / scaleY; return new Size(originalWidth, originalHeight); } private void OnCopy(object sender, ExecutedRoutedEventArgs e) { if (HasSelection()) { _isCut = false; // 创建DataObject来同时设置多种格式 DataObject dataObject = new DataObject(); // 设置标准文本格式(供其他程序使用) dataObject.SetText(GetSelectedText()); // 序列化TextCharacter列表并保存自定义格式 try { var characters = GetSelectedTextCharacters(); if (characters.Count > 0) { string json = Newtonsoft.Json.JsonConvert.SerializeObject(characters); dataObject.SetData("TextEditorCustomFormat", json); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"复制到剪贴板时出错: {ex.Message}"); } // 一次性设置到剪贴板 Clipboard.SetDataObject(dataObject); } e.Handled = true; } private void OnCut(object sender, ExecutedRoutedEventArgs e) { if (!IsReadOnly && HasSelection()) { _isCut = true; // 创建DataObject来同时设置多种格式 DataObject dataObject = new DataObject(); // 设置标准文本格式(供其他程序使用) dataObject.SetText(GetSelectedText()); // 序列化TextCharacter列表并保存自定义格式 try { var characters = GetSelectedTextCharacters(); if (characters.Count > 0) { // 序列化 string json = Newtonsoft.Json.JsonConvert.SerializeObject(characters); dataObject.SetData("TextEditorCustomFormat", json); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"剪切到剪贴板时出错: {ex.Message}"); } // 一次性设置到剪贴板 Clipboard.SetDataObject(dataObject); DeleteSelection(); InvalidateVisual(); } e.Handled = true; } private void OnPaste(object sender, ExecutedRoutedEventArgs e) { if (!IsReadOnly) { List characters_selected = GetSelectedTextCharacters(); // 尝试从剪贴板获取自定义格式数据 bool customDataPasted = false; if (Clipboard.ContainsData("TextEditorCustomFormat")) { try { // 反序列化 string json = Clipboard.GetData("TextEditorCustomFormat") as string; //List characters = (List)Newtonsoft.Json.JsonConvert.DeserializeObject>(json); List characters = new List(); List ls = Newtonsoft.Json.JsonConvert.DeserializeObject>(json); // System.Text.Rune 字段不支持直接序列化,所以需要转换 foreach (var item in ls) { var Character = item["Character"].Value(); var Value = Character["Value"].Value(); System.Text.Rune rune = new System.Text.Rune(Value); // 反序列化每个字符 var chr = new TextCharacter( rune, // 获取第一个字符 item["guid"].Value(), item["x"].Value(), item["y"].Value(), item["w"].Value(), item["h"].Value(), item["ImageMD5"].Value() ); characters.Add(chr); } if (characters != null && characters.Count > 0) { InsertTextCharacters(characters); customDataPasted = true; } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"从剪贴板粘贴时出错: {ex.Message}"); customDataPasted = false; } } // 如果是复制的普通文本 if (!customDataPasted && Clipboard.ContainsText()) { string text = Clipboard.GetText(); if (text.Length > 0) { //List characters = new List(); //TextCharacter c = null; //if (characters_selected.Count > 0) //{ // c = characters_selected[0]; //} //for (int i = 0; i < text.Length;) //{ // Rune rune = Rune.GetRuneAt(text, i); // var chr = new TextCharacter( // rune, // c.guid, // c.x, // c.y, // c.w, // c.h, // c.ImageMD5 // ); // characters.Add(chr); // i += rune.Utf16SequenceLength; //} //if (characters != null && characters.Count > 0) //{ // InsertTextCharacters(characters); //} InsertTextCharacters(text); } } if (_isCut) { Clipboard.Clear(); _isCut = false; // 重置剪切状态 } InvalidateVisual(); } if (HasSelection()) { DeleteSelection(); } e.Handled = true; } public void InsertTextCharacters(string text) { if (text.Length > 0) { List characters = new List(); TextCharacter c = null; if (HasSelection()) { List characters_selected = GetSelectedTextCharacters(); if (characters_selected.Count > 0) { c = characters_selected[0]; } } else { c = GetCharacterAfterCursor(); if (c == null) { c = GetCharacterBeforeCursor(); } } for (int i = 0; i < text.Length;) { Rune rune = Rune.GetRuneAt(text, i); if (c != null) { var chr = new TextCharacter( rune, c.guid, c.x, c.y, c.w, c.h, c.ImageMD5 ); characters.Add(chr); } else { var chr = new TextCharacter( rune, Guid.NewGuid().ToString(), - 1, -1, -1, -1, "" ); characters.Add(chr); } i += rune.Utf16SequenceLength; } if (characters != null && characters.Count > 0) { InsertTextCharacters(characters); } } } private void InsertTextCharacters(List characters) { if (characters == null || characters.Count == 0) return; // 如果有选中的文本,先删除它 if (HasSelection()) { DeleteSelection(); } // 记录撤销操作 var undoAction = new UndoAction { CursorBeforeLine = _cursorLine, CursorBeforeColumn = _cursorColumn }; // 将字符插入到当前行的光标位置 var line = _lines[_cursorLine]; line.Characters.InsertRange(_cursorColumn, characters); _cursorColumn += characters.Count; // 记录添加的文本信息 undoAction.AddedText = string.Concat(characters.Select(c => c.Character.ToString())); undoAction.AddedStartLine = _cursorLine; undoAction.AddedStartColumn = _cursorColumn - characters.Count; undoAction.AddedEndLine = _cursorLine; undoAction.AddedEndColumn = _cursorColumn; // 记录撤销操作后的光标位置 undoAction.CursorAfterLine = _cursorLine; undoAction.CursorAfterColumn = _cursorColumn; // 添加到撤销缓冲区 if (_undoIndex < _undoBuffer.Count - 1) { _undoBuffer.RemoveRange(_undoIndex + 1, _undoBuffer.Count - _undoIndex - 1); } _undoBuffer.Add(undoAction); _undoIndex = _undoBuffer.Count - 1; // 标记文本已更改 _textChanged = true; // 触发文本改变事件 OnTextChanged(); // 触发光标位置改变事件 OnCursorPositionChanged(_cursorLine, _cursorColumn); } private void OnUndo(object sender, ExecutedRoutedEventArgs e) { if (!IsReadOnly && CanUndo()) { Undo(); InvalidateVisual(); } e.Handled = true; } private void OnRedo(object sender, ExecutedRoutedEventArgs e) { if (!IsReadOnly && CanRedo()) { Redo(); InvalidateVisual(); } e.Handled = true; } private void OnSelectAll(object sender, ExecutedRoutedEventArgs e) { SelectAll(); InvalidateVisual(); e.Handled = true; } #endregion #region 辅助方法 public void SetText(string text) { _lines.Clear(); _undoBuffer.Clear(); _undoIndex = -1; if (string.IsNullOrEmpty(text)) { _lines.Add(new TextLine()); } else { var lines = text.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n'); foreach (var line in lines) { var textLine = new TextLine(); foreach (var c in line) { textLine.Characters.Add(new TextCharacter(c)); } _lines.Add(textLine); } } _cursorLine = 0; _cursorColumn = 0; ClearSelection(); _textChanged = true; InvalidateVisual(); // 触发文本改变事件 OnTextChanged(); } public void SetText(JObject jsn, string md5) { _lines.Clear(); _undoBuffer.Clear(); _undoIndex = -1; if (jsn == null) { SetText(string.Empty); } else { int width = jsn.Value("width"); int height = jsn.Value("height"); var prism_wordsInfo = jsn["prism_wordsInfo"].Value(); foreach (var item in prism_wordsInfo) { JArray charInfo = item["charInfo"].Value(); string line_word = item["word"].Value(); var textLine = new TextLine(); foreach (var item2 in charInfo) { string oneChar = item2["word"].Value(); string guid = item2["guid"].Value(); int isDeleted = item2["isDeleted"].Value(); // 就算是阿里云的 json ,也要先给它加入 guid //if (item2["guid"] != null) //{ // guid = item2["guid"].Value(); //} else //{ // guid = Guid.NewGuid().ToString(); //} if (isDeleted == 1) { continue; } int x = item2["x"].Value(); int y = item2["y"].Value(); int w = item2["w"].Value(); int h = item2["h"].Value(); // 遍历 oneChar 中的每个字符 for (int i = 0; i < oneChar.Length;) { // 获取当前位置的 Rune Rune rune = Rune.GetRuneAt(oneChar, i); // 4 个字节表示单个字符 // 将 Rune 添加到字符列表中 textLine.Characters.Add(new TextCharacter(rune, guid, x, y, w, h, md5)); // 移动到下一个 Rune 的位置 i += rune.Utf16SequenceLength; } //Rune rune = Rune.GetRuneAt(oneChar, 0); // 4 个字节表示单个字符 //textLine.Characters.Add(new TextCharacter(rune, x, y, w, h, md5)); } _lines.Add(textLine); } } _cursorLine = 0; _cursorColumn = 0; ClearSelection(); _textChanged = true; InvalidateVisual(); // 触发文本改变事件 OnTextChanged(); } public List get_text_lines(JObject jsn, string md5) { List lines = new List(); int width = jsn.Value("width"); int height = jsn.Value("height"); var prism_wordsInfo = jsn["prism_wordsInfo"].Value(); foreach (var item in prism_wordsInfo) { JObject selected_rectange = new JObject(); if (_mode == EditorMode.ReviseEdit) // 校对模式才有选框 { selected_rectange = item["selected_rectange"].Value(); } JArray pos = item["pos"].Value(); JArray charInfo = item["charInfo"].Value(); string line_word = item["word"].Value(); var textLine = new TextLine(pos, selected_rectange); foreach (var item2 in charInfo) { string oneChar = item2["word"].Value(); string guid = item2["guid"].Value(); // 就算是阿里云的 json ,也要先给它加入 guid //if (item2["guid"] != null) //{ // guid = item2["guid"].Value(); //} else //{ // guid = Guid.NewGuid().ToString(); //} int x = item2["x"].Value(); int y = item2["y"].Value(); int w = item2["w"].Value(); int h = item2["h"].Value(); // 遍历 oneChar 中的每个字符 for (int i = 0; i < oneChar.Length;) { // 获取当前位置的 Rune Rune rune = Rune.GetRuneAt(oneChar, i); // 4 个字节表示单个字符 // 将 Rune 添加到字符列表中 textLine.Characters.Add(new TextCharacter(rune, guid, x, y, w, h, md5)); // 移动到下一个 Rune 的位置 i += rune.Utf16SequenceLength; } //Rune rune = Rune.GetRuneAt(oneChar, 0); // 4 个字节表示单个字符 //textLine.Characters.Add(new TextCharacter(rune, x, y, w, h, md5)); } lines.Add(textLine); } return lines; } public void InsertText(JObject jsn, string md5) { _undoBuffer.Clear(); _undoIndex = -1; if (jsn == null) { SetText(string.Empty); } else { //int width = jsn.Value("width"); //int height = jsn.Value("height"); //var prism_wordsInfo = jsn["prism_wordsInfo"].Value(); //foreach (var item in prism_wordsInfo) //{ // JObject selected_rectange = new JObject(); // if (_mode == EditorMode.ReviseEdit) // 校对模式才有选框 // { // selected_rectange = item["selected_rectange"].Value(); // } // JArray pos = item["pos"].Value(); // JArray charInfo = item["charInfo"].Value(); // string line_word = item["word"].Value(); // var textLine = new TextLine(pos, selected_rectange); // foreach (var item2 in charInfo) // { // string oneChar = item2["word"].Value(); // string guid = item2["guid"].Value(); // // 就算是阿里云的 json ,也要先给它加入 guid // //if (item2["guid"] != null) // //{ // // guid = item2["guid"].Value(); // //} else // //{ // // guid = Guid.NewGuid().ToString(); // //} // int x = item2["x"].Value(); // int y = item2["y"].Value(); // int w = item2["w"].Value(); // int h = item2["h"].Value(); // // 遍历 oneChar 中的每个字符 // for (int i = 0; i < oneChar.Length;) // { // // 获取当前位置的 Rune // Rune rune = Rune.GetRuneAt(oneChar, i); // 4 个字节表示单个字符 // // 将 Rune 添加到字符列表中 // textLine.Characters.Add(new TextCharacter(rune, guid, x, y, w, h, md5)); // // 移动到下一个 Rune 的位置 // i += rune.Utf16SequenceLength; // } // //Rune rune = Rune.GetRuneAt(oneChar, 0); // 4 个字节表示单个字符 // //textLine.Characters.Add(new TextCharacter(rune, x, y, w, h, md5)); // } // _lines.Add(textLine); //} var lines = get_text_lines(jsn, md5); foreach(var line in lines) { _lines.Add(line); } } //_cursorLine = 0; //_cursorColumn = 0; ClearSelection(); _textChanged = true; InvalidateVisual(); // 触发文本改变事件 OnTextChanged(); } public bool saveJson(string pth_img_) { bool isModify = false; string m5 = MD5.ComputeFileHash(pth_img_); var (pth_img, pth_json) = Global.get_img_json_pthv2(pth_img_); if (!Path.Exists(pth_json) || !Path.Exists(pth_img)) { return false; } if (_mode == EditorMode.ReviseEdit) { Global.saveJsonReviseEdit(pth_json, _lines); return false; } if (_mode == EditorMode.MenuSplit) { Global.saveJsonReviseEdit(pth_json, _lines); return false; } var jsonstr = File.ReadAllText(pth_json, new System.Text.UTF8Encoding(false)); JObject jsn = null; try { jsn = JObject.Parse(jsonstr); } catch (Exception ex) { MessageBox.Show("json 解析失败", "错误", MessageBoxButton.OK, MessageBoxImage.Error); return false; } int width = jsn.Value("width"); int height = jsn.Value("height"); var prism_wordsInfo = jsn["prism_wordsInfo"].Value(); foreach (var item in prism_wordsInfo) { JArray charInfo = item["charInfo"].Value(); string line_word = item["word"].Value(); var textLine = new TextLine(); foreach (var item2 in charInfo) { string oneChar = item2["word"].Value(); string guid = item2["guid"].Value(); int x = item2["x"].Value(); int y = item2["y"].Value(); int w = item2["w"].Value(); int h = item2["h"].Value(); // 遍历 oneChar 中的每个字符 for (int i = 0; i < oneChar.Length;) { Rune rune = Rune.GetRuneAt(oneChar, i); // 4 个字节表示单个字符 // 移动到下一个 Rune 的位置 i += rune.Utf16SequenceLength; } if ( _dic_deleted_char.ContainsKey(guid) ) { // 是被标记逻辑删除的字符 item2["isDeleted"] = 1; isModify = true; } foreach (TextLine line in _lines) { bool line_modify = false; foreach (TextCharacter c in line.Characters) { string ImageMD5 = c.ImageMD5; if (ImageMD5 == m5) { if (guid == c.guid) { string c_str = c.Character.ToString(); if (c_str != oneChar) { item2["word"] = c_str; line_modify = true; isModify = true; } } } } if (line_modify) { string new_line_word = string.Concat(line.Characters.Select(c => c.Character.ToString())); item["word"] = new_line_word; } } } } if (isModify) { string jsn_str = jsn.ToString(Formatting.Indented).Replace("\r\n", "\n"); File.WriteAllText(pth_json, jsn_str); } return isModify; } private void RenderEditor(DrawingContext drawingContext) { // 绘制背景 drawingContext.DrawRectangle(Brushes.White, null, new Rect(0, 0, ActualWidth, ActualHeight)); // 计算字体度量 var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch); double lineHeight = FontSize * 1.2; double defaultCharWidth = FontSize * 0.6; // 默认字符宽度(英文) // 计算行号区域宽度 double lineNumberWidth = LineNumbersVisible ? 40 : 0; // 绘制行号区域背景 if (LineNumbersVisible) { drawingContext.DrawRectangle(Brushes.LightGray, null, new Rect(0, 0, lineNumberWidth, ActualHeight)); } double textStartX = lineNumberWidth + 5; // 文本起始X坐标 // 计算可见行范围 int visibleLineCount = (int)Math.Ceiling(ActualHeight / lineHeight); int startLine = _scrollOffset; int endLine = Math.Min(_scrollOffset + visibleLineCount, _lines.Count - 1); // 高亮当前行 if (HighlightCurrentLine && _cursorLine >= startLine && _cursorLine <= endLine) { drawingContext.DrawRectangle(Brushes.LightYellow, null, new Rect(lineNumberWidth, (_cursorLine - _scrollOffset) * lineHeight, ActualWidth - lineNumberWidth, lineHeight)); } // 绘制文本和行号 for (int i = startLine; i <= endLine; i++) { double y = (i - _scrollOffset) * lineHeight; // 绘制行号 if (LineNumbersVisible) { var lineNumberText = new FormattedText( (i + 1).ToString(), System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, FontSize, Brushes.Gray, VisualTreeHelper.GetDpi(this).PixelsPerDip); drawingContext.DrawText(lineNumberText, new Point(5, y)); } // 绘制文本 var line = _lines[i]; double x = textStartX; for (int j = 0; j < line.Characters.Count; j++) { var character = line.Characters[j]; // 绘制选中区域背景 double charWidth = IsFullWidthCharacter(character.Character) ? defaultCharWidth * 2 : defaultCharWidth; if (HasSelection() && IsPositionSelected(i, j)) { drawingContext.DrawRectangle(Brushes.LightBlue, null, new Rect(x, y, charWidth, lineHeight)); } // 绘制字符 var formattedText = new FormattedText( character.Character.ToString(), System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, FontSize, character.Foreground, VisualTreeHelper.GetDpi(this).PixelsPerDip); drawingContext.DrawText(formattedText, new Point(x, y)); // 显示空白字符 if (ShowWhitespaces && character.Character.Value == ' ') { drawingContext.DrawLine( new Pen(Brushes.LightGray, 1), new Point(x + charWidth / 2, y + lineHeight / 2), new Point(x + charWidth / 2, y + lineHeight / 2)); } x += charWidth; } } // 绘制光标 if (IsFocused && _cursorLine >= startLine && _cursorLine <= endLine) { // 计算光标X坐标,考虑前面字符的宽度 double cursorX = textStartX; var line = _lines[_cursorLine]; for (int j = 0; j < _cursorColumn && j < line.Characters.Count; j++) { cursorX += IsFullWidthCharacter(line.Characters[j].Character) ? defaultCharWidth * 2 : defaultCharWidth; } double cursorY = (_cursorLine - _scrollOffset) * lineHeight; drawingContext.DrawLine( new Pen(Brushes.Black, 1), new Point(cursorX, cursorY), new Point(cursorX, cursorY + lineHeight)); } } // 判断是否是全角字符(如中文、日文等) private bool IsFullWidthCharacter(System.Text.Rune r) { int value = r.Value; // 中文字符范围 if (value >= 0x4E00 && value <= 0x9FFF) return true; // CJK统一汉字 if (value >= 0x3400 && value <= 0x4DBF) return true; // CJK扩展A if (value >= 0x20000 && value <= 0x2A6DF) return true; // CJK扩展B if (value >= 0x2A700 && value <= 0x2B73F) return true; // CJK扩展C if (value >= 0x2B740 && value <= 0x2B81F) return true; // CJK扩展D if (value >= 0x2B820 && value <= 0x2CEAF) return true; // CJK扩展E if (value >= 0xF900 && value <= 0xFAFF) return true; // CJK兼容汉字 // 日文假名等 if (value >= 0x3040 && value <= 0x309F) return true; // 平假名 if (value >= 0x30A0 && value <= 0x30FF) return true; // 片假名 // 全角标点和符号 if (value >= 0xFF00 && value <= 0xFFEF) return true; // 全角ASCII、全角标点 // 其他全角字符 if (value >= 0x3000 && value <= 0x303F) return true; // CJK符号和标点 return false; } private bool IsPositionSelected(int line, int column) { if (!HasSelection()) return false; int startLine = Math.Min(_selectionStartLine, _selectionEndLine); int startColumn = startLine == _selectionStartLine ? _selectionStartColumn : _selectionEndColumn; int endLine = Math.Max(_selectionStartLine, _selectionEndLine); int endColumn = endLine == _selectionEndLine ? _selectionEndColumn : _selectionStartColumn; if (line < startLine || line > endLine) return false; if (line == startLine && line == endLine) return column >= startColumn && column < endColumn; if (line == startLine) return column >= startColumn; if (line == endLine) return column < endColumn; return true; } // 检查位置是否在选择区域内的辅助方法 private bool IsPositionInSelection(Point position) { if (!HasSelection()) return false; // 计算字体度量 var typeface = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch); var formattedText = new FormattedText("M", System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, FontSize, Brushes.Black, VisualTreeHelper.GetDpi(this).PixelsPerDip); double charWidth = formattedText.Width; double lineHeight = formattedText.Height; // 计算点击位置对应的行列 int clickLine = Math.Max(0, Math.Min((int)(position.Y / lineHeight) + _scrollOffset, _lines.Count - 1)); int clickColumn = Math.Max(0, (int)((position.X - 50) / charWidth)); // 50是行号区域宽度 // 获取选择区域的起始和结束位置 int startLine = Math.Min(_selectionStartLine, _selectionEndLine); int startColumn = startLine == _selectionStartLine ? _selectionStartColumn : _selectionEndColumn; int endLine = Math.Max(_selectionStartLine, _selectionEndLine); int endColumn = endLine == _selectionEndLine ? _selectionEndColumn : _selectionStartColumn; // 检查点击位置是否在选择区域内 if (clickLine < startLine || clickLine > endLine) return false; if (clickLine == startLine && clickLine == endLine) { return clickColumn >= startColumn && clickColumn <= endColumn; } else if (clickLine == startLine) { return clickColumn >= startColumn; } else if (clickLine == endLine) { return clickColumn <= endColumn; } else { return true; // 在中间行 } } private void SetCursorPositionFromPoint(Point point) { if (_lines.Count <= 0) { return; } // 计算字体度量 double lineHeight = FontSize * 1.2; double defaultCharWidth = FontSize * 0.6; // 默认字符宽度 // 计算行号区域宽度 double lineNumberWidth = LineNumbersVisible ? 40 : 0; double textStartX = lineNumberWidth + 5; // 文本起始X坐标 // 计算行号,考虑滚动偏移量 int line = (int)(point.Y / lineHeight) + _scrollOffset; line = Math.Max(0, Math.Min(line, _lines.Count - 1)); // 计算列号,考虑字符宽度 double x = textStartX; int column = 0; var textLine = _lines[line]; // 找到光标应该在的位置 while (column < textLine.Characters.Count && x < point.X) { x += IsFullWidthCharacter(textLine.Characters[column].Character) ? defaultCharWidth * 2 : defaultCharWidth; if (x > point.X) { // 如果点击位置在字符的前半部分,光标放在字符前面 // 如果在后半部分,光标放在字符后面 double charWidth = IsFullWidthCharacter(textLine.Characters[column].Character) ? defaultCharWidth * 2 : defaultCharWidth; if (point.X > x - charWidth / 2) column++; break; } column++; } // 设置光标位置 _cursorLine = line; _cursorColumn = column; // 触发光标位置改变事件 OnCursorPositionChanged(_cursorLine, _cursorColumn); } private void HandleKeyDown(KeyEventArgs e) { if (IsReadOnly) { e.Handled = true; return; } // 处理组合键 if (Keyboard.Modifiers == ModifierKeys.Control) { switch (e.Key) { case Key.F: ShowFindDialog(); e.Handled = true; return; } } switch (e.Key) { case Key.Left: if (_cursorColumn > 0) { _cursorColumn--; showCurrChar(); } else if (_cursorLine > 0) { _cursorLine--; _cursorColumn = _lines[_cursorLine].Characters.Count; showCurrChar(); } break; case Key.Right: if (_cursorColumn < _lines[_cursorLine].Characters.Count) { _cursorColumn++; showCurrChar(); } else if (_cursorLine < _lines.Count - 1) { _cursorLine++; _cursorColumn = 0; showCurrChar(); } break; case Key.Up: if (_cursorLine > 0) { _cursorLine--; _cursorColumn = Math.Min(_cursorColumn, _lines[_cursorLine].Characters.Count); // 检查光标是否在可见区域内,如果不在则向上滚动一行 if (_cursorLine < _scrollOffset) { _scrollOffset--; } showCurrChar(); } break; case Key.Down: if (_cursorLine < _lines.Count - 1) { _cursorLine++; _cursorColumn = Math.Min(_cursorColumn, _lines[_cursorLine].Characters.Count); // 计算可见行数 double lineHeight = FontSize * 1.2; int visibleLineCount = (int)(ActualHeight / lineHeight); // 检查光标是否在可见区域内,如果不在则向下滚动一行 if (_cursorLine >= _scrollOffset + visibleLineCount) { _scrollOffset++; } showCurrChar(); } break; case Key.Home: _cursorColumn = 0; break; case Key.End: _cursorColumn = _lines[_cursorLine].Characters.Count; break; case Key.Delete: if (HasSelection()) { DeleteSelection(); } else if (_cursorColumn < _lines[_cursorLine].Characters.Count) { // 删除当前字符 TextCharacter c = _lines[_cursorLine].Characters[_cursorColumn]; if (c.guid != "") { _dic_deleted_char[c.guid] = c.Character.Value.ToString(); } _lines[_cursorLine].Characters.RemoveAt(_cursorColumn); _textChanged = true; OnTextChanged(); } else if (_cursorLine < _lines.Count - 1) { // 合并当前行和下一行 var nextLine = _lines[_cursorLine + 1]; _lines[_cursorLine].Characters.AddRange(nextLine.Characters); _lines.RemoveAt(_cursorLine + 1); _textChanged = true; OnTextChanged(); } break; case Key.Back: if (HasSelection()) { DeleteSelection(); } else if (_cursorColumn > 0) { // 删除前一个字符 _cursorColumn--; TextCharacter c = _lines[_cursorLine].Characters[_cursorColumn]; if (c.guid != "") { _dic_deleted_char[c.guid] = c.Character.Value.ToString(); } _lines[_cursorLine].Characters.RemoveAt(_cursorColumn); _textChanged = true; OnTextChanged(); } else if (_cursorLine > 0) { // 合并当前行和上一行 _cursorColumn = _lines[_cursorLine - 1].Characters.Count; _lines[_cursorLine - 1].Characters.AddRange(_lines[_cursorLine].Characters); _lines.RemoveAt(_cursorLine); _cursorLine--; _textChanged = true; OnTextChanged(); } break; case Key.Enter: // 插入新行 var currentLine = _lines[_cursorLine]; var newLine = new TextLine(); // 将当前行光标后的字符移到新行 if (_cursorColumn < currentLine.Characters.Count) { var remainingChars = currentLine.Characters.GetRange(_cursorColumn, currentLine.Characters.Count - _cursorColumn); newLine.Characters.AddRange(remainingChars); currentLine.Characters.RemoveRange(_cursorColumn, remainingChars.Count); } _lines.Insert(_cursorLine + 1, newLine); _cursorLine++; _cursorColumn = 0; _textChanged = true; OnTextChanged(); break; case Key.Tab: // 插入Tab(空格) for (int i = 0; i < TabSize; i++) { InsertText(" "); } break; default: e.Handled = false; return; } // 如果按下Shift键,更新选择区域 if (Keyboard.Modifiers == ModifierKeys.Shift) { UpdateSelection(); } else { ClearSelection(); } // 触发光标位置改变事件 OnCursorPositionChanged(_cursorLine, _cursorColumn); // 重绘编辑器 InvalidateVisual(); e.Handled = true; } private void DeleteSelection() { if (!HasSelection()) return; // 确保起始位置在结束位置之前 int startLine = Math.Min(_selectionStartLine, _selectionEndLine); int startColumn = startLine == _selectionStartLine ? _selectionStartColumn : _selectionEndColumn; int endLine = Math.Max(_selectionStartLine, _selectionEndLine); int endColumn = endLine == _selectionEndLine ? _selectionEndColumn : _selectionStartColumn; if (startLine == endLine) { // 单行删除 int start = Math.Min(startColumn, endColumn); int end = Math.Max(startColumn, endColumn); var line = _lines[startLine]; if (start < line.Characters.Count) { int length = Math.Min(end - start, line.Characters.Count - start); line.Characters.RemoveRange(start, length); } } else { // 多行删除 // 保留第一行开始部分 var firstLine = _lines[startLine]; if (startColumn < firstLine.Characters.Count) { firstLine.Characters.RemoveRange(startColumn, firstLine.Characters.Count - startColumn); } // 保留最后一行结束部分 var lastLine = _lines[endLine]; List lastLineRemaining = new List(); if (endColumn < lastLine.Characters.Count) { lastLineRemaining = lastLine.Characters.GetRange(endColumn, lastLine.Characters.Count - endColumn); } // 删除中间行 _lines.RemoveRange(startLine + 1, endLine - startLine); // 将最后一行剩余部分添加到第一行 firstLine.Characters.AddRange(lastLineRemaining); } // 设置光标位置到选择的开始位置 _cursorLine = startLine; _cursorColumn = startColumn; // 清除选择 ClearSelection(); // 标记文本已更改 _textChanged = true; // 触发文本改变事件 OnTextChanged(); // 触发光标位置改变事件 OnCursorPositionChanged(_cursorLine, _cursorColumn); } public string GetSelectedText() { if (!HasSelection()) return string.Empty; // 确保起始位置在结束位置之前 int startLine = Math.Min(_selectionStartLine, _selectionEndLine); int startColumn = startLine == _selectionStartLine ? _selectionStartColumn : _selectionEndColumn; int endLine = Math.Max(_selectionStartLine, _selectionEndLine); int endColumn = endLine == _selectionEndLine ? _selectionEndColumn : _selectionStartColumn; if (startLine == endLine) { // 单行选择 int start = Math.Min(startColumn, endColumn); int end = Math.Max(startColumn, endColumn); var line = _lines[startLine]; if (start < line.Characters.Count) { int length = Math.Min(end - start, line.Characters.Count - start); return string.Concat(line.Characters.GetRange(start, length).Select(c => c.Character.ToString())); } return string.Empty; } else { // 多行选择 StringBuilder sb = new StringBuilder(); // 第一行 var firstLine = _lines[startLine]; if (startColumn < firstLine.Characters.Count) { sb.Append(string.Concat(firstLine.Characters.GetRange(startColumn, firstLine.Characters.Count - startColumn).Select(c => c.Character.ToString()))); } sb.Append("\n"); // 中间行 for (int i = startLine + 1; i < endLine; i++) { sb.Append(string.Concat(_lines[i].Characters.Select(c => c.Character.ToString()))); sb.Append("\n"); } // 最后一行 var lastLine = _lines[endLine]; if (endColumn > 0 && lastLine.Characters.Count > 0) { sb.Append(string.Concat(lastLine.Characters.GetRange(0, Math.Min(endColumn, lastLine.Characters.Count)).Select(c => c.Character.ToString()))); } return sb.ToString(); } } private List GetSelectedTextCharacters() { if (!HasSelection()) return new List(); // 确保起始位置在结束位置之前 int startLine = Math.Min(_selectionStartLine, _selectionEndLine); int startColumn = startLine == _selectionStartLine ? _selectionStartColumn : _selectionEndColumn; int endLine = Math.Max(_selectionStartLine, _selectionEndLine); int endColumn = endLine == _selectionEndLine ? _selectionEndColumn : _selectionStartColumn; List result = new List(); if (startLine == endLine) { // 单行选择 int start = Math.Min(startColumn, endColumn); int end = Math.Max(startColumn, endColumn); var line = _lines[startLine]; if (start < line.Characters.Count) { int length = Math.Min(end - start, line.Characters.Count - start); result.AddRange(line.Characters.GetRange(start, length)); } } else { // 多行选择 // 第一行 var firstLine = _lines[startLine]; if (startColumn < firstLine.Characters.Count) { result.AddRange(firstLine.Characters.GetRange(startColumn, firstLine.Characters.Count - startColumn)); } // 中间行 for (int i = startLine + 1; i < endLine; i++) { result.AddRange(_lines[i].Characters); } // 最后一行 var lastLine = _lines[endLine]; if (endColumn > 0 && lastLine.Characters.Count > 0) { result.AddRange(lastLine.Characters.GetRange(0, Math.Min(endColumn, lastLine.Characters.Count))); } } return result; } private bool HasSelection() { // 判断是否有选中的文本 return _selectionStartLine >= 0 && _selectionEndLine >= 0; } private bool IsSingleSelection() { if (_selectionStartColumn >= 0 && _selectionEndColumn >= 0) { return _selectionStartColumn + 1 == _selectionEndColumn; } return false; } public void ClearSelection() { // 清除选择 _selectionStartLine = -1; _selectionStartColumn = -1; _selectionEndLine = -1; _selectionEndColumn = -1; } private void UpdateSelection() { // 更新选择区域 if (_selectionStartLine < 0) { _selectionStartLine = _cursorLine; _selectionStartColumn = _cursorColumn; } _selectionEndLine = _cursorLine; _selectionEndColumn = _cursorColumn; } private void SelectAll() { // 全选 _selectionStartLine = 0; _selectionStartColumn = 0; _selectionEndLine = _lines.Count - 1; _selectionEndColumn = _lines[_selectionEndLine].Characters.Count; } private bool CanUndo() { // 判断是否可以撤销 return _undoIndex >= 0; } private bool CanRedo() { // 判断是否可以重做 return _undoIndex < _undoBuffer.Count - 1; } private void Undo() { if (!CanUndo()) return; var action = _undoBuffer[_undoIndex]; // 恢复光标位置到操作前 _cursorLine = action.CursorBeforeLine; _cursorColumn = action.CursorBeforeColumn; // 如果有添加的文本,需要删除它 if (!string.IsNullOrEmpty(action.AddedText)) { // 设置选择区域为添加的文本 _selectionStartLine = action.AddedStartLine; _selectionStartColumn = action.AddedStartColumn; _selectionEndLine = action.AddedEndLine; _selectionEndColumn = action.AddedEndColumn; // 删除添加的文本 DeleteSelection(); } // 如果有删除的文本,需要恢复它 if (!string.IsNullOrEmpty(action.RemovedText)) { // 设置光标位置到删除的起始位置 _cursorLine = action.RemovedStartLine; _cursorColumn = action.RemovedStartColumn; // 插入被删除的文本 InsertText(action.RemovedText); // 恢复光标位置 _cursorLine = action.CursorBeforeLine; _cursorColumn = action.CursorBeforeColumn; } // 清除选择 ClearSelection(); // 更新撤销索引 _undoIndex--; // 触发光标位置改变事件 OnCursorPositionChanged(_cursorLine, _cursorColumn); } private void Redo() { if (!CanRedo()) return; // 更新撤销索引 _undoIndex++; var action = _undoBuffer[_undoIndex]; // 恢复光标位置到操作前 _cursorLine = action.CursorBeforeLine; _cursorColumn = action.CursorBeforeColumn; // 如果有删除的文本,需要再次删除它 if (!string.IsNullOrEmpty(action.RemovedText)) { // 设置选择区域为删除的文本 _selectionStartLine = action.RemovedStartLine; _selectionStartColumn = action.RemovedStartColumn; _selectionEndLine = action.RemovedEndLine; _selectionEndColumn = action.RemovedEndColumn; // 删除文本 DeleteSelection(); } // 如果有添加的文本,需要再次添加它 if (!string.IsNullOrEmpty(action.AddedText)) { // 设置光标位置到添加的起始位置 _cursorLine = action.AddedStartLine; _cursorColumn = action.AddedStartColumn; // 插入文本 InsertText(action.AddedText); } // 恢复光标位置到操作后 _cursorLine = action.CursorAfterLine; _cursorColumn = action.CursorAfterColumn; // 清除选择 ClearSelection(); // 触发光标位置改变事件 OnCursorPositionChanged(_cursorLine, _cursorColumn); } #endregion public event EventHandler TextChanged; public event EventHandler CursorPositionChanged; public virtual void OnTextChanged() { // 从_lines集合构建文本并更新TextProperty UpdateTextProperty(); TextChanged?.Invoke(this, EventArgs.Empty); } private void UpdateTextProperty() { // 从_lines集合构建完整的文本 StringBuilder sb = new StringBuilder(); for (int i = 0; i < _lines.Count; i++) { sb.Append(string.Concat(_lines[i].Characters.Select(c => c.Character.ToString()))); // 除了最后一行,每行后面都添加换行符 if (i < _lines.Count - 1) sb.Append("\n"); } // 保存当前光标位置 int savedCursorLine = _cursorLine; int savedCursorColumn = _cursorColumn; bool textChangedFlag = _textChanged; // 更新TextProperty,但不触发OnTextChanged回调 SetValue(TextProperty, sb.ToString()); // 恢复光标位置 _cursorLine = savedCursorLine; _cursorColumn = savedCursorColumn; _textChanged = textChangedFlag; } public virtual void OnCursorPositionChanged(int line, int column) { CursorPositionChanged?.Invoke(this, new CursorPositionChangedEventArgs(line, column)); } // 获取光标后面的第一个字符 private TextCharacter GetCharacterAfterCursor() { if (_cursorLine >= 0 && _cursorLine < _lines.Count) { var line = _lines[_cursorLine]; if (_cursorColumn >= 0 && _cursorColumn < line.Characters.Count) { // 返回光标位置的字符(即光标后面的第一个字符) return line.Characters[_cursorColumn]; } else if (_cursorColumn == line.Characters.Count && _cursorLine + 1 < _lines.Count) { // 如果光标在行尾,返回下一行的第一个字符 //var nextLine = _lines[_cursorLine + 1]; //if (nextLine.Characters.Count > 0) //{ // return nextLine.Characters[0]; //} return null; } } return null; // 如果没有找到字符,返回null } private TextCharacter GetCharacterBeforeCursor() { if (_cursorLine >= 0 && _cursorLine < _lines.Count) { var line = _lines[_cursorLine]; if (_cursorColumn > 0 && _cursorColumn <= line.Characters.Count) { // 返回光标位置的字符(即光标后面的第一个字符) return line.Characters[_cursorColumn - 1]; } else { return null; } } return null; // 如果没有找到字符,返回null } public void InsertText(string text) { if (string.IsNullOrEmpty(text)) return; // 如果有选中的文本,先删除或修改它 if (HasSelection()) { if ( IsSingleSelection() ) // 选中了单个字符 { if (text.Length == 1) { // 此处是修改单个字符的情况 var line = _lines[_cursorLine]; TextCharacter c = line.Characters[_cursorColumn-1]; c.Character = System.Text.Rune.GetRuneAt(text, 0); // 修改字符 // 清除选择 ClearSelection(); _cursorColumn = _cursorColumn - 1; // 触发光标位置改变事件 OnCursorPositionChanged(_cursorLine, _cursorColumn); // 重绘编辑器 InvalidateVisual(); return; } } DeleteSelection(); } // 记录撤销操作 var undoAction = new UndoAction { CursorBeforeLine = _cursorLine, CursorBeforeColumn = _cursorColumn }; // 处理多行文本 var lines = text.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n'); if (lines.Length == 1) { // 单行文本 var line = _lines[_cursorLine]; var chars = lines[0].EnumerateRunes().Select(r => new TextCharacter(r)).ToList(); line.Characters.InsertRange(_cursorColumn, chars); _cursorColumn += chars.Count; // 记录添加的文本信息 undoAction.AddedText = text; undoAction.AddedStartLine = _cursorLine; undoAction.AddedStartColumn = _cursorColumn - chars.Count; undoAction.AddedEndLine = _cursorLine; undoAction.AddedEndColumn = _cursorColumn; } else { // 多行文本 var currentLine = _lines[_cursorLine]; var remainingChars = currentLine.Characters.GetRange(_cursorColumn, currentLine.Characters.Count - _cursorColumn).ToList(); currentLine.Characters.RemoveRange(_cursorColumn, remainingChars.Count); // 添加第一行 var firstLineChars = lines[0].EnumerateRunes().Select(r => new TextCharacter(r)).ToList(); currentLine.Characters.AddRange(firstLineChars); // 添加中间行 for (int i = 1; i < lines.Length - 1; i++) { var newLine = new TextLine(); newLine.Characters.AddRange(lines[i].EnumerateRunes().Select(r => new TextCharacter(r))); _lines.Insert(_cursorLine + i, newLine); } // 添加最后一行和剩余字符 var lastLine = new TextLine(); lastLine.Characters.AddRange(lines[lines.Length - 1].EnumerateRunes().Select(r => new TextCharacter(r))); lastLine.Characters.AddRange(remainingChars); _lines.Insert(_cursorLine + lines.Length - 1, lastLine); // 更新光标位置 _cursorLine += lines.Length - 1; _cursorColumn = lastLine.Characters.Count - remainingChars.Count; // 记录添加的文本信息 undoAction.AddedText = text; undoAction.AddedStartLine = _cursorLine - (lines.Length - 1); undoAction.AddedStartColumn = _cursorColumn - firstLineChars.Count; undoAction.AddedEndLine = _cursorLine; undoAction.AddedEndColumn = _cursorColumn; } // 记录撤销操作后的光标位置 undoAction.CursorAfterLine = _cursorLine; undoAction.CursorAfterColumn = _cursorColumn; // 添加到撤销缓冲区 if (_undoIndex < _undoBuffer.Count - 1) { _undoBuffer.RemoveRange(_undoIndex + 1, _undoBuffer.Count - _undoIndex - 1); } _undoBuffer.Add(undoAction); _undoIndex = _undoBuffer.Count - 1; // 标记文本已更改 _textChanged = true; // 触发文本改变事件 OnTextChanged(); // 触发光标位置改变事件 OnCursorPositionChanged(_cursorLine, _cursorColumn); // 重绘编辑器 InvalidateVisual(); } #region 查找功能 /// /// 显示查找对话框 /// public void ShowFindDialog() { if (_findDialog == null || !_findDialog.IsLoaded) { _findDialog = new FindDialog(this); _findDialog.Owner = Window.GetWindow(this); } _findDialog.Show(); _findDialog.Activate(); } /// /// 获取当前选中的文本 /// /// //public string GetSelectedText() //{ // if (!HasSelection()) // return string.Empty; // var selectedChars = GetSelectedTextCharacters(); // return string.Join("", selectedChars.Select(c => c.Character.ToString())); //} /// /// 查找下一个匹配项 /// /// 要查找的文本 /// 是否区分大小写 /// 是否全字匹配 /// 是否找到 public bool FindNext(string searchText, bool matchCase, bool wholeWord) { if (string.IsNullOrEmpty(searchText)) return false; // 如果搜索条件改变,重新搜索 if (searchText != _lastSearchText || matchCase != _lastMatchCase || wholeWord != _lastWholeWord) { SearchAll(searchText, matchCase, wholeWord); } if (_findResults.Count == 0) return false; // 找到下一个匹配项 _currentFindIndex = (_currentFindIndex + 1) % _findResults.Count; var result = _findResults[_currentFindIndex]; // 移动光标到匹配位置 _cursorLine = result.line; _cursorColumn = result.column; // 设置选择区域 _selectionStartLine = result.line; _selectionStartColumn = result.column; _selectionEndLine = result.line; _selectionEndColumn = result.column + result.length; // 确保匹配项在可见区域内 EnsureCursorVisible(); // 重绘编辑器 InvalidateVisual(); return true; } /// /// 查找上一个匹配项 /// /// 要查找的文本 /// 是否区分大小写 /// 是否全字匹配 /// 是否找到 public bool FindPrevious(string searchText, bool matchCase, bool wholeWord) { if (string.IsNullOrEmpty(searchText)) return false; // 如果搜索条件改变,重新搜索 if (searchText != _lastSearchText || matchCase != _lastMatchCase || wholeWord != _lastWholeWord) { SearchAll(searchText, matchCase, wholeWord); } if (_findResults.Count == 0) return false; // 找到上一个匹配项 _currentFindIndex = (_currentFindIndex - 1 + _findResults.Count) % _findResults.Count; var result = _findResults[_currentFindIndex]; // 移动光标到匹配位置 _cursorLine = result.line; _cursorColumn = result.column; // 设置选择区域 _selectionStartLine = result.line; _selectionStartColumn = result.column; _selectionEndLine = result.line; _selectionEndColumn = result.column + result.length; // 确保匹配项在可见区域内 EnsureCursorVisible(); // 重绘编辑器 InvalidateVisual(); return true; } /// /// 搜索所有匹配项 /// /// 要查找的文本 /// 是否区分大小写 /// 是否全字匹配 private void SearchAll(string searchText, bool matchCase, bool wholeWord) { _findResults.Clear(); _currentFindIndex = -1; _lastSearchText = searchText; _lastMatchCase = matchCase; _lastWholeWord = wholeWord; if (string.IsNullOrEmpty(searchText)) return; StringComparison comparison = matchCase ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; for (int lineIndex = 0; lineIndex < _lines.Count; lineIndex++) { var line = _lines[lineIndex]; string lineText = string.Join("", line.Characters.Select(c => c.Character.ToString())); int startIndex = 0; while (startIndex < lineText.Length) { int foundIndex = lineText.IndexOf(searchText, startIndex, comparison); if (foundIndex == -1) break; // 检查全字匹配 if (wholeWord) { bool isWholeWord = true; // 检查前一个字符 if (foundIndex > 0) { char prevChar = lineText[foundIndex - 1]; if (char.IsLetterOrDigit(prevChar) || prevChar == '_') isWholeWord = false; } // 检查后一个字符 if (foundIndex + searchText.Length < lineText.Length) { char nextChar = lineText[foundIndex + searchText.Length]; if (char.IsLetterOrDigit(nextChar) || nextChar == '_') isWholeWord = false; } if (!isWholeWord) { startIndex = foundIndex + 1; continue; } } _findResults.Add((lineIndex, foundIndex, searchText.Length)); startIndex = foundIndex + 1; } } // 找到当前光标位置之后的第一个匹配项 for (int i = 0; i < _findResults.Count; i++) { var result = _findResults[i]; if (result.line > _cursorLine || (result.line == _cursorLine && result.column >= _cursorColumn)) { _currentFindIndex = i - 1; // 设置为前一个,因为FindNext会+1 return; } } // 如果没找到,设置为最后一个 if (_findResults.Count > 0) _currentFindIndex = _findResults.Count - 1; } /// /// 确保光标在可见区域内 /// private void EnsureCursorVisible() { double lineHeight = FontSize * 1.2; int visibleLineCount = (int)(ActualHeight / lineHeight); // 如果光标在可见区域上方 if (_cursorLine < _scrollOffset) { _scrollOffset = _cursorLine; } // 如果光标在可见区域下方 else if (_cursorLine >= _scrollOffset + visibleLineCount) { _scrollOffset = _cursorLine - visibleLineCount + 1; } // 确保滚动偏移量不为负数 _scrollOffset = Math.Max(0, _scrollOffset); } /// /// 清除查找高亮 /// public void ClearFindHighlight() { _findResults.Clear(); _currentFindIndex = -1; InvalidateVisual(); } #endregion } [Serializable] public class TextCharacter { [JsonIgnore] public System.Text.Rune Character { get; set; } // 对应图中的原始字符 // 用于 JSON 序列化的属性 [JsonProperty("Character")] public int CharacterValue { get => Character.Value; set => Character = new System.Text.Rune(value); } public Brush Foreground { get; set; } = Brushes.Black; public bool IsComment { get; set; } = false; public bool IsKeyword { get; set; } = false; public bool IsString { get; set; } = false; public bool IsNumber { get; set; } = false; // 字符在图片上的坐标和宽高 public int x { get; set; } = -1; public int y { get; set; } = -1; public int w { get; set; } = -1; public int h { get; set; } = -1; public string ImageMD5 { get; set; } = ""; public string guid { get; set; } = ""; // 添加无参构造函数用于JSON反序列化 public TextCharacter() { } public TextCharacter(System.Text.Rune c) { Character = c; } public TextCharacter(System.Text.Rune c, string guid, int x, int y, int w, int h, string imageMd5) { Character = c; this.guid = guid; this.x = x; this.y = y; this.w = w; this.h = h; ImageMD5 = imageMd5; } // 添加一个接受char的构造函数,方便兼容现有代码 public TextCharacter(char c) { Character = new System.Text.Rune(c); } } public class TextLine { public TextLine() { } public TextLine(JArray po, JObject rectange) { this.pos = po; this.selected_rectange = rectange; } public JArray pos { get; set; } = new JArray(); public JObject selected_rectange { get; set; } = new JObject(); public List Characters { get; set; } = new List(); } public class UndoAction { public string AddedText { get; set; } = string.Empty; public int AddedStartLine { get; set; } public int AddedStartColumn { get; set; } public int AddedEndLine { get; set; } public int AddedEndColumn { get; set; } public string RemovedText { get; set; } = string.Empty; public int RemovedStartLine { get; set; } public int RemovedStartColumn { get; set; } public int RemovedEndLine { get; set; } public int RemovedEndColumn { get; set; } public int CursorBeforeLine { get; set; } public int CursorBeforeColumn { get; set; } public int CursorAfterLine { get; set; } public int CursorAfterColumn { get; set; } } }