Search is not available for this dataset
id
stringlengths
1
8
text
stringlengths
72
9.81M
addition_count
int64
0
10k
commit_subject
stringlengths
0
3.7k
deletion_count
int64
0
8.43k
file_extension
stringlengths
0
32
lang
stringlengths
1
94
license
stringclasses
10 values
repo_name
stringlengths
9
59
10061950
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Use default cursor for buttons <DFF> @@ -173,7 +173,7 @@ namespace AvaloniaEdit.Demo private void AddControlButton_Click(object sender, RoutedEventArgs e) { - _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); + _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); }
1
Use default cursor for buttons
1
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10061951
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Use default cursor for buttons <DFF> @@ -173,7 +173,7 @@ namespace AvaloniaEdit.Demo private void AddControlButton_Click(object sender, RoutedEventArgs e) { - _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); + _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); }
1
Use default cursor for buttons
1
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10061952
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Use default cursor for buttons <DFF> @@ -173,7 +173,7 @@ namespace AvaloniaEdit.Demo private void AddControlButton_Click(object sender, RoutedEventArgs e) { - _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); + _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); }
1
Use default cursor for buttons
1
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10061953
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Use default cursor for buttons <DFF> @@ -173,7 +173,7 @@ namespace AvaloniaEdit.Demo private void AddControlButton_Click(object sender, RoutedEventArgs e) { - _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); + _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); }
1
Use default cursor for buttons
1
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10061954
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Use default cursor for buttons <DFF> @@ -173,7 +173,7 @@ namespace AvaloniaEdit.Demo private void AddControlButton_Click(object sender, RoutedEventArgs e) { - _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); + _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); }
1
Use default cursor for buttons
1
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10061955
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Use default cursor for buttons <DFF> @@ -173,7 +173,7 @@ namespace AvaloniaEdit.Demo private void AddControlButton_Click(object sender, RoutedEventArgs e) { - _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); + _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); }
1
Use default cursor for buttons
1
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10061956
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Use default cursor for buttons <DFF> @@ -173,7 +173,7 @@ namespace AvaloniaEdit.Demo private void AddControlButton_Click(object sender, RoutedEventArgs e) { - _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); + _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); }
1
Use default cursor for buttons
1
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10061957
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Use default cursor for buttons <DFF> @@ -173,7 +173,7 @@ namespace AvaloniaEdit.Demo private void AddControlButton_Click(object sender, RoutedEventArgs e) { - _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); + _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); }
1
Use default cursor for buttons
1
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10061958
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Use default cursor for buttons <DFF> @@ -173,7 +173,7 @@ namespace AvaloniaEdit.Demo private void AddControlButton_Click(object sender, RoutedEventArgs e) { - _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); + _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); }
1
Use default cursor for buttons
1
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10061959
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Use default cursor for buttons <DFF> @@ -173,7 +173,7 @@ namespace AvaloniaEdit.Demo private void AddControlButton_Click(object sender, RoutedEventArgs e) { - _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); + _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); }
1
Use default cursor for buttons
1
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10061960
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Use default cursor for buttons <DFF> @@ -173,7 +173,7 @@ namespace AvaloniaEdit.Demo private void AddControlButton_Click(object sender, RoutedEventArgs e) { - _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); + _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); }
1
Use default cursor for buttons
1
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10061961
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Use default cursor for buttons <DFF> @@ -173,7 +173,7 @@ namespace AvaloniaEdit.Demo private void AddControlButton_Click(object sender, RoutedEventArgs e) { - _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); + _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); }
1
Use default cursor for buttons
1
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10061962
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Use default cursor for buttons <DFF> @@ -173,7 +173,7 @@ namespace AvaloniaEdit.Demo private void AddControlButton_Click(object sender, RoutedEventArgs e) { - _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); + _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); }
1
Use default cursor for buttons
1
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10061963
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Use default cursor for buttons <DFF> @@ -173,7 +173,7 @@ namespace AvaloniaEdit.Demo private void AddControlButton_Click(object sender, RoutedEventArgs e) { - _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); + _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); }
1
Use default cursor for buttons
1
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10061964
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private CompletionWindow _completionWindow; private OverloadInsightWindow _insightWindow; private Button _addControlButton; private Button _clearControlButton; private Button _changeThemeButton; private ComboBox _syntaxModeCombo; private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _textEditor.ContextMenu = new ContextMenu { Items = new List<MenuItem> { new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }, new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }, new MenuItem { Header = "Cut", InputGesture = new KeyGesture(Key.X, KeyModifiers.Control) } } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); _textEditor.TextArea.TextView.Redraw(); } } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> Use default cursor for buttons <DFF> @@ -173,7 +173,7 @@ namespace AvaloniaEdit.Demo private void AddControlButton_Click(object sender, RoutedEventArgs e) { - _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me" })); + _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); }
1
Use default cursor for buttons
1
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10061965
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Ignore empty line copy if text is empty should not be copied, "\n" is not empty string so it will copied. <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Ignore empty line copy
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061966
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Ignore empty line copy if text is empty should not be copied, "\n" is not empty string so it will copied. <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Ignore empty line copy
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061967
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Ignore empty line copy if text is empty should not be copied, "\n" is not empty string so it will copied. <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Ignore empty line copy
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061968
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Ignore empty line copy if text is empty should not be copied, "\n" is not empty string so it will copied. <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Ignore empty line copy
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061969
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Ignore empty line copy if text is empty should not be copied, "\n" is not empty string so it will copied. <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Ignore empty line copy
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061970
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Ignore empty line copy if text is empty should not be copied, "\n" is not empty string so it will copied. <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Ignore empty line copy
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061971
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Ignore empty line copy if text is empty should not be copied, "\n" is not empty string so it will copied. <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Ignore empty line copy
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061972
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Ignore empty line copy if text is empty should not be copied, "\n" is not empty string so it will copied. <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Ignore empty line copy
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061973
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Ignore empty line copy if text is empty should not be copied, "\n" is not empty string so it will copied. <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Ignore empty line copy
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061974
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Ignore empty line copy if text is empty should not be copied, "\n" is not empty string so it will copied. <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Ignore empty line copy
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061975
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Ignore empty line copy if text is empty should not be copied, "\n" is not empty string so it will copied. <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Ignore empty line copy
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061976
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Ignore empty line copy if text is empty should not be copied, "\n" is not empty string so it will copied. <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Ignore empty line copy
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061977
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Ignore empty line copy if text is empty should not be copied, "\n" is not empty string so it will copied. <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Ignore empty line copy
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061978
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Ignore empty line copy if text is empty should not be copied, "\n" is not empty string so it will copied. <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Ignore empty line copy
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061979
<NME> EditingCommandHandler.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using Avalonia.Input; using AvaloniaEdit.Utils; using System.Threading.Tasks; namespace AvaloniaEdit.Editing { /// <summary> /// We re-use the CommandBinding and InputBinding instances between multiple text areas, /// so this class is static. /// </summary> internal class EditingCommandHandler { /// <summary> /// Creates a new <see cref="TextAreaInputHandler"/> for the text area. /// </summary> public static TextAreaInputHandler Create(TextArea textArea) { var handler = new TextAreaInputHandler(textArea); handler.CommandBindings.AddRange(CommandBindings); handler.KeyBindings.AddRange(KeyBindings); return handler; } private static readonly List<RoutedCommandBinding> CommandBindings = new List<RoutedCommandBinding>(); private static readonly List<KeyBinding> KeyBindings = new List<KeyBinding>(); private static void AddBinding(RoutedCommand command, KeyModifiers modifiers, Key key, EventHandler<ExecutedRoutedEventArgs> handler) { CommandBindings.Add(new RoutedCommandBinding(command, handler)); KeyBindings.Add(TextAreaDefaultInputHandler.CreateKeyBinding(command, modifiers, key)); } private static void AddBinding(RoutedCommand command, EventHandler<ExecutedRoutedEventArgs> handler, EventHandler<CanExecuteRoutedEventArgs> canExecuteHandler = null) { CommandBindings.Add(new RoutedCommandBinding(command, handler, canExecuteHandler)); } static EditingCommandHandler() { AddBinding(EditingCommands.Delete, KeyModifiers.None, Key.Delete, OnDelete(CaretMovementType.CharRight)); AddBinding(EditingCommands.DeleteNextWord, KeyModifiers.Control, Key.Delete, OnDelete(CaretMovementType.WordRight)); AddBinding(EditingCommands.Backspace, KeyModifiers.None, Key.Back, OnDelete(CaretMovementType.Backspace)); KeyBindings.Add( TextAreaDefaultInputHandler.CreateKeyBinding(EditingCommands.Backspace, KeyModifiers.Shift, Key.Back)); // make Shift-Backspace do the same as plain backspace AddBinding(EditingCommands.DeletePreviousWord, KeyModifiers.Control, Key.Back, OnDelete(CaretMovementType.WordLeft)); AddBinding(EditingCommands.EnterParagraphBreak, KeyModifiers.None, Key.Enter, OnEnter); AddBinding(EditingCommands.EnterLineBreak, KeyModifiers.Shift, Key.Enter, OnEnter); AddBinding(EditingCommands.TabForward, KeyModifiers.None, Key.Tab, OnTab); AddBinding(EditingCommands.TabBackward, KeyModifiers.Shift, Key.Tab, OnShiftTab); AddBinding(ApplicationCommands.Delete, OnDelete(CaretMovementType.None), CanDelete); AddBinding(ApplicationCommands.Copy, OnCopy, CanCopy); AddBinding(ApplicationCommands.Cut, OnCut, CanCut); AddBinding(ApplicationCommands.Paste, OnPaste, CanPaste); AddBinding(AvaloniaEditCommands.ToggleOverstrike, OnToggleOverstrike); AddBinding(AvaloniaEditCommands.DeleteLine, OnDeleteLine); AddBinding(AvaloniaEditCommands.RemoveLeadingWhitespace, OnRemoveLeadingWhitespace); AddBinding(AvaloniaEditCommands.RemoveTrailingWhitespace, OnRemoveTrailingWhitespace); AddBinding(AvaloniaEditCommands.ConvertToUppercase, OnConvertToUpperCase); AddBinding(AvaloniaEditCommands.ConvertToLowercase, OnConvertToLowerCase); AddBinding(AvaloniaEditCommands.ConvertToTitleCase, OnConvertToTitleCase); AddBinding(AvaloniaEditCommands.InvertCase, OnInvertCase); AddBinding(AvaloniaEditCommands.ConvertTabsToSpaces, OnConvertTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertSpacesToTabs, OnConvertSpacesToTabs); AddBinding(AvaloniaEditCommands.ConvertLeadingTabsToSpaces, OnConvertLeadingTabsToSpaces); AddBinding(AvaloniaEditCommands.ConvertLeadingSpacesToTabs, OnConvertLeadingSpacesToTabs); AddBinding(AvaloniaEditCommands.IndentSelection, OnIndentSelection); } private static TextArea GetTextArea(object target) { return target as TextArea; } #region Text Transformation Helpers private enum DefaultSegmentType { WholeDocument, CurrentLine } /// <summary> /// Calls transformLine on all lines in the selected range. /// transformLine needs to handle read-only segments! /// </summary> private static void TransformSelectedLines(Action<TextArea, DocumentLine> transformLine, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { DocumentLine start, end; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { start = end = textArea.Document.GetLineByNumber(textArea.Caret.Line); } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { start = textArea.Document.Lines.First(); end = textArea.Document.Lines.Last(); } else { start = end = null; } } else { var segment = textArea.Selection.SurroundingSegment; start = textArea.Document.GetLineByOffset(segment.Offset); end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; } if (start != null) { transformLine(textArea, start); while (start != end) { start = start.NextLine; transformLine(textArea, start); } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } /// <summary> /// Calls transformLine on all writable segment in the selected range. /// </summary> private static void TransformSelectedSegments(Action<TextArea, ISegment> transformSegment, object target, ExecutedRoutedEventArgs args, DefaultSegmentType defaultSegmentType) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { IEnumerable<ISegment> segments; if (textArea.Selection.IsEmpty) { if (defaultSegmentType == DefaultSegmentType.CurrentLine) { segments = new ISegment[] { textArea.Document.GetLineByNumber(textArea.Caret.Line) }; } else if (defaultSegmentType == DefaultSegmentType.WholeDocument) { segments = textArea.Document.Lines; } else { segments = null; } } else { segments = textArea.Selection.Segments; } if (segments != null) { foreach (var segment in segments.Reverse()) { foreach (var writableSegment in textArea.GetDeletableSegments(segment).Reverse()) { transformSegment(textArea, writableSegment); } } } } textArea.Caret.BringCaretToView(); args.Handled = true; } } #endregion #region EnterLineBreak private static void OnEnter(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.IsFocused) { textArea.PerformTextInput("\n"); args.Handled = true; } } #endregion #region Tab private static void OnTab(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { using (textArea.Document.RunUpdate()) { if (textArea.Selection.IsMultiline) { var segment = textArea.Selection.SurroundingSegment; var start = textArea.Document.GetLineByOffset(segment.Offset); var end = textArea.Document.GetLineByOffset(segment.EndOffset); // don't include the last line if no characters on it are selected if (start != end && end.Offset == segment.EndOffset) end = end.PreviousLine; var current = start; while (true) { var offset = current.Offset; if (textArea.ReadOnlySectionProvider.CanInsert(offset)) textArea.Document.Replace(offset, 0, textArea.Options.IndentationString, OffsetChangeMappingType.KeepAnchorBeforeInsertion); if (current == end) break; current = current.NextLine; } } else { var indentationString = textArea.Options.GetIndentationString(textArea.Caret.Column); textArea.ReplaceSelectionWithText(indentationString); } } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static void OnShiftTab(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { var offset = line.Offset; var s = TextUtilities.GetSingleIndentationSegment(textArea.Document, offset, textArea.Options.IndentationSize); if (s.Length > 0) { s = textArea.GetDeletableSegments(s).FirstOrDefault(); if (s != null && s.Length > 0) { textArea.Document.Remove(s.Offset, s.Length); } } }, target, args, DefaultSegmentType.CurrentLine); } #endregion #region Delete private static EventHandler<ExecutedRoutedEventArgs> OnDelete(CaretMovementType caretMovement) { return (target, args) => { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty) { var startPos = textArea.Caret.Position; var enableVirtualSpace = textArea.Options.EnableVirtualSpace; // When pressing delete; don't move the caret further into virtual space - instead delete the newline if (caretMovement == CaretMovementType.CharRight) enableVirtualSpace = false; var desiredXPos = textArea.Caret.DesiredXPos; var endPos = CaretNavigationCommandHandler.GetNewCaretPosition( textArea.TextView, startPos, caretMovement, enableVirtualSpace, ref desiredXPos); // GetNewCaretPosition may return (0,0) as new position, // thus we need to validate endPos before using it in the selection. if (endPos.Line < 1 || endPos.Column < 1) endPos = new TextViewPosition(Math.Max(endPos.Line, 1), Math.Max(endPos.Column, 1)); // Don't do anything if the number of lines of a rectangular selection would be changed by the deletion. if (textArea.Selection is RectangleSelection && startPos.Line != endPos.Line) return; // Don't select the text to be deleted; just reuse the ReplaceSelectionWithText logic // Reuse the existing selection, so that we continue using the same logic textArea.Selection.StartSelectionOrSetEndpoint(startPos, endPos) .ReplaceSelectionWithText(string.Empty); } else { textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } }; } private static void CanDelete(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = true; args.Handled = true; } } #endregion #region Clipboard commands private static void CanCut(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = (textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty) && !textArea.IsReadOnly; args.Handled = true; } } private static void CanCopy(object target, CanExecuteRoutedEventArgs args) { // HasSomethingSelected for copy and cut commands var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.Options.CutCopyWholeLine || !textArea.Selection.IsEmpty; args.Handled = true; } } private static void OnCopy(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); CopyWholeLine(textArea, currentLine); } else { CopySelectedText(textArea); } args.Handled = true; } } private static void OnCut(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { if (textArea.Selection.IsEmpty && textArea.Options.CutCopyWholeLine) { var currentLine = textArea.Document.GetLineByNumber(textArea.Caret.Line); if (CopyWholeLine(textArea, currentLine)) { var segmentsToDelete = textArea.GetDeletableSegments( new SimpleSegment(currentLine.Offset, currentLine.TotalLength)); for (var i = segmentsToDelete.Length - 1; i >= 0; i--) { textArea.Document.Remove(segmentsToDelete[i]); } } } else { if (CopySelectedText(textArea)) textArea.RemoveSelectedText(); } textArea.Caret.BringCaretToView(); args.Handled = true; } } private static bool CopySelectedText(TextArea textArea) { var text = textArea.Selection.GetText(); text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void SetClipboardText(string text) { { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); } } private static bool CopyWholeLine(TextArea textArea, DocumentLine line) { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); // Ignore empty line copy if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); // TODO: formats //DataObject data = new DataObject(); //if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText)) // data.SetText(text); //// Also copy text in HTML format to clipboard - good for pasting text into Word //// or to the SharpDevelop forums. //if (ConfirmDataFormat(textArea, data, DataFormats.Html)) //{ // IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter; // HtmlClipboard.SetHtml(data, // HtmlClipboard.CreateHtmlFragment(textArea.Document, highlighter, wholeLine, // new HtmlOptions(textArea.Options))); //} //if (ConfirmDataFormat(textArea, data, LineSelectedType)) //{ // var lineSelected = new MemoryStream(1); // lineSelected.WriteByte(1); // data.SetData(LineSelectedType, lineSelected, false); //} //var copyingEventArgs = new DataObjectCopyingEventArgs(data, false); //textArea.RaiseEvent(copyingEventArgs); //if (copyingEventArgs.CommandCancelled) // return false; SetClipboardText(text); textArea.OnTextCopied(new TextEventArgs(text)); return true; } private static void CanPaste(object target, CanExecuteRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { args.CanExecute = textArea.ReadOnlySectionProvider.CanInsert(textArea.Caret.Offset); args.Handled = true; } } private static async void OnPaste(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { textArea.Document.BeginUpdate(); string text = null; try { text = await Application.Current.Clipboard.GetTextAsync(); } catch (Exception) { textArea.Document.EndUpdate(); return; } if (text == null) return; text = GetTextToPaste(text, textArea); if (!string.IsNullOrEmpty(text)) { textArea.ReplaceSelectionWithText(text); } textArea.Caret.BringCaretToView(); args.Handled = true; textArea.Document.EndUpdate(); } } internal static string GetTextToPaste(string text, TextArea textArea) { try { // Try retrieving the text as one of: // - the FormatToApply // - UnicodeText // - Text // (but don't try the same format twice) //if (pastingEventArgs.FormatToApply != null && dataObject.GetDataPresent(pastingEventArgs.FormatToApply)) // text = (string)dataObject.GetData(pastingEventArgs.FormatToApply); //else if (pastingEventArgs.FormatToApply != DataFormats.UnicodeText && // dataObject.GetDataPresent(DataFormats.UnicodeText)) // text = (string)dataObject.GetData(DataFormats.UnicodeText); //else if (pastingEventArgs.FormatToApply != DataFormats.Text && // dataObject.GetDataPresent(DataFormats.Text)) // text = (string)dataObject.GetData(DataFormats.Text); //else // return null; // no text data format // convert text back to correct newlines for this document var newLine = TextUtilities.GetNewLineFromDocument(textArea.Document, textArea.Caret.Line); text = TextUtilities.NormalizeNewLines(text, newLine); text = textArea.Options.ConvertTabsToSpaces ? text.Replace("\t", new String(' ', textArea.Options.IndentationSize)) : text; return text; } catch (OutOfMemoryException) { // may happen when trying to paste a huge string return null; } } #endregion #region Toggle Overstrike private static void OnToggleOverstrike(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea != null && textArea.Options.AllowToggleOverstrikeMode) textArea.OverstrikeMode = !textArea.OverstrikeMode; } #endregion #region DeleteLine private static void OnDeleteLine(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null) { int firstLineIndex, lastLineIndex; if (textArea.Selection.Length == 0) { // There is no selection, simply delete current line firstLineIndex = lastLineIndex = textArea.Caret.Line; } else { // There is a selection, remove all lines affected by it (use Min/Max to be independent from selection direction) firstLineIndex = Math.Min(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); lastLineIndex = Math.Max(textArea.Selection.StartPosition.Line, textArea.Selection.EndPosition.Line); } var startLine = textArea.Document.GetLineByNumber(firstLineIndex); var endLine = textArea.Document.GetLineByNumber(lastLineIndex); textArea.Selection = Selection.Create(textArea, startLine.Offset, endLine.Offset + endLine.TotalLength); textArea.RemoveSelectedText(); args.Handled = true; } } #endregion #region Remove..Whitespace / Convert Tabs-Spaces private static void OnRemoveLeadingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnRemoveTrailingWhitespace(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { textArea.Document.Remove(TextUtilities.GetTrailingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertTabsToSpaces, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingTabsToSpaces(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertTabsToSpaces(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertTabsToSpaces(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationString = new string(' ', textArea.Options.IndentationSize); for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == '\t') { document.Replace(offset, 1, indentationString, OffsetChangeMappingType.CharacterReplace); endOffset += indentationString.Length - 1; } } } private static void OnConvertSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments(ConvertSpacesToTabs, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertLeadingSpacesToTabs(object target, ExecutedRoutedEventArgs args) { TransformSelectedLines( delegate (TextArea textArea, DocumentLine line) { ConvertSpacesToTabs(textArea, TextUtilities.GetLeadingWhitespace(textArea.Document, line)); }, target, args, DefaultSegmentType.WholeDocument); } private static void ConvertSpacesToTabs(TextArea textArea, ISegment segment) { var document = textArea.Document; var endOffset = segment.EndOffset; var indentationSize = textArea.Options.IndentationSize; var spacesCount = 0; for (var offset = segment.Offset; offset < endOffset; offset++) { if (document.GetCharAt(offset) == ' ') { spacesCount++; if (spacesCount == indentationSize) { document.Replace(offset - (indentationSize - 1), indentationSize, "\t", OffsetChangeMappingType.CharacterReplace); spacesCount = 0; offset -= indentationSize - 1; endOffset -= indentationSize - 1; } } else { spacesCount = 0; } } } #endregion #region Convert...Case private static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args) { TransformSelectedSegments( delegate (TextArea textArea, ISegment segment) { var oldText = textArea.Document.GetText(segment); var newText = transformText(oldText); textArea.Document.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace); }, target, args, DefaultSegmentType.WholeDocument); } private static void OnConvertToUpperCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToUpper, target, args); } private static void OnConvertToLowerCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToLower, target, args); } private static void OnConvertToTitleCase(object target, ExecutedRoutedEventArgs args) { throw new NotSupportedException(); //ConvertCase(CultureInfo.CurrentCulture.TextInfo.ToTitleCase, target, args); } private static void OnInvertCase(object target, ExecutedRoutedEventArgs args) { ConvertCase(InvertCase, target, args); } private static string InvertCase(string text) { // TODO: culture //var culture = CultureInfo.CurrentCulture; var buffer = text.ToCharArray(); for (var i = 0; i < buffer.Length; ++i) { var c = buffer[i]; buffer[i] = char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c); } return new string(buffer); } #endregion private static void OnIndentSelection(object target, ExecutedRoutedEventArgs args) { var textArea = GetTextArea(target); if (textArea?.Document != null && textArea.IndentationStrategy != null) { using (textArea.Document.RunUpdate()) { int start, end; if (textArea.Selection.IsEmpty) { start = 1; end = textArea.Document.LineCount; } } } } .LineNumber; end = textArea.Document.GetLineByOffset(textArea.Selection.SurroundingSegment.EndOffset) .LineNumber; } textArea.IndentationStrategy.IndentLines(textArea.Document, start, end); } textArea.Caret.BringCaretToView(); args.Handled = true; } } } } <MSG> Ignore empty line copy if text is empty should not be copied, "\n" is not empty string so it will copied. <DFF> @@ -427,6 +427,8 @@ namespace AvaloniaEdit.Editing { ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength); var text = textArea.Document.GetText(wholeLine); + // Ignore empty line copy + if(string.IsNullOrEmpty(text)) return false; // Ensure we use the appropriate newline sequence for the OS text = TextUtilities.NormalizeNewLines(text, Environment.NewLine); @@ -757,4 +759,4 @@ namespace AvaloniaEdit.Editing } } } -} \ No newline at end of file +}
3
Ignore empty line copy
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061980
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform; using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Remove unused imports <DFF> @@ -29,13 +29,9 @@ using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; -using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Platform; -using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion {
0
Remove unused imports
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061981
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform; using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Remove unused imports <DFF> @@ -29,13 +29,9 @@ using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; -using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Platform; -using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion {
0
Remove unused imports
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061982
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform; using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Remove unused imports <DFF> @@ -29,13 +29,9 @@ using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; -using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Platform; -using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion {
0
Remove unused imports
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061983
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform; using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Remove unused imports <DFF> @@ -29,13 +29,9 @@ using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; -using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Platform; -using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion {
0
Remove unused imports
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061984
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform; using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Remove unused imports <DFF> @@ -29,13 +29,9 @@ using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; -using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Platform; -using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion {
0
Remove unused imports
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061985
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform; using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Remove unused imports <DFF> @@ -29,13 +29,9 @@ using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; -using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Platform; -using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion {
0
Remove unused imports
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061986
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform; using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Remove unused imports <DFF> @@ -29,13 +29,9 @@ using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; -using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Platform; -using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion {
0
Remove unused imports
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061987
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform; using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Remove unused imports <DFF> @@ -29,13 +29,9 @@ using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; -using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Platform; -using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion {
0
Remove unused imports
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061988
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform; using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Remove unused imports <DFF> @@ -29,13 +29,9 @@ using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; -using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Platform; -using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion {
0
Remove unused imports
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061989
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform; using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Remove unused imports <DFF> @@ -29,13 +29,9 @@ using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; -using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Platform; -using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion {
0
Remove unused imports
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061990
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform; using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Remove unused imports <DFF> @@ -29,13 +29,9 @@ using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; -using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Platform; -using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion {
0
Remove unused imports
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061991
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform; using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Remove unused imports <DFF> @@ -29,13 +29,9 @@ using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; -using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Platform; -using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion {
0
Remove unused imports
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061992
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform; using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Remove unused imports <DFF> @@ -29,13 +29,9 @@ using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; -using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Platform; -using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion {
0
Remove unused imports
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061993
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform; using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Remove unused imports <DFF> @@ -29,13 +29,9 @@ using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; -using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Platform; -using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion {
0
Remove unused imports
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061994
<NME> CompletionWindowBase.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Platform; using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion { /// <summary> /// Base class for completion windows. Handles positioning the window at the caret. /// </summary> public class CompletionWindowBase : Popup, IStyleable { static CompletionWindowBase() { //BackgroundProperty.OverrideDefaultValue(typeof(CompletionWindowBase), Brushes.White); } Type IStyleable.StyleKey => typeof(PopupRoot); /// <summary> /// Gets the parent TextArea. /// </summary> public TextArea TextArea { get; } private readonly Window _parentWindow; private TextDocument _document; /// <summary> /// Gets/Sets the start of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int StartOffset { get; set; } /// <summary> /// Gets/Sets the end of the text range in which the completion window stays open. /// This text portion is used to determine the text used to select an entry in the completion list by typing. /// </summary> public int EndOffset { get; set; } /// <summary> /// Gets whether the window was opened above the current line. /// </summary> protected bool IsUp { get; private set; } /// <summary> /// Creates a new CompletionWindowBase. /// </summary> public CompletionWindowBase(TextArea textArea) : base() { TextArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); _parentWindow = textArea.GetVisualRoot() as Window; AddHandler(PointerReleasedEvent, OnMouseUp, handledEventsToo: true); StartOffset = EndOffset = TextArea.Caret.Offset; PlacementTarget = TextArea.TextView; PlacementMode = PlacementMode.AnchorAndGravity; PlacementAnchor = Avalonia.Controls.Primitives.PopupPositioning.PopupAnchor.TopLeft; PlacementGravity = Avalonia.Controls.Primitives.PopupPositioning.PopupGravity.BottomRight; //Deactivated += OnDeactivated; //Not needed? Closed += (sender, args) => DetachEvents(); AttachEvents(); Initailize(); } protected virtual void OnClosed() { DetachEvents(); } private void Initailize() { if (_document != null && StartOffset != TextArea.Caret.Offset) { SetPosition(new TextViewPosition(_document.GetLocation(StartOffset))); } else { SetPosition(TextArea.Caret.Position); } } public void Show() { UpdatePosition(); Open(); Height = double.NaN; MinHeight = 0; } public void Hide() { Close(); OnClosed(); } #region Event Handlers private void AttachEvents() { ((ISetLogicalParent)this).SetParent(TextArea.GetVisualRoot() as ILogical); _document = TextArea.Document; if (_document != null) { _document.Changing += TextArea_Document_Changing; } // LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729 TextArea.LostFocus += TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged; TextArea.DocumentChanged += TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged += ParentWindow_LocationChanged; _parentWindow.Deactivated += ParentWindow_Deactivated; } // close previous completion windows of same type foreach (var x in TextArea.StackedInputHandlers.OfType<InputHandler>()) { if (x.Window.GetType() == GetType()) TextArea.PopStackedInputHandler(x); } _myInputHandler = new InputHandler(this); TextArea.PushStackedInputHandler(_myInputHandler); } /// <summary> /// Detaches events from the text area. /// </summary> protected virtual void DetachEvents() { ((ISetLogicalParent)this).SetParent(null); if (_document != null) { _document.Changing -= TextArea_Document_Changing; } TextArea.LostFocus -= TextAreaLostFocus; TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged; TextArea.DocumentChanged -= TextAreaDocumentChanged; if (_parentWindow != null) { _parentWindow.PositionChanged -= ParentWindow_LocationChanged; _parentWindow.Deactivated -= ParentWindow_Deactivated; } TextArea.PopStackedInputHandler(_myInputHandler); } #region InputHandler private InputHandler _myInputHandler; /// <summary> /// A dummy input handler (that justs invokes the default input handler). /// This is used to ensure the completion window closes when any other input handler /// becomes active. /// </summary> private sealed class InputHandler : TextAreaStackedInputHandler { internal readonly CompletionWindowBase Window; public InputHandler(CompletionWindowBase window) : base(window.TextArea) { Debug.Assert(window != null); Window = window; } public override void Detach() { base.Detach(); Window.Hide(); } public override void OnPreviewKeyDown(KeyEventArgs e) { // prevents crash when typing deadchar while CC window is open if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyDownEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } public override void OnPreviewKeyUp(KeyEventArgs e) { if (e.Key == Key.DeadCharProcessed) return; e.Handled = RaiseEventPair(Window, null, KeyUpEvent, new KeyEventArgs { Device = e.Device, Key = e.Key }); } } #endregion private void TextViewScrollOffsetChanged(object sender, EventArgs e) { ILogicalScrollable textView = TextArea; var visibleRect = new Rect(textView.Offset.X, textView.Offset.Y, textView.Viewport.Width, textView.Viewport.Height); //close completion window when the user scrolls so far that the anchor position is leaving the visible area if (visibleRect.Contains(_visualLocation) || visibleRect.Contains(_visualLocationTop)) { UpdatePosition(); } else { Hide(); } } private void TextAreaDocumentChanged(object sender, EventArgs e) { Hide(); } private void TextAreaLostFocus(object sender, RoutedEventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } private void ParentWindow_Deactivated(object sender, EventArgs e) { Hide(); } private void ParentWindow_LocationChanged(object sender, EventArgs e) { UpdatePosition(); } /// <inheritdoc/> private void OnDeactivated(object sender, EventArgs e) { Dispatcher.UIThread.Post(CloseIfFocusLost, DispatcherPriority.Background); } #endregion /// <summary> /// Raises a tunnel/bubble event pair for a control. /// </summary> /// <param name="target">The control for which the event should be raised.</param> /// <param name="previewEvent">The tunneling event.</param> /// <param name="event">The bubbling event.</param> /// <param name="args">The event args to use.</param> /// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] protected static bool RaiseEventPair(Control target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args) { if (target == null) throw new ArgumentNullException(nameof(target)); if (args == null) throw new ArgumentNullException(nameof(args)); if (previewEvent != null) { args.RoutedEvent = previewEvent; target.RaiseEvent(args); } args.RoutedEvent = @event ?? throw new ArgumentNullException(nameof(@event)); target.RaiseEvent(args); return args.Handled; } // Special handler: handledEventsToo private void OnMouseUp(object sender, PointerReleasedEventArgs e) { ActivateParentWindow(); } /// <summary> /// Activates the parent window. /// </summary> protected virtual void ActivateParentWindow() { _parentWindow?.Activate(); } private void CloseIfFocusLost() { if (CloseOnFocusLost) { Debug.WriteLine("CloseIfFocusLost: this.IsFocues=" + IsFocused + " IsTextAreaFocused=" + IsTextAreaFocused); if (!IsFocused && !IsTextAreaFocused) { Hide(); } } } /// <summary> /// Gets whether the completion window should automatically close when the text editor looses focus. /// </summary> protected virtual bool CloseOnFocusLost => true; private bool IsTextAreaFocused { get { if (_parentWindow != null && !_parentWindow.IsActive) return false; return TextArea.IsFocused; } } /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (!e.Handled && e.Key == Key.Escape) { e.Handled = true; Hide(); } } private Point _visualLocation; private Point _visualLocationTop; /// <summary> /// Positions the completion window at the specified position. /// </summary> protected void SetPosition(TextViewPosition position) { var textView = TextArea.TextView; _visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom); _visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop); UpdatePosition(); } /// <summary> /// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area. /// It ensures that the CompletionWindow is completely visible on the screen. /// </summary> protected void UpdatePosition() { var textView = TextArea.TextView; var position = _visualLocation - textView.ScrollOffset; this.HorizontalOffset = position.X; this.VerticalOffset = position.Y; } // TODO: check if needed ///// <inheritdoc/> //protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) //{ // base.OnRenderSizeChanged(sizeInfo); // if (sizeInfo.HeightChanged && IsUp) // { // this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height; // } //} /// <summary> /// Gets/sets whether the completion window should expect text insertion at the start offset, /// which not go into the completion region, but before it. /// </summary> /// <remarks>This property allows only a single insertion, it is reset to false /// when that insertion has occurred.</remarks> public bool ExpectInsertionBeforeStart { get; set; } private void TextArea_Document_Changing(object sender, DocumentChangeEventArgs e) { if (e.Offset + e.RemovalLength == StartOffset && e.RemovalLength > 0) { Hide(); // removal immediately in front of completion segment: close the window // this is necessary when pressing backspace after dot-completion } if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion); ExpectInsertionBeforeStart = false; } else { StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion); } EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion); } } } <MSG> Remove unused imports <DFF> @@ -29,13 +29,9 @@ using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; -using Avalonia.Media; using Avalonia.Styling; using Avalonia.Threading; using Avalonia.VisualTree; -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Platform; -using Avalonia.Controls.Platform; namespace AvaloniaEdit.CodeCompletion {
0
Remove unused imports
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061995
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: Add .jsgrid-cell and .jsgrid-header-cell classes to simplify styling <DFF> @@ -555,6 +555,7 @@ $(function() { equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); + equal(grid._filterRow.find("." + this.gridClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); @@ -924,12 +925,14 @@ $(function() { grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); + equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2",
5
Core: Add .jsgrid-cell and .jsgrid-header-cell classes to simplify styling
0
.js
tests
mit
tabalinas/jsgrid
10061996
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: Add .jsgrid-cell and .jsgrid-header-cell classes to simplify styling <DFF> @@ -555,6 +555,7 @@ $(function() { equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); + equal(grid._filterRow.find("." + this.gridClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); @@ -924,12 +925,14 @@ $(function() { grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); + equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2",
5
Core: Add .jsgrid-cell and .jsgrid-header-cell classes to simplify styling
0
.js
tests
mit
tabalinas/jsgrid
10061997
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent { #region Constructor static TextView() Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); } MeasureInlineObjects(); InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(_scrollViewport); } finally { VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); TextLayer.SetVisualLines(_visibleVisualLines); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); if (_visibleVisualLines != null) { } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if(!VisualLinesValid) { return; } builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } private void ClearScrollData() { SetScrollData(new Size(), new Size()); _scrollOffset = new Vector(); } public bool SetScrollData(Size viewport, Size extent) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent))) { _scrollViewport = viewport; _scrollExtent = extent; return true; } return false; } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; /// <summary> /// Gets the horizontal scroll offset. private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; /// </summary> public event EventHandler ScrollOffsetChanged; internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); if (!_canVerticallyScroll) vector = new Vector(vector.X, 0); if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); InvalidateMeasure(); } } CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); InvalidateMeasure(DispatcherPriority.Normal); } } Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); return pen; } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; } } <MSG> Fix horizontal scroll <DFF> @@ -32,6 +32,7 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; @@ -48,7 +49,7 @@ namespace AvaloniaEdit.Rendering /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] - public class TextView : Control, ITextEditorComponent + public class TextView : Control, ITextEditorComponent, ILogicalScrollable { #region Constructor static TextView() @@ -724,7 +725,7 @@ namespace AvaloniaEdit.Rendering { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } - + visualLine.Dispose(); RemoveInlineObjects(visualLine); } @@ -919,7 +920,8 @@ namespace AvaloniaEdit.Rendering } MeasureInlineObjects(); - InvalidateVisual(); // = InvalidateArrange+InvalidateRender + // TODO: is this needed? + //InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) @@ -934,7 +936,7 @@ namespace AvaloniaEdit.Rendering _inMeasure = true; try { - maxWidth = CreateAndMeasureVisualLines(_scrollViewport); + maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { @@ -964,6 +966,10 @@ namespace AvaloniaEdit.Rendering TextLayer.SetVisualLines(_visibleVisualLines); + SetScrollData(availableSize, + new Size(maxWidth, heightTreeHeight), + _scrollOffset); + VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); @@ -1076,7 +1082,7 @@ namespace AvaloniaEdit.Rendering { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); - + var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { @@ -1201,7 +1207,10 @@ namespace AvaloniaEdit.Rendering newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } - // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); + if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) + { + InvalidateMeasure(DispatcherPriority.Normal); + } if (_visibleVisualLines != null) { @@ -1226,6 +1235,7 @@ namespace AvaloniaEdit.Rendering } } } + InvalidateCursorIfPointerWithinTextView(); return finalSize; @@ -1256,7 +1266,7 @@ namespace AvaloniaEdit.Rendering /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - if(!VisualLinesValid) + if (!VisualLinesValid) { return; } @@ -1358,25 +1368,33 @@ namespace AvaloniaEdit.Rendering private void ClearScrollData() { - SetScrollData(new Size(), new Size()); - _scrollOffset = new Vector(); + SetScrollData(new Size(), new Size(), new Vector()); } - public bool SetScrollData(Size viewport, Size extent) + private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) - && extent.IsClose(_scrollExtent))) + && extent.IsClose(_scrollExtent) + && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; + SetScrollOffset(offset); + OnScrollChange(); return true; } + return false; } + private void OnScrollChange() + { + ((ILogicalScrollable)this).InvalidateScroll?.Invoke(); + } + private bool _canVerticallyScroll = true; - private bool _canHorizontallyScroll; + private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. @@ -1398,19 +1416,22 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - internal void SetScrollOffset(Vector vector) + private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) + { vector = new Vector(0, vector.Y); + } + if (!_canVerticallyScroll) + { vector = new Vector(vector.X, 0); + } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); - - InvalidateMeasure(); } } @@ -1555,6 +1576,7 @@ namespace AvaloniaEdit.Rendering if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); + OnScrollChange(); InvalidateMeasure(DispatcherPriority.Normal); } } @@ -1665,7 +1687,7 @@ namespace AvaloniaEdit.Rendering if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); - + foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) @@ -1946,6 +1968,28 @@ namespace AvaloniaEdit.Rendering return pen; } + bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) + { + if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) + { + return false; + } + + // TODO: + // Convert rectangle into our coordinate space. + //var childTransform = target.TransformToVisual(this); + //rectangle = childTransform.Value(rectangle); + + MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); + + return true; + } + + IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) + { + return null; + } + /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> @@ -1999,5 +2043,71 @@ namespace AvaloniaEdit.Rendering /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; + + bool ILogicalScrollable.CanHorizontallyScroll + { + get => _canHorizontallyScroll; + set + { + if (_canHorizontallyScroll != value) + { + _canHorizontallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.CanVerticallyScroll + { + get => _canVerticallyScroll; + set + { + if (_canVerticallyScroll != value) + { + _canVerticallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.IsLogicalScrollEnabled => true; + + Action ILogicalScrollable.InvalidateScroll { get; set; } + + Size ILogicalScrollable.ScrollSize => new Size(10, 10); + + Size ILogicalScrollable.PageScrollSize => new Size(10, 10); + + Size IScrollable.Extent => _scrollExtent; + + Vector IScrollable.Offset + { + get => _scrollOffset; + set + { + value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); + var isX = !_scrollOffset.X.IsClose(value.X); + var isY = !_scrollOffset.Y.IsClose(value.Y); + if (isX || isY) + { + SetScrollOffset(value); + + if (isX) + { + InvalidateVisual(); + TextLayer.InvalidateVisual(); + } + + if (isY) + { + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + } + + Size IScrollable.Viewport => _scrollViewport; } }
126
Fix horizontal scroll
16
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061998
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent { #region Constructor static TextView() Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); } MeasureInlineObjects(); InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(_scrollViewport); } finally { VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); TextLayer.SetVisualLines(_visibleVisualLines); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); if (_visibleVisualLines != null) { } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if(!VisualLinesValid) { return; } builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } private void ClearScrollData() { SetScrollData(new Size(), new Size()); _scrollOffset = new Vector(); } public bool SetScrollData(Size viewport, Size extent) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent))) { _scrollViewport = viewport; _scrollExtent = extent; return true; } return false; } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; /// <summary> /// Gets the horizontal scroll offset. private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; /// </summary> public event EventHandler ScrollOffsetChanged; internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); if (!_canVerticallyScroll) vector = new Vector(vector.X, 0); if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); InvalidateMeasure(); } } CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); InvalidateMeasure(DispatcherPriority.Normal); } } Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); return pen; } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; } } <MSG> Fix horizontal scroll <DFF> @@ -32,6 +32,7 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; @@ -48,7 +49,7 @@ namespace AvaloniaEdit.Rendering /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] - public class TextView : Control, ITextEditorComponent + public class TextView : Control, ITextEditorComponent, ILogicalScrollable { #region Constructor static TextView() @@ -724,7 +725,7 @@ namespace AvaloniaEdit.Rendering { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } - + visualLine.Dispose(); RemoveInlineObjects(visualLine); } @@ -919,7 +920,8 @@ namespace AvaloniaEdit.Rendering } MeasureInlineObjects(); - InvalidateVisual(); // = InvalidateArrange+InvalidateRender + // TODO: is this needed? + //InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) @@ -934,7 +936,7 @@ namespace AvaloniaEdit.Rendering _inMeasure = true; try { - maxWidth = CreateAndMeasureVisualLines(_scrollViewport); + maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { @@ -964,6 +966,10 @@ namespace AvaloniaEdit.Rendering TextLayer.SetVisualLines(_visibleVisualLines); + SetScrollData(availableSize, + new Size(maxWidth, heightTreeHeight), + _scrollOffset); + VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); @@ -1076,7 +1082,7 @@ namespace AvaloniaEdit.Rendering { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); - + var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { @@ -1201,7 +1207,10 @@ namespace AvaloniaEdit.Rendering newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } - // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); + if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) + { + InvalidateMeasure(DispatcherPriority.Normal); + } if (_visibleVisualLines != null) { @@ -1226,6 +1235,7 @@ namespace AvaloniaEdit.Rendering } } } + InvalidateCursorIfPointerWithinTextView(); return finalSize; @@ -1256,7 +1266,7 @@ namespace AvaloniaEdit.Rendering /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - if(!VisualLinesValid) + if (!VisualLinesValid) { return; } @@ -1358,25 +1368,33 @@ namespace AvaloniaEdit.Rendering private void ClearScrollData() { - SetScrollData(new Size(), new Size()); - _scrollOffset = new Vector(); + SetScrollData(new Size(), new Size(), new Vector()); } - public bool SetScrollData(Size viewport, Size extent) + private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) - && extent.IsClose(_scrollExtent))) + && extent.IsClose(_scrollExtent) + && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; + SetScrollOffset(offset); + OnScrollChange(); return true; } + return false; } + private void OnScrollChange() + { + ((ILogicalScrollable)this).InvalidateScroll?.Invoke(); + } + private bool _canVerticallyScroll = true; - private bool _canHorizontallyScroll; + private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. @@ -1398,19 +1416,22 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - internal void SetScrollOffset(Vector vector) + private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) + { vector = new Vector(0, vector.Y); + } + if (!_canVerticallyScroll) + { vector = new Vector(vector.X, 0); + } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); - - InvalidateMeasure(); } } @@ -1555,6 +1576,7 @@ namespace AvaloniaEdit.Rendering if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); + OnScrollChange(); InvalidateMeasure(DispatcherPriority.Normal); } } @@ -1665,7 +1687,7 @@ namespace AvaloniaEdit.Rendering if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); - + foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) @@ -1946,6 +1968,28 @@ namespace AvaloniaEdit.Rendering return pen; } + bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) + { + if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) + { + return false; + } + + // TODO: + // Convert rectangle into our coordinate space. + //var childTransform = target.TransformToVisual(this); + //rectangle = childTransform.Value(rectangle); + + MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); + + return true; + } + + IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) + { + return null; + } + /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> @@ -1999,5 +2043,71 @@ namespace AvaloniaEdit.Rendering /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; + + bool ILogicalScrollable.CanHorizontallyScroll + { + get => _canHorizontallyScroll; + set + { + if (_canHorizontallyScroll != value) + { + _canHorizontallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.CanVerticallyScroll + { + get => _canVerticallyScroll; + set + { + if (_canVerticallyScroll != value) + { + _canVerticallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.IsLogicalScrollEnabled => true; + + Action ILogicalScrollable.InvalidateScroll { get; set; } + + Size ILogicalScrollable.ScrollSize => new Size(10, 10); + + Size ILogicalScrollable.PageScrollSize => new Size(10, 10); + + Size IScrollable.Extent => _scrollExtent; + + Vector IScrollable.Offset + { + get => _scrollOffset; + set + { + value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); + var isX = !_scrollOffset.X.IsClose(value.X); + var isY = !_scrollOffset.Y.IsClose(value.Y); + if (isX || isY) + { + SetScrollOffset(value); + + if (isX) + { + InvalidateVisual(); + TextLayer.InvalidateVisual(); + } + + if (isY) + { + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + } + + Size IScrollable.Viewport => _scrollViewport; } }
126
Fix horizontal scroll
16
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10061999
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent { #region Constructor static TextView() Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); } MeasureInlineObjects(); InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(_scrollViewport); } finally { VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); TextLayer.SetVisualLines(_visibleVisualLines); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); if (_visibleVisualLines != null) { } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if(!VisualLinesValid) { return; } builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } private void ClearScrollData() { SetScrollData(new Size(), new Size()); _scrollOffset = new Vector(); } public bool SetScrollData(Size viewport, Size extent) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent))) { _scrollViewport = viewport; _scrollExtent = extent; return true; } return false; } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; /// <summary> /// Gets the horizontal scroll offset. private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; /// </summary> public event EventHandler ScrollOffsetChanged; internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); if (!_canVerticallyScroll) vector = new Vector(vector.X, 0); if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); InvalidateMeasure(); } } CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); InvalidateMeasure(DispatcherPriority.Normal); } } Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); return pen; } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; } } <MSG> Fix horizontal scroll <DFF> @@ -32,6 +32,7 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; @@ -48,7 +49,7 @@ namespace AvaloniaEdit.Rendering /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] - public class TextView : Control, ITextEditorComponent + public class TextView : Control, ITextEditorComponent, ILogicalScrollable { #region Constructor static TextView() @@ -724,7 +725,7 @@ namespace AvaloniaEdit.Rendering { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } - + visualLine.Dispose(); RemoveInlineObjects(visualLine); } @@ -919,7 +920,8 @@ namespace AvaloniaEdit.Rendering } MeasureInlineObjects(); - InvalidateVisual(); // = InvalidateArrange+InvalidateRender + // TODO: is this needed? + //InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) @@ -934,7 +936,7 @@ namespace AvaloniaEdit.Rendering _inMeasure = true; try { - maxWidth = CreateAndMeasureVisualLines(_scrollViewport); + maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { @@ -964,6 +966,10 @@ namespace AvaloniaEdit.Rendering TextLayer.SetVisualLines(_visibleVisualLines); + SetScrollData(availableSize, + new Size(maxWidth, heightTreeHeight), + _scrollOffset); + VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); @@ -1076,7 +1082,7 @@ namespace AvaloniaEdit.Rendering { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); - + var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { @@ -1201,7 +1207,10 @@ namespace AvaloniaEdit.Rendering newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } - // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); + if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) + { + InvalidateMeasure(DispatcherPriority.Normal); + } if (_visibleVisualLines != null) { @@ -1226,6 +1235,7 @@ namespace AvaloniaEdit.Rendering } } } + InvalidateCursorIfPointerWithinTextView(); return finalSize; @@ -1256,7 +1266,7 @@ namespace AvaloniaEdit.Rendering /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - if(!VisualLinesValid) + if (!VisualLinesValid) { return; } @@ -1358,25 +1368,33 @@ namespace AvaloniaEdit.Rendering private void ClearScrollData() { - SetScrollData(new Size(), new Size()); - _scrollOffset = new Vector(); + SetScrollData(new Size(), new Size(), new Vector()); } - public bool SetScrollData(Size viewport, Size extent) + private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) - && extent.IsClose(_scrollExtent))) + && extent.IsClose(_scrollExtent) + && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; + SetScrollOffset(offset); + OnScrollChange(); return true; } + return false; } + private void OnScrollChange() + { + ((ILogicalScrollable)this).InvalidateScroll?.Invoke(); + } + private bool _canVerticallyScroll = true; - private bool _canHorizontallyScroll; + private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. @@ -1398,19 +1416,22 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - internal void SetScrollOffset(Vector vector) + private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) + { vector = new Vector(0, vector.Y); + } + if (!_canVerticallyScroll) + { vector = new Vector(vector.X, 0); + } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); - - InvalidateMeasure(); } } @@ -1555,6 +1576,7 @@ namespace AvaloniaEdit.Rendering if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); + OnScrollChange(); InvalidateMeasure(DispatcherPriority.Normal); } } @@ -1665,7 +1687,7 @@ namespace AvaloniaEdit.Rendering if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); - + foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) @@ -1946,6 +1968,28 @@ namespace AvaloniaEdit.Rendering return pen; } + bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) + { + if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) + { + return false; + } + + // TODO: + // Convert rectangle into our coordinate space. + //var childTransform = target.TransformToVisual(this); + //rectangle = childTransform.Value(rectangle); + + MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); + + return true; + } + + IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) + { + return null; + } + /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> @@ -1999,5 +2043,71 @@ namespace AvaloniaEdit.Rendering /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; + + bool ILogicalScrollable.CanHorizontallyScroll + { + get => _canHorizontallyScroll; + set + { + if (_canHorizontallyScroll != value) + { + _canHorizontallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.CanVerticallyScroll + { + get => _canVerticallyScroll; + set + { + if (_canVerticallyScroll != value) + { + _canVerticallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.IsLogicalScrollEnabled => true; + + Action ILogicalScrollable.InvalidateScroll { get; set; } + + Size ILogicalScrollable.ScrollSize => new Size(10, 10); + + Size ILogicalScrollable.PageScrollSize => new Size(10, 10); + + Size IScrollable.Extent => _scrollExtent; + + Vector IScrollable.Offset + { + get => _scrollOffset; + set + { + value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); + var isX = !_scrollOffset.X.IsClose(value.X); + var isY = !_scrollOffset.Y.IsClose(value.Y); + if (isX || isY) + { + SetScrollOffset(value); + + if (isX) + { + InvalidateVisual(); + TextLayer.InvalidateVisual(); + } + + if (isY) + { + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + } + + Size IScrollable.Viewport => _scrollViewport; } }
126
Fix horizontal scroll
16
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062000
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent { #region Constructor static TextView() Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); } MeasureInlineObjects(); InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(_scrollViewport); } finally { VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); TextLayer.SetVisualLines(_visibleVisualLines); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); if (_visibleVisualLines != null) { } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if(!VisualLinesValid) { return; } builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } private void ClearScrollData() { SetScrollData(new Size(), new Size()); _scrollOffset = new Vector(); } public bool SetScrollData(Size viewport, Size extent) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent))) { _scrollViewport = viewport; _scrollExtent = extent; return true; } return false; } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; /// <summary> /// Gets the horizontal scroll offset. private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; /// </summary> public event EventHandler ScrollOffsetChanged; internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); if (!_canVerticallyScroll) vector = new Vector(vector.X, 0); if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); InvalidateMeasure(); } } CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); InvalidateMeasure(DispatcherPriority.Normal); } } Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); return pen; } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; } } <MSG> Fix horizontal scroll <DFF> @@ -32,6 +32,7 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; @@ -48,7 +49,7 @@ namespace AvaloniaEdit.Rendering /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] - public class TextView : Control, ITextEditorComponent + public class TextView : Control, ITextEditorComponent, ILogicalScrollable { #region Constructor static TextView() @@ -724,7 +725,7 @@ namespace AvaloniaEdit.Rendering { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } - + visualLine.Dispose(); RemoveInlineObjects(visualLine); } @@ -919,7 +920,8 @@ namespace AvaloniaEdit.Rendering } MeasureInlineObjects(); - InvalidateVisual(); // = InvalidateArrange+InvalidateRender + // TODO: is this needed? + //InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) @@ -934,7 +936,7 @@ namespace AvaloniaEdit.Rendering _inMeasure = true; try { - maxWidth = CreateAndMeasureVisualLines(_scrollViewport); + maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { @@ -964,6 +966,10 @@ namespace AvaloniaEdit.Rendering TextLayer.SetVisualLines(_visibleVisualLines); + SetScrollData(availableSize, + new Size(maxWidth, heightTreeHeight), + _scrollOffset); + VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); @@ -1076,7 +1082,7 @@ namespace AvaloniaEdit.Rendering { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); - + var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { @@ -1201,7 +1207,10 @@ namespace AvaloniaEdit.Rendering newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } - // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); + if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) + { + InvalidateMeasure(DispatcherPriority.Normal); + } if (_visibleVisualLines != null) { @@ -1226,6 +1235,7 @@ namespace AvaloniaEdit.Rendering } } } + InvalidateCursorIfPointerWithinTextView(); return finalSize; @@ -1256,7 +1266,7 @@ namespace AvaloniaEdit.Rendering /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - if(!VisualLinesValid) + if (!VisualLinesValid) { return; } @@ -1358,25 +1368,33 @@ namespace AvaloniaEdit.Rendering private void ClearScrollData() { - SetScrollData(new Size(), new Size()); - _scrollOffset = new Vector(); + SetScrollData(new Size(), new Size(), new Vector()); } - public bool SetScrollData(Size viewport, Size extent) + private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) - && extent.IsClose(_scrollExtent))) + && extent.IsClose(_scrollExtent) + && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; + SetScrollOffset(offset); + OnScrollChange(); return true; } + return false; } + private void OnScrollChange() + { + ((ILogicalScrollable)this).InvalidateScroll?.Invoke(); + } + private bool _canVerticallyScroll = true; - private bool _canHorizontallyScroll; + private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. @@ -1398,19 +1416,22 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - internal void SetScrollOffset(Vector vector) + private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) + { vector = new Vector(0, vector.Y); + } + if (!_canVerticallyScroll) + { vector = new Vector(vector.X, 0); + } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); - - InvalidateMeasure(); } } @@ -1555,6 +1576,7 @@ namespace AvaloniaEdit.Rendering if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); + OnScrollChange(); InvalidateMeasure(DispatcherPriority.Normal); } } @@ -1665,7 +1687,7 @@ namespace AvaloniaEdit.Rendering if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); - + foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) @@ -1946,6 +1968,28 @@ namespace AvaloniaEdit.Rendering return pen; } + bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) + { + if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) + { + return false; + } + + // TODO: + // Convert rectangle into our coordinate space. + //var childTransform = target.TransformToVisual(this); + //rectangle = childTransform.Value(rectangle); + + MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); + + return true; + } + + IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) + { + return null; + } + /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> @@ -1999,5 +2043,71 @@ namespace AvaloniaEdit.Rendering /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; + + bool ILogicalScrollable.CanHorizontallyScroll + { + get => _canHorizontallyScroll; + set + { + if (_canHorizontallyScroll != value) + { + _canHorizontallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.CanVerticallyScroll + { + get => _canVerticallyScroll; + set + { + if (_canVerticallyScroll != value) + { + _canVerticallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.IsLogicalScrollEnabled => true; + + Action ILogicalScrollable.InvalidateScroll { get; set; } + + Size ILogicalScrollable.ScrollSize => new Size(10, 10); + + Size ILogicalScrollable.PageScrollSize => new Size(10, 10); + + Size IScrollable.Extent => _scrollExtent; + + Vector IScrollable.Offset + { + get => _scrollOffset; + set + { + value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); + var isX = !_scrollOffset.X.IsClose(value.X); + var isY = !_scrollOffset.Y.IsClose(value.Y); + if (isX || isY) + { + SetScrollOffset(value); + + if (isX) + { + InvalidateVisual(); + TextLayer.InvalidateVisual(); + } + + if (isY) + { + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + } + + Size IScrollable.Viewport => _scrollViewport; } }
126
Fix horizontal scroll
16
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062001
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent { #region Constructor static TextView() Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); } MeasureInlineObjects(); InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(_scrollViewport); } finally { VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); TextLayer.SetVisualLines(_visibleVisualLines); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); if (_visibleVisualLines != null) { } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if(!VisualLinesValid) { return; } builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } private void ClearScrollData() { SetScrollData(new Size(), new Size()); _scrollOffset = new Vector(); } public bool SetScrollData(Size viewport, Size extent) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent))) { _scrollViewport = viewport; _scrollExtent = extent; return true; } return false; } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; /// <summary> /// Gets the horizontal scroll offset. private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; /// </summary> public event EventHandler ScrollOffsetChanged; internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); if (!_canVerticallyScroll) vector = new Vector(vector.X, 0); if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); InvalidateMeasure(); } } CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); InvalidateMeasure(DispatcherPriority.Normal); } } Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); return pen; } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; } } <MSG> Fix horizontal scroll <DFF> @@ -32,6 +32,7 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; @@ -48,7 +49,7 @@ namespace AvaloniaEdit.Rendering /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] - public class TextView : Control, ITextEditorComponent + public class TextView : Control, ITextEditorComponent, ILogicalScrollable { #region Constructor static TextView() @@ -724,7 +725,7 @@ namespace AvaloniaEdit.Rendering { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } - + visualLine.Dispose(); RemoveInlineObjects(visualLine); } @@ -919,7 +920,8 @@ namespace AvaloniaEdit.Rendering } MeasureInlineObjects(); - InvalidateVisual(); // = InvalidateArrange+InvalidateRender + // TODO: is this needed? + //InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) @@ -934,7 +936,7 @@ namespace AvaloniaEdit.Rendering _inMeasure = true; try { - maxWidth = CreateAndMeasureVisualLines(_scrollViewport); + maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { @@ -964,6 +966,10 @@ namespace AvaloniaEdit.Rendering TextLayer.SetVisualLines(_visibleVisualLines); + SetScrollData(availableSize, + new Size(maxWidth, heightTreeHeight), + _scrollOffset); + VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); @@ -1076,7 +1082,7 @@ namespace AvaloniaEdit.Rendering { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); - + var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { @@ -1201,7 +1207,10 @@ namespace AvaloniaEdit.Rendering newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } - // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); + if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) + { + InvalidateMeasure(DispatcherPriority.Normal); + } if (_visibleVisualLines != null) { @@ -1226,6 +1235,7 @@ namespace AvaloniaEdit.Rendering } } } + InvalidateCursorIfPointerWithinTextView(); return finalSize; @@ -1256,7 +1266,7 @@ namespace AvaloniaEdit.Rendering /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - if(!VisualLinesValid) + if (!VisualLinesValid) { return; } @@ -1358,25 +1368,33 @@ namespace AvaloniaEdit.Rendering private void ClearScrollData() { - SetScrollData(new Size(), new Size()); - _scrollOffset = new Vector(); + SetScrollData(new Size(), new Size(), new Vector()); } - public bool SetScrollData(Size viewport, Size extent) + private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) - && extent.IsClose(_scrollExtent))) + && extent.IsClose(_scrollExtent) + && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; + SetScrollOffset(offset); + OnScrollChange(); return true; } + return false; } + private void OnScrollChange() + { + ((ILogicalScrollable)this).InvalidateScroll?.Invoke(); + } + private bool _canVerticallyScroll = true; - private bool _canHorizontallyScroll; + private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. @@ -1398,19 +1416,22 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - internal void SetScrollOffset(Vector vector) + private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) + { vector = new Vector(0, vector.Y); + } + if (!_canVerticallyScroll) + { vector = new Vector(vector.X, 0); + } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); - - InvalidateMeasure(); } } @@ -1555,6 +1576,7 @@ namespace AvaloniaEdit.Rendering if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); + OnScrollChange(); InvalidateMeasure(DispatcherPriority.Normal); } } @@ -1665,7 +1687,7 @@ namespace AvaloniaEdit.Rendering if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); - + foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) @@ -1946,6 +1968,28 @@ namespace AvaloniaEdit.Rendering return pen; } + bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) + { + if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) + { + return false; + } + + // TODO: + // Convert rectangle into our coordinate space. + //var childTransform = target.TransformToVisual(this); + //rectangle = childTransform.Value(rectangle); + + MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); + + return true; + } + + IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) + { + return null; + } + /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> @@ -1999,5 +2043,71 @@ namespace AvaloniaEdit.Rendering /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; + + bool ILogicalScrollable.CanHorizontallyScroll + { + get => _canHorizontallyScroll; + set + { + if (_canHorizontallyScroll != value) + { + _canHorizontallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.CanVerticallyScroll + { + get => _canVerticallyScroll; + set + { + if (_canVerticallyScroll != value) + { + _canVerticallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.IsLogicalScrollEnabled => true; + + Action ILogicalScrollable.InvalidateScroll { get; set; } + + Size ILogicalScrollable.ScrollSize => new Size(10, 10); + + Size ILogicalScrollable.PageScrollSize => new Size(10, 10); + + Size IScrollable.Extent => _scrollExtent; + + Vector IScrollable.Offset + { + get => _scrollOffset; + set + { + value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); + var isX = !_scrollOffset.X.IsClose(value.X); + var isY = !_scrollOffset.Y.IsClose(value.Y); + if (isX || isY) + { + SetScrollOffset(value); + + if (isX) + { + InvalidateVisual(); + TextLayer.InvalidateVisual(); + } + + if (isY) + { + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + } + + Size IScrollable.Viewport => _scrollViewport; } }
126
Fix horizontal scroll
16
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062002
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent { #region Constructor static TextView() Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); } MeasureInlineObjects(); InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(_scrollViewport); } finally { VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); TextLayer.SetVisualLines(_visibleVisualLines); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); if (_visibleVisualLines != null) { } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if(!VisualLinesValid) { return; } builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } private void ClearScrollData() { SetScrollData(new Size(), new Size()); _scrollOffset = new Vector(); } public bool SetScrollData(Size viewport, Size extent) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent))) { _scrollViewport = viewport; _scrollExtent = extent; return true; } return false; } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; /// <summary> /// Gets the horizontal scroll offset. private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; /// </summary> public event EventHandler ScrollOffsetChanged; internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); if (!_canVerticallyScroll) vector = new Vector(vector.X, 0); if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); InvalidateMeasure(); } } CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); InvalidateMeasure(DispatcherPriority.Normal); } } Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); return pen; } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; } } <MSG> Fix horizontal scroll <DFF> @@ -32,6 +32,7 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; @@ -48,7 +49,7 @@ namespace AvaloniaEdit.Rendering /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] - public class TextView : Control, ITextEditorComponent + public class TextView : Control, ITextEditorComponent, ILogicalScrollable { #region Constructor static TextView() @@ -724,7 +725,7 @@ namespace AvaloniaEdit.Rendering { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } - + visualLine.Dispose(); RemoveInlineObjects(visualLine); } @@ -919,7 +920,8 @@ namespace AvaloniaEdit.Rendering } MeasureInlineObjects(); - InvalidateVisual(); // = InvalidateArrange+InvalidateRender + // TODO: is this needed? + //InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) @@ -934,7 +936,7 @@ namespace AvaloniaEdit.Rendering _inMeasure = true; try { - maxWidth = CreateAndMeasureVisualLines(_scrollViewport); + maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { @@ -964,6 +966,10 @@ namespace AvaloniaEdit.Rendering TextLayer.SetVisualLines(_visibleVisualLines); + SetScrollData(availableSize, + new Size(maxWidth, heightTreeHeight), + _scrollOffset); + VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); @@ -1076,7 +1082,7 @@ namespace AvaloniaEdit.Rendering { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); - + var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { @@ -1201,7 +1207,10 @@ namespace AvaloniaEdit.Rendering newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } - // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); + if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) + { + InvalidateMeasure(DispatcherPriority.Normal); + } if (_visibleVisualLines != null) { @@ -1226,6 +1235,7 @@ namespace AvaloniaEdit.Rendering } } } + InvalidateCursorIfPointerWithinTextView(); return finalSize; @@ -1256,7 +1266,7 @@ namespace AvaloniaEdit.Rendering /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - if(!VisualLinesValid) + if (!VisualLinesValid) { return; } @@ -1358,25 +1368,33 @@ namespace AvaloniaEdit.Rendering private void ClearScrollData() { - SetScrollData(new Size(), new Size()); - _scrollOffset = new Vector(); + SetScrollData(new Size(), new Size(), new Vector()); } - public bool SetScrollData(Size viewport, Size extent) + private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) - && extent.IsClose(_scrollExtent))) + && extent.IsClose(_scrollExtent) + && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; + SetScrollOffset(offset); + OnScrollChange(); return true; } + return false; } + private void OnScrollChange() + { + ((ILogicalScrollable)this).InvalidateScroll?.Invoke(); + } + private bool _canVerticallyScroll = true; - private bool _canHorizontallyScroll; + private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. @@ -1398,19 +1416,22 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - internal void SetScrollOffset(Vector vector) + private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) + { vector = new Vector(0, vector.Y); + } + if (!_canVerticallyScroll) + { vector = new Vector(vector.X, 0); + } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); - - InvalidateMeasure(); } } @@ -1555,6 +1576,7 @@ namespace AvaloniaEdit.Rendering if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); + OnScrollChange(); InvalidateMeasure(DispatcherPriority.Normal); } } @@ -1665,7 +1687,7 @@ namespace AvaloniaEdit.Rendering if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); - + foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) @@ -1946,6 +1968,28 @@ namespace AvaloniaEdit.Rendering return pen; } + bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) + { + if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) + { + return false; + } + + // TODO: + // Convert rectangle into our coordinate space. + //var childTransform = target.TransformToVisual(this); + //rectangle = childTransform.Value(rectangle); + + MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); + + return true; + } + + IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) + { + return null; + } + /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> @@ -1999,5 +2043,71 @@ namespace AvaloniaEdit.Rendering /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; + + bool ILogicalScrollable.CanHorizontallyScroll + { + get => _canHorizontallyScroll; + set + { + if (_canHorizontallyScroll != value) + { + _canHorizontallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.CanVerticallyScroll + { + get => _canVerticallyScroll; + set + { + if (_canVerticallyScroll != value) + { + _canVerticallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.IsLogicalScrollEnabled => true; + + Action ILogicalScrollable.InvalidateScroll { get; set; } + + Size ILogicalScrollable.ScrollSize => new Size(10, 10); + + Size ILogicalScrollable.PageScrollSize => new Size(10, 10); + + Size IScrollable.Extent => _scrollExtent; + + Vector IScrollable.Offset + { + get => _scrollOffset; + set + { + value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); + var isX = !_scrollOffset.X.IsClose(value.X); + var isY = !_scrollOffset.Y.IsClose(value.Y); + if (isX || isY) + { + SetScrollOffset(value); + + if (isX) + { + InvalidateVisual(); + TextLayer.InvalidateVisual(); + } + + if (isY) + { + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + } + + Size IScrollable.Viewport => _scrollViewport; } }
126
Fix horizontal scroll
16
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062003
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent { #region Constructor static TextView() Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); } MeasureInlineObjects(); InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(_scrollViewport); } finally { VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); TextLayer.SetVisualLines(_visibleVisualLines); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); if (_visibleVisualLines != null) { } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if(!VisualLinesValid) { return; } builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } private void ClearScrollData() { SetScrollData(new Size(), new Size()); _scrollOffset = new Vector(); } public bool SetScrollData(Size viewport, Size extent) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent))) { _scrollViewport = viewport; _scrollExtent = extent; return true; } return false; } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; /// <summary> /// Gets the horizontal scroll offset. private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; /// </summary> public event EventHandler ScrollOffsetChanged; internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); if (!_canVerticallyScroll) vector = new Vector(vector.X, 0); if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); InvalidateMeasure(); } } CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); InvalidateMeasure(DispatcherPriority.Normal); } } Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); return pen; } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; } } <MSG> Fix horizontal scroll <DFF> @@ -32,6 +32,7 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; @@ -48,7 +49,7 @@ namespace AvaloniaEdit.Rendering /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] - public class TextView : Control, ITextEditorComponent + public class TextView : Control, ITextEditorComponent, ILogicalScrollable { #region Constructor static TextView() @@ -724,7 +725,7 @@ namespace AvaloniaEdit.Rendering { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } - + visualLine.Dispose(); RemoveInlineObjects(visualLine); } @@ -919,7 +920,8 @@ namespace AvaloniaEdit.Rendering } MeasureInlineObjects(); - InvalidateVisual(); // = InvalidateArrange+InvalidateRender + // TODO: is this needed? + //InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) @@ -934,7 +936,7 @@ namespace AvaloniaEdit.Rendering _inMeasure = true; try { - maxWidth = CreateAndMeasureVisualLines(_scrollViewport); + maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { @@ -964,6 +966,10 @@ namespace AvaloniaEdit.Rendering TextLayer.SetVisualLines(_visibleVisualLines); + SetScrollData(availableSize, + new Size(maxWidth, heightTreeHeight), + _scrollOffset); + VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); @@ -1076,7 +1082,7 @@ namespace AvaloniaEdit.Rendering { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); - + var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { @@ -1201,7 +1207,10 @@ namespace AvaloniaEdit.Rendering newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } - // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); + if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) + { + InvalidateMeasure(DispatcherPriority.Normal); + } if (_visibleVisualLines != null) { @@ -1226,6 +1235,7 @@ namespace AvaloniaEdit.Rendering } } } + InvalidateCursorIfPointerWithinTextView(); return finalSize; @@ -1256,7 +1266,7 @@ namespace AvaloniaEdit.Rendering /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - if(!VisualLinesValid) + if (!VisualLinesValid) { return; } @@ -1358,25 +1368,33 @@ namespace AvaloniaEdit.Rendering private void ClearScrollData() { - SetScrollData(new Size(), new Size()); - _scrollOffset = new Vector(); + SetScrollData(new Size(), new Size(), new Vector()); } - public bool SetScrollData(Size viewport, Size extent) + private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) - && extent.IsClose(_scrollExtent))) + && extent.IsClose(_scrollExtent) + && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; + SetScrollOffset(offset); + OnScrollChange(); return true; } + return false; } + private void OnScrollChange() + { + ((ILogicalScrollable)this).InvalidateScroll?.Invoke(); + } + private bool _canVerticallyScroll = true; - private bool _canHorizontallyScroll; + private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. @@ -1398,19 +1416,22 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - internal void SetScrollOffset(Vector vector) + private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) + { vector = new Vector(0, vector.Y); + } + if (!_canVerticallyScroll) + { vector = new Vector(vector.X, 0); + } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); - - InvalidateMeasure(); } } @@ -1555,6 +1576,7 @@ namespace AvaloniaEdit.Rendering if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); + OnScrollChange(); InvalidateMeasure(DispatcherPriority.Normal); } } @@ -1665,7 +1687,7 @@ namespace AvaloniaEdit.Rendering if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); - + foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) @@ -1946,6 +1968,28 @@ namespace AvaloniaEdit.Rendering return pen; } + bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) + { + if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) + { + return false; + } + + // TODO: + // Convert rectangle into our coordinate space. + //var childTransform = target.TransformToVisual(this); + //rectangle = childTransform.Value(rectangle); + + MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); + + return true; + } + + IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) + { + return null; + } + /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> @@ -1999,5 +2043,71 @@ namespace AvaloniaEdit.Rendering /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; + + bool ILogicalScrollable.CanHorizontallyScroll + { + get => _canHorizontallyScroll; + set + { + if (_canHorizontallyScroll != value) + { + _canHorizontallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.CanVerticallyScroll + { + get => _canVerticallyScroll; + set + { + if (_canVerticallyScroll != value) + { + _canVerticallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.IsLogicalScrollEnabled => true; + + Action ILogicalScrollable.InvalidateScroll { get; set; } + + Size ILogicalScrollable.ScrollSize => new Size(10, 10); + + Size ILogicalScrollable.PageScrollSize => new Size(10, 10); + + Size IScrollable.Extent => _scrollExtent; + + Vector IScrollable.Offset + { + get => _scrollOffset; + set + { + value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); + var isX = !_scrollOffset.X.IsClose(value.X); + var isY = !_scrollOffset.Y.IsClose(value.Y); + if (isX || isY) + { + SetScrollOffset(value); + + if (isX) + { + InvalidateVisual(); + TextLayer.InvalidateVisual(); + } + + if (isY) + { + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + } + + Size IScrollable.Viewport => _scrollViewport; } }
126
Fix horizontal scroll
16
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062004
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent { #region Constructor static TextView() Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); } MeasureInlineObjects(); InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(_scrollViewport); } finally { VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); TextLayer.SetVisualLines(_visibleVisualLines); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); if (_visibleVisualLines != null) { } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if(!VisualLinesValid) { return; } builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } private void ClearScrollData() { SetScrollData(new Size(), new Size()); _scrollOffset = new Vector(); } public bool SetScrollData(Size viewport, Size extent) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent))) { _scrollViewport = viewport; _scrollExtent = extent; return true; } return false; } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; /// <summary> /// Gets the horizontal scroll offset. private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; /// </summary> public event EventHandler ScrollOffsetChanged; internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); if (!_canVerticallyScroll) vector = new Vector(vector.X, 0); if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); InvalidateMeasure(); } } CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); InvalidateMeasure(DispatcherPriority.Normal); } } Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); return pen; } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; } } <MSG> Fix horizontal scroll <DFF> @@ -32,6 +32,7 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; @@ -48,7 +49,7 @@ namespace AvaloniaEdit.Rendering /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] - public class TextView : Control, ITextEditorComponent + public class TextView : Control, ITextEditorComponent, ILogicalScrollable { #region Constructor static TextView() @@ -724,7 +725,7 @@ namespace AvaloniaEdit.Rendering { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } - + visualLine.Dispose(); RemoveInlineObjects(visualLine); } @@ -919,7 +920,8 @@ namespace AvaloniaEdit.Rendering } MeasureInlineObjects(); - InvalidateVisual(); // = InvalidateArrange+InvalidateRender + // TODO: is this needed? + //InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) @@ -934,7 +936,7 @@ namespace AvaloniaEdit.Rendering _inMeasure = true; try { - maxWidth = CreateAndMeasureVisualLines(_scrollViewport); + maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { @@ -964,6 +966,10 @@ namespace AvaloniaEdit.Rendering TextLayer.SetVisualLines(_visibleVisualLines); + SetScrollData(availableSize, + new Size(maxWidth, heightTreeHeight), + _scrollOffset); + VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); @@ -1076,7 +1082,7 @@ namespace AvaloniaEdit.Rendering { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); - + var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { @@ -1201,7 +1207,10 @@ namespace AvaloniaEdit.Rendering newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } - // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); + if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) + { + InvalidateMeasure(DispatcherPriority.Normal); + } if (_visibleVisualLines != null) { @@ -1226,6 +1235,7 @@ namespace AvaloniaEdit.Rendering } } } + InvalidateCursorIfPointerWithinTextView(); return finalSize; @@ -1256,7 +1266,7 @@ namespace AvaloniaEdit.Rendering /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - if(!VisualLinesValid) + if (!VisualLinesValid) { return; } @@ -1358,25 +1368,33 @@ namespace AvaloniaEdit.Rendering private void ClearScrollData() { - SetScrollData(new Size(), new Size()); - _scrollOffset = new Vector(); + SetScrollData(new Size(), new Size(), new Vector()); } - public bool SetScrollData(Size viewport, Size extent) + private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) - && extent.IsClose(_scrollExtent))) + && extent.IsClose(_scrollExtent) + && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; + SetScrollOffset(offset); + OnScrollChange(); return true; } + return false; } + private void OnScrollChange() + { + ((ILogicalScrollable)this).InvalidateScroll?.Invoke(); + } + private bool _canVerticallyScroll = true; - private bool _canHorizontallyScroll; + private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. @@ -1398,19 +1416,22 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - internal void SetScrollOffset(Vector vector) + private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) + { vector = new Vector(0, vector.Y); + } + if (!_canVerticallyScroll) + { vector = new Vector(vector.X, 0); + } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); - - InvalidateMeasure(); } } @@ -1555,6 +1576,7 @@ namespace AvaloniaEdit.Rendering if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); + OnScrollChange(); InvalidateMeasure(DispatcherPriority.Normal); } } @@ -1665,7 +1687,7 @@ namespace AvaloniaEdit.Rendering if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); - + foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) @@ -1946,6 +1968,28 @@ namespace AvaloniaEdit.Rendering return pen; } + bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) + { + if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) + { + return false; + } + + // TODO: + // Convert rectangle into our coordinate space. + //var childTransform = target.TransformToVisual(this); + //rectangle = childTransform.Value(rectangle); + + MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); + + return true; + } + + IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) + { + return null; + } + /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> @@ -1999,5 +2043,71 @@ namespace AvaloniaEdit.Rendering /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; + + bool ILogicalScrollable.CanHorizontallyScroll + { + get => _canHorizontallyScroll; + set + { + if (_canHorizontallyScroll != value) + { + _canHorizontallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.CanVerticallyScroll + { + get => _canVerticallyScroll; + set + { + if (_canVerticallyScroll != value) + { + _canVerticallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.IsLogicalScrollEnabled => true; + + Action ILogicalScrollable.InvalidateScroll { get; set; } + + Size ILogicalScrollable.ScrollSize => new Size(10, 10); + + Size ILogicalScrollable.PageScrollSize => new Size(10, 10); + + Size IScrollable.Extent => _scrollExtent; + + Vector IScrollable.Offset + { + get => _scrollOffset; + set + { + value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); + var isX = !_scrollOffset.X.IsClose(value.X); + var isY = !_scrollOffset.Y.IsClose(value.Y); + if (isX || isY) + { + SetScrollOffset(value); + + if (isX) + { + InvalidateVisual(); + TextLayer.InvalidateVisual(); + } + + if (isY) + { + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + } + + Size IScrollable.Viewport => _scrollViewport; } }
126
Fix horizontal scroll
16
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062005
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent { #region Constructor static TextView() Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); } MeasureInlineObjects(); InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(_scrollViewport); } finally { VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); TextLayer.SetVisualLines(_visibleVisualLines); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); if (_visibleVisualLines != null) { } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if(!VisualLinesValid) { return; } builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } private void ClearScrollData() { SetScrollData(new Size(), new Size()); _scrollOffset = new Vector(); } public bool SetScrollData(Size viewport, Size extent) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent))) { _scrollViewport = viewport; _scrollExtent = extent; return true; } return false; } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; /// <summary> /// Gets the horizontal scroll offset. private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; /// </summary> public event EventHandler ScrollOffsetChanged; internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); if (!_canVerticallyScroll) vector = new Vector(vector.X, 0); if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); InvalidateMeasure(); } } CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); InvalidateMeasure(DispatcherPriority.Normal); } } Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); return pen; } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; } } <MSG> Fix horizontal scroll <DFF> @@ -32,6 +32,7 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; @@ -48,7 +49,7 @@ namespace AvaloniaEdit.Rendering /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] - public class TextView : Control, ITextEditorComponent + public class TextView : Control, ITextEditorComponent, ILogicalScrollable { #region Constructor static TextView() @@ -724,7 +725,7 @@ namespace AvaloniaEdit.Rendering { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } - + visualLine.Dispose(); RemoveInlineObjects(visualLine); } @@ -919,7 +920,8 @@ namespace AvaloniaEdit.Rendering } MeasureInlineObjects(); - InvalidateVisual(); // = InvalidateArrange+InvalidateRender + // TODO: is this needed? + //InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) @@ -934,7 +936,7 @@ namespace AvaloniaEdit.Rendering _inMeasure = true; try { - maxWidth = CreateAndMeasureVisualLines(_scrollViewport); + maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { @@ -964,6 +966,10 @@ namespace AvaloniaEdit.Rendering TextLayer.SetVisualLines(_visibleVisualLines); + SetScrollData(availableSize, + new Size(maxWidth, heightTreeHeight), + _scrollOffset); + VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); @@ -1076,7 +1082,7 @@ namespace AvaloniaEdit.Rendering { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); - + var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { @@ -1201,7 +1207,10 @@ namespace AvaloniaEdit.Rendering newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } - // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); + if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) + { + InvalidateMeasure(DispatcherPriority.Normal); + } if (_visibleVisualLines != null) { @@ -1226,6 +1235,7 @@ namespace AvaloniaEdit.Rendering } } } + InvalidateCursorIfPointerWithinTextView(); return finalSize; @@ -1256,7 +1266,7 @@ namespace AvaloniaEdit.Rendering /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - if(!VisualLinesValid) + if (!VisualLinesValid) { return; } @@ -1358,25 +1368,33 @@ namespace AvaloniaEdit.Rendering private void ClearScrollData() { - SetScrollData(new Size(), new Size()); - _scrollOffset = new Vector(); + SetScrollData(new Size(), new Size(), new Vector()); } - public bool SetScrollData(Size viewport, Size extent) + private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) - && extent.IsClose(_scrollExtent))) + && extent.IsClose(_scrollExtent) + && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; + SetScrollOffset(offset); + OnScrollChange(); return true; } + return false; } + private void OnScrollChange() + { + ((ILogicalScrollable)this).InvalidateScroll?.Invoke(); + } + private bool _canVerticallyScroll = true; - private bool _canHorizontallyScroll; + private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. @@ -1398,19 +1416,22 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - internal void SetScrollOffset(Vector vector) + private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) + { vector = new Vector(0, vector.Y); + } + if (!_canVerticallyScroll) + { vector = new Vector(vector.X, 0); + } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); - - InvalidateMeasure(); } } @@ -1555,6 +1576,7 @@ namespace AvaloniaEdit.Rendering if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); + OnScrollChange(); InvalidateMeasure(DispatcherPriority.Normal); } } @@ -1665,7 +1687,7 @@ namespace AvaloniaEdit.Rendering if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); - + foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) @@ -1946,6 +1968,28 @@ namespace AvaloniaEdit.Rendering return pen; } + bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) + { + if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) + { + return false; + } + + // TODO: + // Convert rectangle into our coordinate space. + //var childTransform = target.TransformToVisual(this); + //rectangle = childTransform.Value(rectangle); + + MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); + + return true; + } + + IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) + { + return null; + } + /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> @@ -1999,5 +2043,71 @@ namespace AvaloniaEdit.Rendering /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; + + bool ILogicalScrollable.CanHorizontallyScroll + { + get => _canHorizontallyScroll; + set + { + if (_canHorizontallyScroll != value) + { + _canHorizontallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.CanVerticallyScroll + { + get => _canVerticallyScroll; + set + { + if (_canVerticallyScroll != value) + { + _canVerticallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.IsLogicalScrollEnabled => true; + + Action ILogicalScrollable.InvalidateScroll { get; set; } + + Size ILogicalScrollable.ScrollSize => new Size(10, 10); + + Size ILogicalScrollable.PageScrollSize => new Size(10, 10); + + Size IScrollable.Extent => _scrollExtent; + + Vector IScrollable.Offset + { + get => _scrollOffset; + set + { + value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); + var isX = !_scrollOffset.X.IsClose(value.X); + var isY = !_scrollOffset.Y.IsClose(value.Y); + if (isX || isY) + { + SetScrollOffset(value); + + if (isX) + { + InvalidateVisual(); + TextLayer.InvalidateVisual(); + } + + if (isY) + { + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + } + + Size IScrollable.Viewport => _scrollViewport; } }
126
Fix horizontal scroll
16
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062006
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent { #region Constructor static TextView() Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); } MeasureInlineObjects(); InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(_scrollViewport); } finally { VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); TextLayer.SetVisualLines(_visibleVisualLines); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); if (_visibleVisualLines != null) { } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if(!VisualLinesValid) { return; } builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } private void ClearScrollData() { SetScrollData(new Size(), new Size()); _scrollOffset = new Vector(); } public bool SetScrollData(Size viewport, Size extent) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent))) { _scrollViewport = viewport; _scrollExtent = extent; return true; } return false; } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; /// <summary> /// Gets the horizontal scroll offset. private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; /// </summary> public event EventHandler ScrollOffsetChanged; internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); if (!_canVerticallyScroll) vector = new Vector(vector.X, 0); if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); InvalidateMeasure(); } } CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); InvalidateMeasure(DispatcherPriority.Normal); } } Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); return pen; } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; } } <MSG> Fix horizontal scroll <DFF> @@ -32,6 +32,7 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; @@ -48,7 +49,7 @@ namespace AvaloniaEdit.Rendering /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] - public class TextView : Control, ITextEditorComponent + public class TextView : Control, ITextEditorComponent, ILogicalScrollable { #region Constructor static TextView() @@ -724,7 +725,7 @@ namespace AvaloniaEdit.Rendering { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } - + visualLine.Dispose(); RemoveInlineObjects(visualLine); } @@ -919,7 +920,8 @@ namespace AvaloniaEdit.Rendering } MeasureInlineObjects(); - InvalidateVisual(); // = InvalidateArrange+InvalidateRender + // TODO: is this needed? + //InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) @@ -934,7 +936,7 @@ namespace AvaloniaEdit.Rendering _inMeasure = true; try { - maxWidth = CreateAndMeasureVisualLines(_scrollViewport); + maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { @@ -964,6 +966,10 @@ namespace AvaloniaEdit.Rendering TextLayer.SetVisualLines(_visibleVisualLines); + SetScrollData(availableSize, + new Size(maxWidth, heightTreeHeight), + _scrollOffset); + VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); @@ -1076,7 +1082,7 @@ namespace AvaloniaEdit.Rendering { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); - + var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { @@ -1201,7 +1207,10 @@ namespace AvaloniaEdit.Rendering newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } - // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); + if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) + { + InvalidateMeasure(DispatcherPriority.Normal); + } if (_visibleVisualLines != null) { @@ -1226,6 +1235,7 @@ namespace AvaloniaEdit.Rendering } } } + InvalidateCursorIfPointerWithinTextView(); return finalSize; @@ -1256,7 +1266,7 @@ namespace AvaloniaEdit.Rendering /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - if(!VisualLinesValid) + if (!VisualLinesValid) { return; } @@ -1358,25 +1368,33 @@ namespace AvaloniaEdit.Rendering private void ClearScrollData() { - SetScrollData(new Size(), new Size()); - _scrollOffset = new Vector(); + SetScrollData(new Size(), new Size(), new Vector()); } - public bool SetScrollData(Size viewport, Size extent) + private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) - && extent.IsClose(_scrollExtent))) + && extent.IsClose(_scrollExtent) + && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; + SetScrollOffset(offset); + OnScrollChange(); return true; } + return false; } + private void OnScrollChange() + { + ((ILogicalScrollable)this).InvalidateScroll?.Invoke(); + } + private bool _canVerticallyScroll = true; - private bool _canHorizontallyScroll; + private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. @@ -1398,19 +1416,22 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - internal void SetScrollOffset(Vector vector) + private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) + { vector = new Vector(0, vector.Y); + } + if (!_canVerticallyScroll) + { vector = new Vector(vector.X, 0); + } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); - - InvalidateMeasure(); } } @@ -1555,6 +1576,7 @@ namespace AvaloniaEdit.Rendering if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); + OnScrollChange(); InvalidateMeasure(DispatcherPriority.Normal); } } @@ -1665,7 +1687,7 @@ namespace AvaloniaEdit.Rendering if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); - + foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) @@ -1946,6 +1968,28 @@ namespace AvaloniaEdit.Rendering return pen; } + bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) + { + if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) + { + return false; + } + + // TODO: + // Convert rectangle into our coordinate space. + //var childTransform = target.TransformToVisual(this); + //rectangle = childTransform.Value(rectangle); + + MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); + + return true; + } + + IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) + { + return null; + } + /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> @@ -1999,5 +2043,71 @@ namespace AvaloniaEdit.Rendering /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; + + bool ILogicalScrollable.CanHorizontallyScroll + { + get => _canHorizontallyScroll; + set + { + if (_canHorizontallyScroll != value) + { + _canHorizontallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.CanVerticallyScroll + { + get => _canVerticallyScroll; + set + { + if (_canVerticallyScroll != value) + { + _canVerticallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.IsLogicalScrollEnabled => true; + + Action ILogicalScrollable.InvalidateScroll { get; set; } + + Size ILogicalScrollable.ScrollSize => new Size(10, 10); + + Size ILogicalScrollable.PageScrollSize => new Size(10, 10); + + Size IScrollable.Extent => _scrollExtent; + + Vector IScrollable.Offset + { + get => _scrollOffset; + set + { + value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); + var isX = !_scrollOffset.X.IsClose(value.X); + var isY = !_scrollOffset.Y.IsClose(value.Y); + if (isX || isY) + { + SetScrollOffset(value); + + if (isX) + { + InvalidateVisual(); + TextLayer.InvalidateVisual(); + } + + if (isY) + { + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + } + + Size IScrollable.Viewport => _scrollViewport; } }
126
Fix horizontal scroll
16
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062007
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent { #region Constructor static TextView() Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); } MeasureInlineObjects(); InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(_scrollViewport); } finally { VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); TextLayer.SetVisualLines(_visibleVisualLines); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); if (_visibleVisualLines != null) { } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if(!VisualLinesValid) { return; } builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } private void ClearScrollData() { SetScrollData(new Size(), new Size()); _scrollOffset = new Vector(); } public bool SetScrollData(Size viewport, Size extent) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent))) { _scrollViewport = viewport; _scrollExtent = extent; return true; } return false; } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; /// <summary> /// Gets the horizontal scroll offset. private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; /// </summary> public event EventHandler ScrollOffsetChanged; internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); if (!_canVerticallyScroll) vector = new Vector(vector.X, 0); if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); InvalidateMeasure(); } } CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); InvalidateMeasure(DispatcherPriority.Normal); } } Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); return pen; } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; } } <MSG> Fix horizontal scroll <DFF> @@ -32,6 +32,7 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; @@ -48,7 +49,7 @@ namespace AvaloniaEdit.Rendering /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] - public class TextView : Control, ITextEditorComponent + public class TextView : Control, ITextEditorComponent, ILogicalScrollable { #region Constructor static TextView() @@ -724,7 +725,7 @@ namespace AvaloniaEdit.Rendering { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } - + visualLine.Dispose(); RemoveInlineObjects(visualLine); } @@ -919,7 +920,8 @@ namespace AvaloniaEdit.Rendering } MeasureInlineObjects(); - InvalidateVisual(); // = InvalidateArrange+InvalidateRender + // TODO: is this needed? + //InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) @@ -934,7 +936,7 @@ namespace AvaloniaEdit.Rendering _inMeasure = true; try { - maxWidth = CreateAndMeasureVisualLines(_scrollViewport); + maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { @@ -964,6 +966,10 @@ namespace AvaloniaEdit.Rendering TextLayer.SetVisualLines(_visibleVisualLines); + SetScrollData(availableSize, + new Size(maxWidth, heightTreeHeight), + _scrollOffset); + VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); @@ -1076,7 +1082,7 @@ namespace AvaloniaEdit.Rendering { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); - + var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { @@ -1201,7 +1207,10 @@ namespace AvaloniaEdit.Rendering newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } - // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); + if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) + { + InvalidateMeasure(DispatcherPriority.Normal); + } if (_visibleVisualLines != null) { @@ -1226,6 +1235,7 @@ namespace AvaloniaEdit.Rendering } } } + InvalidateCursorIfPointerWithinTextView(); return finalSize; @@ -1256,7 +1266,7 @@ namespace AvaloniaEdit.Rendering /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - if(!VisualLinesValid) + if (!VisualLinesValid) { return; } @@ -1358,25 +1368,33 @@ namespace AvaloniaEdit.Rendering private void ClearScrollData() { - SetScrollData(new Size(), new Size()); - _scrollOffset = new Vector(); + SetScrollData(new Size(), new Size(), new Vector()); } - public bool SetScrollData(Size viewport, Size extent) + private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) - && extent.IsClose(_scrollExtent))) + && extent.IsClose(_scrollExtent) + && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; + SetScrollOffset(offset); + OnScrollChange(); return true; } + return false; } + private void OnScrollChange() + { + ((ILogicalScrollable)this).InvalidateScroll?.Invoke(); + } + private bool _canVerticallyScroll = true; - private bool _canHorizontallyScroll; + private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. @@ -1398,19 +1416,22 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - internal void SetScrollOffset(Vector vector) + private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) + { vector = new Vector(0, vector.Y); + } + if (!_canVerticallyScroll) + { vector = new Vector(vector.X, 0); + } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); - - InvalidateMeasure(); } } @@ -1555,6 +1576,7 @@ namespace AvaloniaEdit.Rendering if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); + OnScrollChange(); InvalidateMeasure(DispatcherPriority.Normal); } } @@ -1665,7 +1687,7 @@ namespace AvaloniaEdit.Rendering if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); - + foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) @@ -1946,6 +1968,28 @@ namespace AvaloniaEdit.Rendering return pen; } + bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) + { + if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) + { + return false; + } + + // TODO: + // Convert rectangle into our coordinate space. + //var childTransform = target.TransformToVisual(this); + //rectangle = childTransform.Value(rectangle); + + MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); + + return true; + } + + IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) + { + return null; + } + /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> @@ -1999,5 +2043,71 @@ namespace AvaloniaEdit.Rendering /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; + + bool ILogicalScrollable.CanHorizontallyScroll + { + get => _canHorizontallyScroll; + set + { + if (_canHorizontallyScroll != value) + { + _canHorizontallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.CanVerticallyScroll + { + get => _canVerticallyScroll; + set + { + if (_canVerticallyScroll != value) + { + _canVerticallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.IsLogicalScrollEnabled => true; + + Action ILogicalScrollable.InvalidateScroll { get; set; } + + Size ILogicalScrollable.ScrollSize => new Size(10, 10); + + Size ILogicalScrollable.PageScrollSize => new Size(10, 10); + + Size IScrollable.Extent => _scrollExtent; + + Vector IScrollable.Offset + { + get => _scrollOffset; + set + { + value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); + var isX = !_scrollOffset.X.IsClose(value.X); + var isY = !_scrollOffset.Y.IsClose(value.Y); + if (isX || isY) + { + SetScrollOffset(value); + + if (isX) + { + InvalidateVisual(); + TextLayer.InvalidateVisual(); + } + + if (isY) + { + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + } + + Size IScrollable.Viewport => _scrollViewport; } }
126
Fix horizontal scroll
16
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062008
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent { #region Constructor static TextView() Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); } MeasureInlineObjects(); InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(_scrollViewport); } finally { VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); TextLayer.SetVisualLines(_visibleVisualLines); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); if (_visibleVisualLines != null) { } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if(!VisualLinesValid) { return; } builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } private void ClearScrollData() { SetScrollData(new Size(), new Size()); _scrollOffset = new Vector(); } public bool SetScrollData(Size viewport, Size extent) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent))) { _scrollViewport = viewport; _scrollExtent = extent; return true; } return false; } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; /// <summary> /// Gets the horizontal scroll offset. private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; /// </summary> public event EventHandler ScrollOffsetChanged; internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); if (!_canVerticallyScroll) vector = new Vector(vector.X, 0); if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); InvalidateMeasure(); } } CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); InvalidateMeasure(DispatcherPriority.Normal); } } Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); return pen; } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; } } <MSG> Fix horizontal scroll <DFF> @@ -32,6 +32,7 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; @@ -48,7 +49,7 @@ namespace AvaloniaEdit.Rendering /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] - public class TextView : Control, ITextEditorComponent + public class TextView : Control, ITextEditorComponent, ILogicalScrollable { #region Constructor static TextView() @@ -724,7 +725,7 @@ namespace AvaloniaEdit.Rendering { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } - + visualLine.Dispose(); RemoveInlineObjects(visualLine); } @@ -919,7 +920,8 @@ namespace AvaloniaEdit.Rendering } MeasureInlineObjects(); - InvalidateVisual(); // = InvalidateArrange+InvalidateRender + // TODO: is this needed? + //InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) @@ -934,7 +936,7 @@ namespace AvaloniaEdit.Rendering _inMeasure = true; try { - maxWidth = CreateAndMeasureVisualLines(_scrollViewport); + maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { @@ -964,6 +966,10 @@ namespace AvaloniaEdit.Rendering TextLayer.SetVisualLines(_visibleVisualLines); + SetScrollData(availableSize, + new Size(maxWidth, heightTreeHeight), + _scrollOffset); + VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); @@ -1076,7 +1082,7 @@ namespace AvaloniaEdit.Rendering { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); - + var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { @@ -1201,7 +1207,10 @@ namespace AvaloniaEdit.Rendering newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } - // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); + if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) + { + InvalidateMeasure(DispatcherPriority.Normal); + } if (_visibleVisualLines != null) { @@ -1226,6 +1235,7 @@ namespace AvaloniaEdit.Rendering } } } + InvalidateCursorIfPointerWithinTextView(); return finalSize; @@ -1256,7 +1266,7 @@ namespace AvaloniaEdit.Rendering /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - if(!VisualLinesValid) + if (!VisualLinesValid) { return; } @@ -1358,25 +1368,33 @@ namespace AvaloniaEdit.Rendering private void ClearScrollData() { - SetScrollData(new Size(), new Size()); - _scrollOffset = new Vector(); + SetScrollData(new Size(), new Size(), new Vector()); } - public bool SetScrollData(Size viewport, Size extent) + private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) - && extent.IsClose(_scrollExtent))) + && extent.IsClose(_scrollExtent) + && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; + SetScrollOffset(offset); + OnScrollChange(); return true; } + return false; } + private void OnScrollChange() + { + ((ILogicalScrollable)this).InvalidateScroll?.Invoke(); + } + private bool _canVerticallyScroll = true; - private bool _canHorizontallyScroll; + private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. @@ -1398,19 +1416,22 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - internal void SetScrollOffset(Vector vector) + private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) + { vector = new Vector(0, vector.Y); + } + if (!_canVerticallyScroll) + { vector = new Vector(vector.X, 0); + } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); - - InvalidateMeasure(); } } @@ -1555,6 +1576,7 @@ namespace AvaloniaEdit.Rendering if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); + OnScrollChange(); InvalidateMeasure(DispatcherPriority.Normal); } } @@ -1665,7 +1687,7 @@ namespace AvaloniaEdit.Rendering if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); - + foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) @@ -1946,6 +1968,28 @@ namespace AvaloniaEdit.Rendering return pen; } + bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) + { + if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) + { + return false; + } + + // TODO: + // Convert rectangle into our coordinate space. + //var childTransform = target.TransformToVisual(this); + //rectangle = childTransform.Value(rectangle); + + MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); + + return true; + } + + IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) + { + return null; + } + /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> @@ -1999,5 +2043,71 @@ namespace AvaloniaEdit.Rendering /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; + + bool ILogicalScrollable.CanHorizontallyScroll + { + get => _canHorizontallyScroll; + set + { + if (_canHorizontallyScroll != value) + { + _canHorizontallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.CanVerticallyScroll + { + get => _canVerticallyScroll; + set + { + if (_canVerticallyScroll != value) + { + _canVerticallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.IsLogicalScrollEnabled => true; + + Action ILogicalScrollable.InvalidateScroll { get; set; } + + Size ILogicalScrollable.ScrollSize => new Size(10, 10); + + Size ILogicalScrollable.PageScrollSize => new Size(10, 10); + + Size IScrollable.Extent => _scrollExtent; + + Vector IScrollable.Offset + { + get => _scrollOffset; + set + { + value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); + var isX = !_scrollOffset.X.IsClose(value.X); + var isY = !_scrollOffset.Y.IsClose(value.Y); + if (isX || isY) + { + SetScrollOffset(value); + + if (isX) + { + InvalidateVisual(); + TextLayer.InvalidateVisual(); + } + + if (isY) + { + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + } + + Size IScrollable.Viewport => _scrollViewport; } }
126
Fix horizontal scroll
16
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062009
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent { #region Constructor static TextView() Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); } MeasureInlineObjects(); InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(_scrollViewport); } finally { VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); TextLayer.SetVisualLines(_visibleVisualLines); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); if (_visibleVisualLines != null) { } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if(!VisualLinesValid) { return; } builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } private void ClearScrollData() { SetScrollData(new Size(), new Size()); _scrollOffset = new Vector(); } public bool SetScrollData(Size viewport, Size extent) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent))) { _scrollViewport = viewport; _scrollExtent = extent; return true; } return false; } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; /// <summary> /// Gets the horizontal scroll offset. private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; /// </summary> public event EventHandler ScrollOffsetChanged; internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); if (!_canVerticallyScroll) vector = new Vector(vector.X, 0); if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); InvalidateMeasure(); } } CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); InvalidateMeasure(DispatcherPriority.Normal); } } Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); return pen; } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; } } <MSG> Fix horizontal scroll <DFF> @@ -32,6 +32,7 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; @@ -48,7 +49,7 @@ namespace AvaloniaEdit.Rendering /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] - public class TextView : Control, ITextEditorComponent + public class TextView : Control, ITextEditorComponent, ILogicalScrollable { #region Constructor static TextView() @@ -724,7 +725,7 @@ namespace AvaloniaEdit.Rendering { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } - + visualLine.Dispose(); RemoveInlineObjects(visualLine); } @@ -919,7 +920,8 @@ namespace AvaloniaEdit.Rendering } MeasureInlineObjects(); - InvalidateVisual(); // = InvalidateArrange+InvalidateRender + // TODO: is this needed? + //InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) @@ -934,7 +936,7 @@ namespace AvaloniaEdit.Rendering _inMeasure = true; try { - maxWidth = CreateAndMeasureVisualLines(_scrollViewport); + maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { @@ -964,6 +966,10 @@ namespace AvaloniaEdit.Rendering TextLayer.SetVisualLines(_visibleVisualLines); + SetScrollData(availableSize, + new Size(maxWidth, heightTreeHeight), + _scrollOffset); + VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); @@ -1076,7 +1082,7 @@ namespace AvaloniaEdit.Rendering { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); - + var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { @@ -1201,7 +1207,10 @@ namespace AvaloniaEdit.Rendering newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } - // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); + if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) + { + InvalidateMeasure(DispatcherPriority.Normal); + } if (_visibleVisualLines != null) { @@ -1226,6 +1235,7 @@ namespace AvaloniaEdit.Rendering } } } + InvalidateCursorIfPointerWithinTextView(); return finalSize; @@ -1256,7 +1266,7 @@ namespace AvaloniaEdit.Rendering /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - if(!VisualLinesValid) + if (!VisualLinesValid) { return; } @@ -1358,25 +1368,33 @@ namespace AvaloniaEdit.Rendering private void ClearScrollData() { - SetScrollData(new Size(), new Size()); - _scrollOffset = new Vector(); + SetScrollData(new Size(), new Size(), new Vector()); } - public bool SetScrollData(Size viewport, Size extent) + private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) - && extent.IsClose(_scrollExtent))) + && extent.IsClose(_scrollExtent) + && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; + SetScrollOffset(offset); + OnScrollChange(); return true; } + return false; } + private void OnScrollChange() + { + ((ILogicalScrollable)this).InvalidateScroll?.Invoke(); + } + private bool _canVerticallyScroll = true; - private bool _canHorizontallyScroll; + private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. @@ -1398,19 +1416,22 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - internal void SetScrollOffset(Vector vector) + private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) + { vector = new Vector(0, vector.Y); + } + if (!_canVerticallyScroll) + { vector = new Vector(vector.X, 0); + } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); - - InvalidateMeasure(); } } @@ -1555,6 +1576,7 @@ namespace AvaloniaEdit.Rendering if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); + OnScrollChange(); InvalidateMeasure(DispatcherPriority.Normal); } } @@ -1665,7 +1687,7 @@ namespace AvaloniaEdit.Rendering if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); - + foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) @@ -1946,6 +1968,28 @@ namespace AvaloniaEdit.Rendering return pen; } + bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) + { + if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) + { + return false; + } + + // TODO: + // Convert rectangle into our coordinate space. + //var childTransform = target.TransformToVisual(this); + //rectangle = childTransform.Value(rectangle); + + MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); + + return true; + } + + IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) + { + return null; + } + /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> @@ -1999,5 +2043,71 @@ namespace AvaloniaEdit.Rendering /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; + + bool ILogicalScrollable.CanHorizontallyScroll + { + get => _canHorizontallyScroll; + set + { + if (_canHorizontallyScroll != value) + { + _canHorizontallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.CanVerticallyScroll + { + get => _canVerticallyScroll; + set + { + if (_canVerticallyScroll != value) + { + _canVerticallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.IsLogicalScrollEnabled => true; + + Action ILogicalScrollable.InvalidateScroll { get; set; } + + Size ILogicalScrollable.ScrollSize => new Size(10, 10); + + Size ILogicalScrollable.PageScrollSize => new Size(10, 10); + + Size IScrollable.Extent => _scrollExtent; + + Vector IScrollable.Offset + { + get => _scrollOffset; + set + { + value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); + var isX = !_scrollOffset.X.IsClose(value.X); + var isY = !_scrollOffset.Y.IsClose(value.Y); + if (isX || isY) + { + SetScrollOffset(value); + + if (isX) + { + InvalidateVisual(); + TextLayer.InvalidateVisual(); + } + + if (isY) + { + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + } + + Size IScrollable.Viewport => _scrollViewport; } }
126
Fix horizontal scroll
16
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062010
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent { #region Constructor static TextView() Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); } MeasureInlineObjects(); InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(_scrollViewport); } finally { VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); TextLayer.SetVisualLines(_visibleVisualLines); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); if (_visibleVisualLines != null) { } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if(!VisualLinesValid) { return; } builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } private void ClearScrollData() { SetScrollData(new Size(), new Size()); _scrollOffset = new Vector(); } public bool SetScrollData(Size viewport, Size extent) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent))) { _scrollViewport = viewport; _scrollExtent = extent; return true; } return false; } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; /// <summary> /// Gets the horizontal scroll offset. private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; /// </summary> public event EventHandler ScrollOffsetChanged; internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); if (!_canVerticallyScroll) vector = new Vector(vector.X, 0); if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); InvalidateMeasure(); } } CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); InvalidateMeasure(DispatcherPriority.Normal); } } Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); return pen; } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; } } <MSG> Fix horizontal scroll <DFF> @@ -32,6 +32,7 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; @@ -48,7 +49,7 @@ namespace AvaloniaEdit.Rendering /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] - public class TextView : Control, ITextEditorComponent + public class TextView : Control, ITextEditorComponent, ILogicalScrollable { #region Constructor static TextView() @@ -724,7 +725,7 @@ namespace AvaloniaEdit.Rendering { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } - + visualLine.Dispose(); RemoveInlineObjects(visualLine); } @@ -919,7 +920,8 @@ namespace AvaloniaEdit.Rendering } MeasureInlineObjects(); - InvalidateVisual(); // = InvalidateArrange+InvalidateRender + // TODO: is this needed? + //InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) @@ -934,7 +936,7 @@ namespace AvaloniaEdit.Rendering _inMeasure = true; try { - maxWidth = CreateAndMeasureVisualLines(_scrollViewport); + maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { @@ -964,6 +966,10 @@ namespace AvaloniaEdit.Rendering TextLayer.SetVisualLines(_visibleVisualLines); + SetScrollData(availableSize, + new Size(maxWidth, heightTreeHeight), + _scrollOffset); + VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); @@ -1076,7 +1082,7 @@ namespace AvaloniaEdit.Rendering { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); - + var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { @@ -1201,7 +1207,10 @@ namespace AvaloniaEdit.Rendering newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } - // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); + if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) + { + InvalidateMeasure(DispatcherPriority.Normal); + } if (_visibleVisualLines != null) { @@ -1226,6 +1235,7 @@ namespace AvaloniaEdit.Rendering } } } + InvalidateCursorIfPointerWithinTextView(); return finalSize; @@ -1256,7 +1266,7 @@ namespace AvaloniaEdit.Rendering /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - if(!VisualLinesValid) + if (!VisualLinesValid) { return; } @@ -1358,25 +1368,33 @@ namespace AvaloniaEdit.Rendering private void ClearScrollData() { - SetScrollData(new Size(), new Size()); - _scrollOffset = new Vector(); + SetScrollData(new Size(), new Size(), new Vector()); } - public bool SetScrollData(Size viewport, Size extent) + private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) - && extent.IsClose(_scrollExtent))) + && extent.IsClose(_scrollExtent) + && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; + SetScrollOffset(offset); + OnScrollChange(); return true; } + return false; } + private void OnScrollChange() + { + ((ILogicalScrollable)this).InvalidateScroll?.Invoke(); + } + private bool _canVerticallyScroll = true; - private bool _canHorizontallyScroll; + private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. @@ -1398,19 +1416,22 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - internal void SetScrollOffset(Vector vector) + private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) + { vector = new Vector(0, vector.Y); + } + if (!_canVerticallyScroll) + { vector = new Vector(vector.X, 0); + } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); - - InvalidateMeasure(); } } @@ -1555,6 +1576,7 @@ namespace AvaloniaEdit.Rendering if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); + OnScrollChange(); InvalidateMeasure(DispatcherPriority.Normal); } } @@ -1665,7 +1687,7 @@ namespace AvaloniaEdit.Rendering if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); - + foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) @@ -1946,6 +1968,28 @@ namespace AvaloniaEdit.Rendering return pen; } + bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) + { + if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) + { + return false; + } + + // TODO: + // Convert rectangle into our coordinate space. + //var childTransform = target.TransformToVisual(this); + //rectangle = childTransform.Value(rectangle); + + MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); + + return true; + } + + IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) + { + return null; + } + /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> @@ -1999,5 +2043,71 @@ namespace AvaloniaEdit.Rendering /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; + + bool ILogicalScrollable.CanHorizontallyScroll + { + get => _canHorizontallyScroll; + set + { + if (_canHorizontallyScroll != value) + { + _canHorizontallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.CanVerticallyScroll + { + get => _canVerticallyScroll; + set + { + if (_canVerticallyScroll != value) + { + _canVerticallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.IsLogicalScrollEnabled => true; + + Action ILogicalScrollable.InvalidateScroll { get; set; } + + Size ILogicalScrollable.ScrollSize => new Size(10, 10); + + Size ILogicalScrollable.PageScrollSize => new Size(10, 10); + + Size IScrollable.Extent => _scrollExtent; + + Vector IScrollable.Offset + { + get => _scrollOffset; + set + { + value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); + var isX = !_scrollOffset.X.IsClose(value.X); + var isY = !_scrollOffset.Y.IsClose(value.Y); + if (isX || isY) + { + SetScrollOffset(value); + + if (isX) + { + InvalidateVisual(); + TextLayer.InvalidateVisual(); + } + + if (isY) + { + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + } + + Size IScrollable.Viewport => _scrollViewport; } }
126
Fix horizontal scroll
16
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062011
<NME> TextView.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Utils; namespace AvaloniaEdit.Rendering { /// <summary> /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent { #region Constructor static TextView() Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] public class TextView : Control, ITextEditorComponent, ILogicalScrollable { private EventHandler _scrollInvalidated; #region Constructor static TextView() { ClipToBoundsProperty.OverrideDefaultValue<TextView>(true); FocusableProperty.OverrideDefaultValue<TextView>(false); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); } private readonly ColumnRulerRenderer _columnRulerRenderer; private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer; /// <summary> /// Creates a new TextView instance. /// </summary> public TextView() { Services.AddService(this); TextLayer = new TextLayer(this); _elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed); _lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed); _backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed); _columnRulerRenderer = new ColumnRulerRenderer(this); _currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this); Options = new TextEditorOptions(); Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators Layers = new LayerCollection(this); InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace); _hoverLogic = new PointerHoverLogic(this); _hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent); _hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent); } #endregion #region Document Property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = AvaloniaProperty.Register<TextView, TextDocument>("Document"); private TextDocument _document; private HeightTree _heightTree; /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } internal double FontSize { get => GetValue(TemplatedControl.FontSizeProperty); set => SetValue(TemplatedControl.FontSizeProperty, value); } internal FontFamily FontFamily { get => GetValue(TemplatedControl.FontFamilyProperty); set => SetValue(TemplatedControl.FontFamilyProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { _heightTree.Dispose(); _heightTree = null; _formatter = null; CachedElements = null; TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging); } _document = newValue; ClearScrollData(); ClearVisualLines(); if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging); _formatter = TextFormatter.Current; InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter _heightTree = new HeightTree(newValue, DefaultLineHeight); CachedElements = new TextViewCachedElements(); } InvalidateMeasure(); DocumentChanged?.Invoke(this, EventArgs.Empty); } private void RecreateCachedElements() { if (CachedElements != null) { CachedElements = new TextViewCachedElements(); } } private void OnChanging(object sender, DocumentChangeEventArgs e) { Redraw(e.Offset, e.RemovalLength); } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = AvaloniaProperty.Register<TextView, TextEditorOptions>("Options"); /// <summary> /// Gets/Sets the options used by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); if (Options.ShowColumnRulers) _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); else _columnRulerRenderer.SetRuler(null, ColumnRulerPen); UpdateBuiltinElementGeneratorsFromOptions(); Redraw(); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged); } if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region ElementGenerators+LineTransformers Properties private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators; /// <summary> /// Gets a collection where element generators can be registered. /// </summary> public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators; private void ElementGenerator_Added(VisualLineElementGenerator generator) { ConnectToTextView(generator); Redraw(); } private void ElementGenerator_Removed(VisualLineElementGenerator generator) { DisconnectFromTextView(generator); Redraw(); } private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers; /// <summary> /// Gets a collection where line transformers can be registered. /// </summary> public IList<IVisualLineTransformer> LineTransformers => _lineTransformers; private void LineTransformer_Added(IVisualLineTransformer lineTransformer) { ConnectToTextView(lineTransformer); Redraw(); } private void LineTransformer_Removed(IVisualLineTransformer lineTransformer) { DisconnectFromTextView(lineTransformer); Redraw(); } #endregion #region Builtin ElementGenerators // NewLineElementGenerator newLineElementGenerator; private SingleCharacterElementGenerator _singleCharacterElementGenerator; private LinkElementGenerator _linkElementGenerator; private MailLinkElementGenerator _mailLinkElementGenerator; private void UpdateBuiltinElementGeneratorsFromOptions() { var options = Options; // AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine); AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs); AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks); AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks); } private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand) where T : VisualLineElementGenerator, IBuiltinElementGenerator, new() { var hasGenerator = generator != null; if (hasGenerator != demand) { if (demand) { generator = new T(); ElementGenerators.Add(generator); } else { ElementGenerators.Remove(generator); generator = null; } } generator?.FetchOptions(Options); } #endregion #region Layers internal readonly TextLayer TextLayer; /// <summary> /// Gets the list of layers displayed in the text view. /// </summary> public LayerCollection Layers { get; } public sealed class LayerCollection : Collection<Control> { private readonly TextView _textView; public LayerCollection(TextView textView) { _textView = textView; } protected override void ClearItems() { foreach (var control in Items) { _textView.VisualChildren.Remove(control); } base.ClearItems(); _textView.LayersChanged(); } protected override void InsertItem(int index, Control item) { base.InsertItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } protected override void RemoveItem(int index) { base.RemoveItem(index); _textView.VisualChildren.RemoveAt(index); _textView.LayersChanged(); } protected override void SetItem(int index, Control item) { _textView.VisualChildren.Remove(Items[index]); base.SetItem(index, item); _textView.VisualChildren.Add(item); _textView.LayersChanged(); } } private void LayersChanged() { TextLayer.Index = Layers.IndexOf(TextLayer); } /// <summary> /// Inserts a new layer at a position specified relative to an existing layer. /// </summary> /// <param name="layer">The new layer to insert.</param> /// <param name="referencedLayer">The existing layer</param> /// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param> public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position) { if (layer == null) throw new ArgumentNullException(nameof(layer)); if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer)) throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer)); if (!Enum.IsDefined(typeof(LayerInsertionPosition), position)) throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition)); if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above) throw new InvalidOperationException("Cannot replace or insert below the background layer."); var newPosition = new LayerPosition(referencedLayer, position); LayerPosition.SetLayerPosition(layer, newPosition); for (var i = 0; i < Layers.Count; i++) { var p = LayerPosition.GetLayerPosition(Layers[i]); if (p != null) { if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace) { // found the referenced layer switch (position) { case LayerInsertionPosition.Below: Layers.Insert(i, layer); return; case LayerInsertionPosition.Above: Layers.Insert(i + 1, layer); return; case LayerInsertionPosition.Replace: Layers[i] = layer; return; } } else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above || p.KnownLayer > referencedLayer) { // we skipped the insertion position (referenced layer does not exist?) Layers.Insert(i, layer); return; } } } // inserting after all existing layers: Layers.Add(layer); } #endregion #region Inline object handling private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>(); /// <summary> /// Adds a new inline object. /// </summary> internal void AddInlineObject(InlineObjectRun inlineObject) { Debug.Assert(inlineObject.VisualLine != null); // Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping var alreadyAdded = false; for (var i = 0; i < _inlineObjects.Count; i++) { if (_inlineObjects[i].Element == inlineObject.Element) { RemoveInlineObjectRun(_inlineObjects[i], true); _inlineObjects.RemoveAt(i); alreadyAdded = true; break; } } _inlineObjects.Add(inlineObject); if (!alreadyAdded) { VisualChildren.Add(inlineObject.Element); ((ISetLogicalParent)inlineObject.Element).SetParent(this); } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); inlineObject.DesiredSize = inlineObject.Element.DesiredSize; } private void MeasureInlineObjects() { // As part of MeasureOverride(), re-measure the inline objects foreach (var inlineObject in _inlineObjects) { if (inlineObject.VisualLine.IsDisposed) { // Don't re-measure inline objects that are going to be removed anyways. // If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call. continue; } inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize)) { // the element changed size -> recreate its parent visual line inlineObject.DesiredSize = inlineObject.Element.DesiredSize; if (_allVisualLines.Remove(inlineObject.VisualLine)) { DisposeVisualLine(inlineObject.VisualLine); } } } } private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>(); private void RemoveInlineObjects(VisualLine visualLine) { // Delay removing inline objects: // A document change immediately invalidates affected visual lines, but it does not // cause an immediate redraw. // To prevent inline objects from flickering when they are recreated, we delay removing // inline objects until the next redraw. if (visualLine.HasInlineObjects) { _visualLinesWithOutstandingInlineObjects.Add(visualLine); } } /// <summary> /// Remove the inline objects that were marked for removal. /// </summary> private void RemoveInlineObjectsNow() { if (_visualLinesWithOutstandingInlineObjects.Count == 0) return; _inlineObjects.RemoveAll( ior => { if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine)) { RemoveInlineObjectRun(ior, false); return true; } return false; }); _visualLinesWithOutstandingInlineObjects.Clear(); } // Remove InlineObjectRun.Element from TextLayer. // Caller of RemoveInlineObjectRun will remove it from inlineObjects collection. private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement) { // TODO: Focus //if (!keepElement && ior.Element.IsKeyboardFocusWithin) //{ // // When the inline element that has the focus is removed, it will reset the // // focus to the main window without raising appropriate LostKeyboardFocus events. // // To work around this, we manually set focus to the next focusable parent. // UIElement element = this; // while (element != null && !element.Focusable) // { // element = VisualTreeHelper.GetParent(element) as UIElement; // } // if (element != null) // Keyboard.Focus(element); //} ior.VisualLine = null; if (!keepElement) VisualChildren.Remove(ior.Element); } #endregion #region Brushes /// <summary> /// NonPrintableCharacterBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128))); /// <summary> /// Gets/sets the Brush used for displaying non-printable characters. /// </summary> public IBrush NonPrintableCharacterBrush { get => GetValue(NonPrintableCharacterBrushProperty); set => SetValue(NonPrintableCharacterBrushProperty, value); } /// <summary> /// LinkTextForegroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue); /// <summary> /// Gets/sets the Brush used for displaying link texts. /// </summary> public IBrush LinkTextForegroundBrush { get => GetValue(LinkTextForegroundBrushProperty); set => SetValue(LinkTextForegroundBrushProperty, value); } /// <summary> /// LinkTextBackgroundBrush dependency property. /// </summary> public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty = AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent); /// <summary> /// Gets/sets the Brush used for the background of link texts. /// </summary> public IBrush LinkTextBackgroundBrush { get => GetValue(LinkTextBackgroundBrushProperty); set => SetValue(LinkTextBackgroundBrushProperty, value); } #endregion /// <summary> /// LinkTextUnderlinedBrush dependency property. /// </summary> public static readonly StyledProperty<bool> LinkTextUnderlineProperty = AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true); /// <summary> /// Gets/sets whether to underline link texts. /// </summary> /// <remarks> /// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied. /// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely. /// </remarks> public bool LinkTextUnderline { get => GetValue(LinkTextUnderlineProperty); set => SetValue(LinkTextUnderlineProperty, value); } #region Redraw methods / VisualLine invalidation /// <summary> /// Causes the text editor to regenerate all visual lines. /// </summary> public void Redraw() { VerifyAccess(); ClearVisualLines(); InvalidateMeasure(); } /// <summary> /// Causes the text editor to regenerate the specified visual line. /// </summary> public void Redraw(VisualLine visualLine) { VerifyAccess(); if (_allVisualLines.Remove(visualLine)) { DisposeVisualLine(visualLine); InvalidateMeasure(); } } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// </summary> public void Redraw(int offset, int length) { VerifyAccess(); var changedSomethingBeforeOrInLine = false; for (var i = 0; i < _allVisualLines.Count; i++) { var visualLine = _allVisualLines[i]; var lineStart = visualLine.FirstDocumentLine.Offset; var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength; if (offset <= lineEnd) { changedSomethingBeforeOrInLine = true; if (offset + length >= lineStart) { _allVisualLines.RemoveAt(i--); DisposeVisualLine(visualLine); } } } if (changedSomethingBeforeOrInLine) { // Repaint not only when something in visible area was changed, but also when anything in front of it // was changed. We might have to redraw the line number margin. Or the highlighting changed. // However, we'll try to reuse the existing VisualLines. InvalidateMeasure(); } } /// <summary> /// Causes a known layer to redraw. /// This method does not invalidate visual lines; /// use the <see cref="Redraw()"/> method to do that. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer", Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")] public void InvalidateLayer(KnownLayer knownLayer) { InvalidateMeasure(); } /// <summary> /// Causes the text editor to redraw all lines overlapping with the specified segment. /// Does nothing if segment is null. /// </summary> public void Redraw(ISegment segment) { if (segment != null) { Redraw(segment.Offset, segment.Length); } } /// <summary> /// Invalidates all visual lines. /// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure /// that the visual lines will be recreated. /// </summary> private void ClearVisualLines() { if (_allVisualLines.Count != 0) { foreach (var visualLine in _allVisualLines) { DisposeVisualLine(visualLine); } _allVisualLines.Clear(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); } } private void DisposeVisualLine(VisualLine visualLine) { if (_newVisualLines != null && _newVisualLines.Contains(visualLine)) { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } visualLine.Dispose(); RemoveInlineObjects(visualLine); } /// Returns null if the document line is outside the visible range. /// </summary> public VisualLine GetVisualLine(int documentLineNumber) { // TODO: EnsureVisualLines() ? foreach (var visualLine in _allVisualLines) { Debug.Assert(visualLine.IsDisposed == false); var start = visualLine.FirstDocumentLine.LineNumber; var end = visualLine.LastDocumentLine.LineNumber; if (documentLineNumber >= start && documentLineNumber <= end) return visualLine; } return null; } /// <summary> /// Gets the visual line that contains the document line with the specified number. /// If that line is outside the visible range, a new VisualLine for that document line is constructed. /// </summary> public VisualLine GetOrConstructVisualLine(DocumentLine documentLine) { if (documentLine == null) throw new ArgumentNullException("documentLine"); if (!this.Document.Lines.Contains(documentLine)) throw new InvalidOperationException("Line belongs to wrong document"); VerifyAccess(); VisualLine l = GetVisualLine(documentLine.LineNumber); if (l == null) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); while (_heightTree.GetIsCollapsed(documentLine.LineNumber)) { documentLine = documentLine.PreviousLine; } l = BuildVisualLine(documentLine, globalTextRunProperties, paragraphProperties, _elementGenerators.ToArray(), _lineTransformers.ToArray(), _lastAvailableSize); _allVisualLines.Add(l); // update all visual top values (building the line might have changed visual top of other lines due to word wrapping) foreach (var line in _allVisualLines) { line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine); } } return l; } #endregion #region Visual Lines (fields and properties) private List<VisualLine> _allVisualLines = new List<VisualLine>(); private ReadOnlyCollection<VisualLine> _visibleVisualLines; private double _clippedPixelsOnTop; private List<VisualLine> _newVisualLines; /// <summary> /// Gets the currently visible visual lines. /// </summary> /// <exception cref="VisualLinesInvalidException"> /// Gets thrown if there are invalid visual lines when this property is accessed. /// You can use the <see cref="VisualLinesValid"/> property to check for this case, /// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines /// when they are invalid. /// </exception> [SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public ReadOnlyCollection<VisualLine> VisualLines { get { if (_visibleVisualLines == null) throw new VisualLinesInvalidException(); return _visibleVisualLines; } } /// <summary> /// Gets whether the visual lines are valid. /// Will return false after a call to Redraw(). /// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/> /// if this property is <c>false</c>. /// </summary> public bool VisualLinesValid => _visibleVisualLines != null; /// <summary> /// Occurs when the TextView is about to be measured and will regenerate its visual lines. /// This event may be used to mark visual lines as invalid that would otherwise be reused. /// </summary> public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting; /// <summary> /// Occurs when the TextView was measured and changed its visual lines. /// </summary> public event EventHandler VisualLinesChanged; /// <summary> /// If the visual lines are invalid, creates new visual lines for the visible part /// of the document. /// If all visual lines are valid, this method does nothing. /// </summary> /// <exception cref="InvalidOperationException">The visual line build process is already running. /// It is not allowed to call this method during the construction of a visual line.</exception> public void EnsureVisualLines() { Dispatcher.UIThread.VerifyAccess(); if (_inMeasure) throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!"); if (!VisualLinesValid) { // increase priority for re-measure InvalidateMeasure(); // force immediate re-measure InvalidateVisual(); } // Sometimes we still have invalid lines after UpdateLayout - work around the problem // by calling MeasureOverride directly. if (!VisualLinesValid) { Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines"); MeasureOverride(_lastAvailableSize); } if (!VisualLinesValid) throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call"); } #endregion #region Measure /// <summary> /// Additonal amount that allows horizontal scrolling past the end of the longest line. /// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line. /// </summary> private const double AdditionalHorizontalScrollAmount = 3; private Size _lastAvailableSize; private bool _inMeasure; /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { // We don't support infinite available width, so we'll limit it to 32000 pixels. if (availableSize.Width > 32000) availableSize = availableSize.WithWidth(32000); if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width)) { ClearVisualLines(); } _lastAvailableSize = availableSize; foreach (var layer in Layers) { layer.Measure(availableSize); } InvalidateVisual(); // = InvalidateArrange+InvalidateRender MeasureInlineObjects(); double maxWidth; if (_document == null) { // no document -> create empty list of lines _allVisualLines = new List<VisualLine>(); _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray()); maxWidth = 0; } else { _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { _inMeasure = false; } } // remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor RemoveInlineObjectsNow(); } MeasureInlineObjects(); InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) { // HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after // scrolling to the very bottom. var minVisibleDocumentHeight = DefaultLineHeight; // increase the extend height to allow scrolling below the document extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight; } } _inMeasure = true; try { maxWidth = CreateAndMeasureVisualLines(_scrollViewport); } finally { VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight); } /// <summary> /// Build all VisualLines in the visible range. /// </summary> /// <returns>Width the longest line</returns> private double CreateAndMeasureVisualLines(Size availableSize) { TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties(); VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties); //Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset); var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y); // number of pixels clipped from the first visual line(s) _clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView); // clippedPixelsOnTop should be >= 0, except for floating point inaccurracy. Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon); _newVisualLines = new List<VisualLine>(); TextLayer.SetVisualLines(_visibleVisualLines); VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); var visualLine = GetVisualLine(nextLine.LineNumber) ?? BuildVisualLine(nextLine, globalTextRunProperties, paragraphProperties, elementGeneratorsArray, lineTransformersArray, availableSize); visualLine.VisualTop = _scrollOffset.Y + yPos; nextLine = visualLine.LastDocumentLine.NextLine; yPos += visualLine.Height; foreach (var textLine in visualLine.TextLines) { if (textLine.WidthIncludingTrailingWhitespace > maxWidth) maxWidth = textLine.WidthIncludingTrailingWhitespace; } _newVisualLines.Add(visualLine); } foreach (var line in _allVisualLines) { Debug.Assert(line.IsDisposed == false); if (!_newVisualLines.Contains(line)) DisposeVisualLine(line); } _allVisualLines = _newVisualLines; // visibleVisualLines = readonly copy of visual lines _visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray()); _newVisualLines = null; if (_allVisualLines.Any(line => line.IsDisposed)) { throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" + "This can happen when Redraw() is called during measure for lines " + "that are already constructed."); } return maxWidth; } #endregion #region BuildVisualLine private TextFormatter _formatter; internal TextViewCachedElements CachedElements; private TextRunProperties CreateGlobalTextRunProperties() { var p = new GlobalTextRunProperties(); p.typeface = this.CreateTypeface(); p.fontRenderingEmSize = FontSize; p.foregroundBrush = GetValue(TextElement.ForegroundProperty); ExtensionMethods.CheckIsFrozen(p.foregroundBrush); p.cultureInfo = CultureInfo.CurrentCulture; return p; } private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties) { return new VisualLineTextParagraphProperties { defaultTextRunProperties = defaultTextRunProperties, textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap, tabSize = Options.IndentationSize * WideSpaceWidth }; } private VisualLine BuildVisualLine(DocumentLine documentLine, TextRunProperties globalTextRunProperties, VisualLineTextParagraphProperties paragraphProperties, IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray, IReadOnlyList<IVisualLineTransformer> lineTransformersArray, Size availableSize) { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); //Debug.WriteLine("Building line " + documentLine.LineNumber); VisualLine visualLine = new VisualLine(this, documentLine); VisualLineTextSource textSource = new VisualLineTextSource(visualLine) { Document = _document, GlobalTextRunProperties = globalTextRunProperties, TextView = this }; visualLine.ConstructVisualElements(textSource, elementGeneratorsArray); if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine) { // Check whether the lines are collapsed correctly: double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine); double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine); if (!firstLinePos.IsClose(lastLinePos)) { for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++) { if (!_heightTree.GetIsCollapsed(i)) throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed."); } throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?"); } } { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker) { var textLine = _formatter.FormatLine( textSource, textOffset, availableSize.Width, paragraphProperties, lastLineBreak ); textLines.Add(textLine); textOffset += textLine.Length; // exit loop so that we don't do the indentation calculation if there's only a single line if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker) break; if (paragraphProperties.firstLineInParagraph) { paragraphProperties.firstLineInParagraph = false; TextEditorOptions options = this.Options; double indentation = 0; if (options.InheritWordWrapIndentation) { // determine indentation for next line: int indentVisualColumn = GetIndentationVisualColumn(visualLine); if (indentVisualColumn > 0 && indentVisualColumn < textOffset) { indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0)); } } indentation += options.WordWrapIndentation; // apply the calculated indentation unless it's more than half of the text editor size: if (indentation > 0 && indentation * 2 < availableSize.Width) paragraphProperties.indent = indentation; } lastLineBreak = textLine.TextLineBreak; } visualLine.SetTextLines(textLines); _heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height); return visualLine; } private static int GetIndentationVisualColumn(VisualLine visualLine) { if (visualLine.Elements.Count == 0) return 0; var column = 0; var elementIndex = 0; var element = visualLine.Elements[elementIndex]; while (element.IsWhitespace(column)) { column++; if (column == element.VisualColumn + element.VisualLength) { elementIndex++; if (elementIndex == visualLine.Elements.Count) break; element = visualLine.Elements[elementIndex]; } } return column; } #endregion #region Arrange /// <summary> /// Arrange implementation. /// </summary> protected override Size ArrangeOverride(Size finalSize) { EnsureVisualLines(); foreach (var layer in Layers) { layer.Arrange(new Rect(new Point(0, 0), finalSize)); } if (_document == null || _allVisualLines.Count == 0) return finalSize; // validate scroll position var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width) { newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width); } if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height) { newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Apply final view port and offset if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) InvalidateMeasure(); if (_visibleVisualLines != null) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visualLine in _visibleVisualLines) { var offset = 0; foreach (var textLine in visualLine.TextLines) { foreach (var span in textLine.TextRuns) { var inline = span as InlineObjectRun; if (inline?.VisualLine != null) { Debug.Assert(_inlineObjects.Contains(inline)); var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset)); newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); if (_visibleVisualLines != null) { } InvalidateCursorIfPointerWithinTextView(); return finalSize; } #endregion #region Render private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers; /// <summary> /// Gets the list of background renderers. /// </summary> public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers; private void BackgroundRenderer_Added(IBackgroundRenderer renderer) } } } InvalidateCursorIfPointerWithinTextView(); return finalSize; DisconnectFromTextView(renderer); InvalidateLayer(renderer.Layer); } /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (!VisualLinesValid) { return; } RenderBackground(drawingContext, KnownLayer.Background); foreach (var line in _visibleVisualLines) { IBrush currentBrush = null; var startVc = 0; var length = 0; foreach (var element in line.Elements) { if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush)) { if (currentBrush != null) { /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if(!VisualLinesValid) { return; } builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } startVc = element.VisualColumn; length = element.DocumentLength; currentBrush = element.BackgroundBrush; } else { length += element.VisualLength; } } if (currentBrush != null) { var builder = new BackgroundGeometryBuilder { AlignToWholePixels = true, CornerRadius = 3 }; foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length)) builder.AddRectangle(this, rect); var geometry = builder.CreateGeometry(); if (geometry != null) { drawingContext.DrawGeometry(currentBrush, null, geometry); } } } } internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer) { // this is necessary so hit-testing works properly and events get tunneled to the TextView. drawingContext.FillRectangle(Brushes.Transparent, Bounds); foreach (var bg in _backgroundRenderers) { if (bg.Layer == layer) { bg.Draw(this, drawingContext); } } } internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals) { var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop); foreach (var visual in visuals) { var t = visual.RenderTransform as TranslateTransform; if (t == null || t.X != pos.X || t.Y != pos.Y) { visual.RenderTransform = new TranslateTransform(pos.X, pos.Y); } pos = new Point(pos.X, pos.Y + visual.LineHeight); } } #endregion #region IScrollInfo implementation /// <summary> /// Size of the scroll, in pixels. /// </summary> private Size _scrollExtent; /// <summary> /// Offset of the scroll position. /// </summary> private Vector _scrollOffset; /// <summary> /// Size of the viewport. /// </summary> private Size _scrollViewport; private void ClearScrollData() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } private void ClearScrollData() { SetScrollData(new Size(), new Size()); _scrollOffset = new Vector(); } public bool SetScrollData(Size viewport, Size extent) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent))) { _scrollViewport = viewport; _scrollExtent = extent; return true; } return false; } private bool _canVerticallyScroll = true; private bool _canHorizontallyScroll; /// <summary> /// Gets the horizontal scroll offset. private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) { vector = new Vector(0, vector.Y); } if (!_canVerticallyScroll) { vector = new Vector(vector.X, 0); } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; /// </summary> public event EventHandler ScrollOffsetChanged; internal void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) vector = new Vector(0, vector.Y); if (!_canVerticallyScroll) vector = new Vector(vector.X, 0); if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); InvalidateMeasure(); } } CalculateDefaultTextMetrics(); return _wideSpaceWidth; } } /// <summary> /// Gets the default line height. This is the height of an empty line or a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different line height. /// </summary> public double DefaultLineHeight { get { CalculateDefaultTextMetrics(); return _defaultLineHeight; } } /// <summary> /// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/> /// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text. /// Lines that include formatted text or custom UI elements may have a different baseline. /// </summary> public double DefaultBaseline { get { CalculateDefaultTextMetrics(); return _defaultBaseline; } } private void InvalidateDefaultTextMetrics() { _defaultTextMetricsValid = false; if (_heightTree != null) { // calculate immediately so that height tree gets updated CalculateDefaultTextMetrics(); } } private void CalculateDefaultTextMetrics() { if (_defaultTextMetricsValid) return; _defaultTextMetricsValid = true; if (_formatter != null) { var textRunProperties = CreateGlobalTextRunProperties(); var line = _formatter.FormatLine( new SimpleTextSource("x", textRunProperties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties }, null); _wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace); _defaultBaseline = Math.Max(1, line.Baseline); _defaultLineHeight = Math.Max(1, line.Height); } else { _wideSpaceWidth = FontSize / 2; _defaultBaseline = FontSize; _defaultLineHeight = FontSize + 3; } // Update heightTree.DefaultLineHeight, if a document is loaded. if (_heightTree != null) _heightTree.DefaultLineHeight = _defaultLineHeight; } private static double ValidateVisualOffset(double offset) { if (double.IsNaN(offset)) throw new ArgumentException("offset must not be NaN"); if (offset < 0) return 0; return offset; } /// <summary> /// Scrolls the text view so that the specified rectangle gets visible. /// </summary> public virtual void MakeVisible(Rect rectangle) { var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y, _scrollViewport.Width, _scrollViewport.Height); var newScrollOffsetX = _scrollOffset.X; var newScrollOffsetY = _scrollOffset.Y; if (rectangle.X < visibleRectangle.X) { if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.X + rectangle.Width / 2; } else { newScrollOffsetX = rectangle.X; } } else if (rectangle.Right > visibleRectangle.Right) { newScrollOffsetX = rectangle.Right - _scrollViewport.Width; } if (rectangle.Y < visibleRectangle.Y) { if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Y + rectangle.Height / 2; } else { newScrollOffsetY = rectangle.Y; } } else if (rectangle.Bottom > visibleRectangle.Bottom) { newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height; } newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX); newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY); var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY); if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); OnScrollChange(); InvalidateMeasure(); } } #endregion #region Visual element pointer handling [ThreadStatic] private static bool _invalidCursor; //private VisualLineElement _currentHoveredElement; /// <summary> if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); InvalidateMeasure(DispatcherPriority.Normal); } } Dispatcher.UIThread.InvokeAsync( delegate { _invalidCursor = false; //MouseDevice.Instance.UpdateCursor(); }, DispatcherPriority.Background // fixes issue #288 ); } } internal void InvalidateCursorIfPointerWithinTextView() { // Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view. // Unnecessary updates may cause the mouse pointer to flicker // (e.g. if it is over a window border, it blinks between Resize and Normal) if (IsPointerOver) { InvalidateCursor(); } } protected override void OnPointerMoved(PointerEventArgs e) { base.OnPointerMoved(e); //var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); //// Change back to default if hover on a different element //if (_currentHoveredElement != element) //{ // Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor // _currentHoveredElement = element; //} //element?.OnQueryCursor(e); } protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerPressed(e); } } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (!e.Handled) { EnsureVisualLines(); var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset); element?.OnPointerReleased(e); } } #endregion #region Getting elements from Visual Position /// <summary> /// Gets the visual line at the specified document position (relative to start of document). /// Returns null if there is no visual line for the position (e.g. the position is outside the visible /// text area). /// </summary> public VisualLine GetVisualLineFromVisualTop(double visualTop) { // TODO: change this method to also work outside the visible range - // required to make GetPosition work as expected! EnsureVisualLines(); foreach (var vl in VisualLines) { if (visualTop < vl.VisualTop) continue; if (visualTop < vl.VisualTop + vl.Height) return vl; } return null; } /// <summary> /// Gets the visual top position (relative to start of document) from a document line number. /// </summary> public double GetVisualTopByDocumentLine(int line) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line)); } private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition) { var vl = GetVisualLineFromVisualTop(visualPosition.Y); if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) #region Visual Position <-> TextViewPosition /// <summary> /// Gets the visual position from a text view position. /// </summary> /// <param name="position">The text view position.</param> /// <param name="yPositionMode">The mode how to retrieve the Y position.</param> /// <returns>The position in device-independent pixels relative /// to the top left corner of the document.</returns> public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var documentLine = Document.GetLineByNumber(position.Line); var visualLine = GetOrConstructVisualLine(documentLine); var visualColumn = position.VisualColumn; if (visualColumn < 0) { var offset = documentLine.Offset + position.Column - 1; visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset); } return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is within a character, it is rounded to the next character boundary. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPosition(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace); } /// <summary> /// Gets the text view position from the specified visual position. /// If the position is inside a character, the position in front of the character is returned. /// </summary> /// <param name="visualPosition">The position in device-independent pixels relative /// to the top left corner of the document.</param> /// <returns>The logical position, or null if the position is outside the document.</returns> public TextViewPosition? GetPositionFloor(Point visualPosition) { VerifyAccess(); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); var line = GetVisualLineFromVisualTop(visualPosition.Y); return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace); } #endregion #region Service Provider /// <summary> /// Gets a service container used to associate services with the text view. /// </summary> internal IServiceContainer Services { get; } = new ServiceContainer(); /// <summary> /// Retrieves a service from the text view. /// If the service is not found in the <see cref="Services"/> container, /// this method will also look for it in the current document's service provider. /// </summary> public virtual object GetService(Type serviceType) { var instance = Services.GetService(serviceType); if (instance == null && _document != null) { instance = _document.ServiceProvider.GetService(serviceType); } return instance; } private void ConnectToTextView(object obj) { var c = obj as ITextViewConnect; c?.AddToTextView(this); } private void DisconnectFromTextView(object obj) { var c = obj as ITextViewConnect; c?.RemoveFromTextView(this); } #endregion #region PointerHover /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel, typeof(TextView)); /// <summary> /// The PointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble, typeof(TextView)); /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHover { add => AddHandler(PreviewPointerHoverEvent, value); remove => RemoveHandler(PreviewPointerHoverEvent, value); } /// <summary> /// Occurs when the pointer has hovered over a fixed location for some time. /// </summary> public event EventHandler<PointerEventArgs> PointerHover { add => AddHandler(PointerHoverEvent, value); remove => RemoveHandler(PointerHoverEvent, value); } /// <summary> /// Occurs when the pointe had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped { add => AddHandler(PreviewPointerHoverStoppedEvent, value); remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value); } /// <summary> /// Occurs when the pointer had previously hovered but now started moving again. /// </summary> public event EventHandler<PointerEventArgs> PointerHoverStopped { add => AddHandler(PointerHoverStoppedEvent, value); remove => RemoveHandler(PointerHoverStoppedEvent, value); } private readonly PointerHoverLogic _hoverLogic; private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent) { e.RoutedEvent = tunnelingEvent; RaiseEvent(e); e.RoutedEvent = bubblingEvent; RaiseEvent(e); } #endregion /// <summary> /// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden /// and not used to start the generation of a <see cref="VisualLine"/>. /// </summary> /// <remarks> /// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span /// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding /// <see cref="VisualLineElementGenerator"/>. /// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>. /// /// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines /// N+1 to M. Do not collapse line N itself. /// /// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the /// <see cref="CollapsedLineSection"/> returned from this method. /// </remarks> public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.CollapseText(start, end); } /// <summary> /// Gets the height of the document. /// </summary> public double DocumentHeight => _heightTree?.TotalHeight ?? 0; /// <summary> /// Gets the document line at the specified visual position. /// </summary> public DocumentLine GetDocumentLineByVisualTop(double visualTop) { VerifyAccess(); if (_heightTree == null) throw ThrowUtil.NoDocumentAssigned(); return _heightTree.GetLineByVisualPosition(visualTop); } /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == TemplatedControl.ForegroundProperty || change.Property == NonPrintableCharacterBrushProperty || change.Property == LinkTextBackgroundBrushProperty || change.Property == LinkTextForegroundBrushProperty || change.Property == LinkTextUnderlineProperty) { // changing brushes requires recreating the cached elements RecreateCachedElements(); Redraw(); } if (change.Property == TemplatedControl.FontFamilyProperty || change.Property == TemplatedControl.FontSizeProperty || change.Property == TemplatedControl.FontStyleProperty || change.Property == TemplatedControl.FontWeightProperty) { // changing font properties requires recreating cached elements RecreateCachedElements(); // and we need to re-measure the font metrics: InvalidateDefaultTextMetrics(); Redraw(); } if (change.Property == ColumnRulerPenProperty) { _columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen); } if (change.Property == CurrentLineBorderProperty) { _currentLineHighlighRenderer.BorderPen = CurrentLineBorder; } if (change.Property == CurrentLineBackgroundProperty) { _currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground; } } /// <summary> /// The pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRulers"/> /// </summary> public static readonly StyledProperty<IPen> ColumnRulerPenProperty = AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128)))); private static ImmutablePen CreateFrozenPen(IBrush brush) { var pen = new ImmutablePen(brush?.ToImmutable()); return pen; } bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) { if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) { return false; } // TODO: // Convert rectangle into our coordinate space. //var childTransform = target.TransformToVisual(this); //rectangle = childTransform.Value(rectangle); return pen; } /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> set => SetValue(ColumnRulerPenProperty, value); } /// <summary> /// The <see cref="CurrentLineBackground"/> property. /// </summary> public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty = AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground"); /// <summary> /// Gets/Sets the background brush used by current line highlighter. /// </summary> public IBrush CurrentLineBackground { get => GetValue(CurrentLineBackgroundProperty); set => SetValue(CurrentLineBackgroundProperty, value); } /// <summary> /// The <see cref="CurrentLineBorder"/> property. /// </summary> public static readonly StyledProperty<IPen> CurrentLineBorderProperty = AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder"); /// <summary> /// Gets/Sets the background brush used for the current line. /// </summary> public IPen CurrentLineBorder { get => GetValue(CurrentLineBorderProperty); set => SetValue(CurrentLineBorderProperty, value); } /// <summary> /// Gets/Sets highlighted line number. /// </summary> public int HighlightedLine { get => _currentLineHighlighRenderer.Line; set => _currentLineHighlighRenderer.Line = value; } /// <summary> /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; } } <MSG> Fix horizontal scroll <DFF> @@ -32,6 +32,7 @@ using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; +using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Text; @@ -48,7 +49,7 @@ namespace AvaloniaEdit.Rendering /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")] - public class TextView : Control, ITextEditorComponent + public class TextView : Control, ITextEditorComponent, ILogicalScrollable { #region Constructor static TextView() @@ -724,7 +725,7 @@ namespace AvaloniaEdit.Rendering { throw new ArgumentException("Cannot dispose visual line because it is in construction!"); } - + visualLine.Dispose(); RemoveInlineObjects(visualLine); } @@ -919,7 +920,8 @@ namespace AvaloniaEdit.Rendering } MeasureInlineObjects(); - InvalidateVisual(); // = InvalidateArrange+InvalidateRender + // TODO: is this needed? + //InvalidateVisual(); // = InvalidateArrange+InvalidateRender double maxWidth; if (_document == null) @@ -934,7 +936,7 @@ namespace AvaloniaEdit.Rendering _inMeasure = true; try { - maxWidth = CreateAndMeasureVisualLines(_scrollViewport); + maxWidth = CreateAndMeasureVisualLines(availableSize); } finally { @@ -964,6 +966,10 @@ namespace AvaloniaEdit.Rendering TextLayer.SetVisualLines(_visibleVisualLines); + SetScrollData(availableSize, + new Size(maxWidth, heightTreeHeight), + _scrollOffset); + VisualLinesChanged?.Invoke(this, EventArgs.Empty); return new Size(Math.Min(availableSize.Width, maxWidth), Math.Min(availableSize.Height, heightTreeHeight)); @@ -1076,7 +1082,7 @@ namespace AvaloniaEdit.Rendering { if (_heightTree.GetIsCollapsed(documentLine.LineNumber)) throw new InvalidOperationException("Trying to build visual line from collapsed line"); - + var visualLine = new VisualLine(this, documentLine); var textSource = new VisualLineTextSource(visualLine) { @@ -1201,7 +1207,10 @@ namespace AvaloniaEdit.Rendering newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height); } - // Debug.WriteLine("Arrange finalSize=" + finalSize + ", scrollOffset=" + _scrollOffset); + if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY))) + { + InvalidateMeasure(DispatcherPriority.Normal); + } if (_visibleVisualLines != null) { @@ -1226,6 +1235,7 @@ namespace AvaloniaEdit.Rendering } } } + InvalidateCursorIfPointerWithinTextView(); return finalSize; @@ -1256,7 +1266,7 @@ namespace AvaloniaEdit.Rendering /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { - if(!VisualLinesValid) + if (!VisualLinesValid) { return; } @@ -1358,25 +1368,33 @@ namespace AvaloniaEdit.Rendering private void ClearScrollData() { - SetScrollData(new Size(), new Size()); - _scrollOffset = new Vector(); + SetScrollData(new Size(), new Size(), new Vector()); } - public bool SetScrollData(Size viewport, Size extent) + private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) - && extent.IsClose(_scrollExtent))) + && extent.IsClose(_scrollExtent) + && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; + SetScrollOffset(offset); + OnScrollChange(); return true; } + return false; } + private void OnScrollChange() + { + ((ILogicalScrollable)this).InvalidateScroll?.Invoke(); + } + private bool _canVerticallyScroll = true; - private bool _canHorizontallyScroll; + private bool _canHorizontallyScroll = true; /// <summary> /// Gets the horizontal scroll offset. @@ -1398,19 +1416,22 @@ namespace AvaloniaEdit.Rendering /// </summary> public event EventHandler ScrollOffsetChanged; - internal void SetScrollOffset(Vector vector) + private void SetScrollOffset(Vector vector) { if (!_canHorizontallyScroll) + { vector = new Vector(0, vector.Y); + } + if (!_canVerticallyScroll) + { vector = new Vector(vector.X, 0); + } if (!_scrollOffset.IsClose(vector)) { _scrollOffset = vector; ScrollOffsetChanged?.Invoke(this, EventArgs.Empty); - - InvalidateMeasure(); } } @@ -1555,6 +1576,7 @@ namespace AvaloniaEdit.Rendering if (!_scrollOffset.IsClose(newScrollOffset)) { SetScrollOffset(newScrollOffset); + OnScrollChange(); InvalidateMeasure(DispatcherPriority.Normal); } } @@ -1665,7 +1687,7 @@ namespace AvaloniaEdit.Rendering if (vl != null) { var column = vl.GetVisualColumnFloor(visualPosition); - + foreach (var element in vl.Elements) { if (element.VisualColumn + element.VisualLength <= column) @@ -1946,6 +1968,28 @@ namespace AvaloniaEdit.Rendering return pen; } + bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle) + { + if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target)) + { + return false; + } + + // TODO: + // Convert rectangle into our coordinate space. + //var childTransform = target.TransformToVisual(this); + //rectangle = childTransform.Value(rectangle); + + MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y)); + + return true; + } + + IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) + { + return null; + } + /// <summary> /// Gets/Sets the pen used to draw the column ruler. /// <seealso cref="TextEditorOptions.ShowColumnRuler"/> @@ -1999,5 +2043,71 @@ namespace AvaloniaEdit.Rendering /// Empty line selection width. /// </summary> public virtual double EmptyLineSelectionWidth => 1; + + bool ILogicalScrollable.CanHorizontallyScroll + { + get => _canHorizontallyScroll; + set + { + if (_canHorizontallyScroll != value) + { + _canHorizontallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.CanVerticallyScroll + { + get => _canVerticallyScroll; + set + { + if (_canVerticallyScroll != value) + { + _canVerticallyScroll = value; + ClearVisualLines(); + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + + bool ILogicalScrollable.IsLogicalScrollEnabled => true; + + Action ILogicalScrollable.InvalidateScroll { get; set; } + + Size ILogicalScrollable.ScrollSize => new Size(10, 10); + + Size ILogicalScrollable.PageScrollSize => new Size(10, 10); + + Size IScrollable.Extent => _scrollExtent; + + Vector IScrollable.Offset + { + get => _scrollOffset; + set + { + value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y)); + var isX = !_scrollOffset.X.IsClose(value.X); + var isY = !_scrollOffset.Y.IsClose(value.Y); + if (isX || isY) + { + SetScrollOffset(value); + + if (isX) + { + InvalidateVisual(); + TextLayer.InvalidateVisual(); + } + + if (isY) + { + InvalidateMeasure(DispatcherPriority.Normal); + } + } + } + } + + Size IScrollable.Viewport => _scrollViewport; } }
126
Fix horizontal scroll
16
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062012
<NME> FoldingManager.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Threading; namespace AvaloniaEdit.Folding { /// <summary> /// Stores a list of foldings for a specific TextView and TextDocument. /// </summary> public class FoldingManager { internal TextDocument Document { get; } internal List<TextView> TextViews { get; } = new List<TextView>(); private readonly TextSegmentCollection<FoldingSection> _foldings; private bool _isFirstUpdate = true; #region Constructor /// <summary> /// Creates a new FoldingManager instance. /// </summary> public FoldingManager(TextDocument document) { Document = document ?? throw new ArgumentNullException(nameof(document)); _foldings = new TextSegmentCollection<FoldingSection>(); Dispatcher.UIThread.VerifyAccess(); TextDocumentWeakEventManager.Changed.AddHandler(document, OnDocumentChanged); } #endregion #region ReceiveWeakEvent private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { _foldings.UpdateOffsets(e); var newEndOffset = e.Offset + e.InsertionLength; // extend end offset to the end of the line (including delimiter) var endLine = Document.GetLineByOffset(newEndOffset); newEndOffset = endLine.Offset + endLine.TotalLength; foreach (var affectedFolding in _foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) { if (affectedFolding.Length == 0) { RemoveFolding(affectedFolding); } else { affectedFolding.ValidateCollapsedLineSections(); } } } #endregion #region Manage TextViews internal void AddToTextView(TextView textView) { if (textView == null || TextViews.Contains(textView)) throw new ArgumentException(); TextViews.Add(textView); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { Array.Resize(ref fs.CollapsedSections, TextViews.Count); fs.ValidateCollapsedLineSections(); } } } internal void RemoveFromTextView(TextView textView) { var pos = TextViews.IndexOf(textView); if (pos < 0) throw new ArgumentException(); TextViews.RemoveAt(pos); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { var c = new CollapsedLineSection[TextViews.Count]; Array.Copy(fs.CollapsedSections, 0, c, 0, pos); fs.CollapsedSections[pos].Uncollapse(); Array.Copy(fs.CollapsedSections, pos + 1, c, pos, c.Length - pos); fs.CollapsedSections = c; } } } internal void Redraw() { foreach (var textView in TextViews) textView.Redraw(); } internal void Redraw(FoldingSection fs) { foreach (var textView in TextViews) textView.Redraw(fs); } #endregion #region Create / Remove / Clear /// <summary> /// Creates a folding for the specified text section. /// </summary> public FoldingSection CreateFolding(int startOffset, int endOffset) { if (startOffset >= endOffset) throw new ArgumentException("startOffset must be less than endOffset"); if (startOffset < 0 || endOffset > Document.TextLength) throw new ArgumentException("Folding must be within document boundary"); var fs = new FoldingSection(this, startOffset, endOffset); _foldings.Add(fs); Redraw(fs); return fs; } /// <summary> /// Removes a folding section from this manager. /// </summary> public void RemoveFolding(FoldingSection fs) { if (fs == null) throw new ArgumentNullException(nameof(fs)); fs.IsFolded = false; _foldings.Remove(fs); Redraw(fs); } /// <summary> /// Removes all folding sections. /// </summary> public void Clear() { Dispatcher.UIThread.VerifyAccess(); foreach (var s in _foldings) s.IsFolded = false; _foldings.Clear(); Redraw(); } #endregion #region Get...Folding /// <summary> /// Gets all foldings in this manager. /// The foldings are returned sorted by start offset; /// for multiple foldings at the same offset the order is undefined. /// </summary> public IEnumerable<FoldingSection> AllFoldings => _foldings; /// <summary> /// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts. /// Returns -1 if there are no foldings after <paramref name="startOffset"/>. /// </summary> public int GetNextFoldedFoldingStart(int startOffset) { var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && !fs.IsFolded) fs = _foldings.GetNextSegment(fs); return fs?.StartOffset ?? -1; } /// <summary> /// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to /// <paramref name="startOffset"/>. /// Returns null if there are no foldings after <paramref name="startOffset"/>. /// </summary> public FoldingSection GetNextFolding(int startOffset) { // TODO: returns the longest folding instead of any folding at the first position after startOffset return _foldings.FindFirstSegmentWithStartAfter(startOffset); } /// <summary> /// Gets all foldings that start exactly at <paramref name="startOffset"/>. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset) { var result = new List<FoldingSection>(); var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && fs.StartOffset == startOffset) { result.Add(fs); fs = _foldings.GetNextSegment(fs); } return new ReadOnlyCollection<FoldingSection>(result); } /// <summary> /// Gets all foldings that contain <paramref name="offset" />. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset) { return _foldings.FindSegmentsContaining(offset); } #endregion #region UpdateFoldings /// <summary> /// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings. /// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state /// (<see cref="FoldingSection.IsFolded"/>) for existing foldings. /// </summary> /// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param> /// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after /// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>. /// Use -1 for this parameter if there were no parse errors.</param> public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset) { if (newFoldings == null) throw new ArgumentNullException(nameof(newFoldings)); if (firstErrorOffset < 0) firstErrorOffset = int.MaxValue; var oldFoldings = AllFoldings.ToArray(); var oldFoldingIndex = 0; var previousStartOffset = 0; // merge new foldings into old foldings so that sections keep being collapsed // both oldFoldings and newFoldings are sorted by start offset foreach (var newFolding in newFoldings) { // ensure newFoldings are sorted correctly if (newFolding.StartOffset < previousStartOffset) throw new ArgumentException("newFoldings must be sorted by start offset"); previousStartOffset = newFolding.StartOffset; if (newFolding.StartOffset == newFolding.EndOffset) continue; // ignore zero-length foldings // remove old foldings that were skipped while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) { RemoveFolding(oldFoldings[oldFoldingIndex++]); } FoldingSection section; // reuse current folding if its matching: if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) { section = oldFoldings[oldFoldingIndex++]; section.Length = newFolding.EndOffset - newFolding.StartOffset; } else { // no matching current folding; create a new one: section = CreateFolding(newFolding.StartOffset, newFolding.EndOffset); // auto-close #regions only when opening the document if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) { var oldSection = oldFoldings[oldFoldingIndex++]; if (oldSection.StartOffset >= firstErrorOffset) break; RemoveFolding(oldSection); } } #endregion #region Install /// <summary> /// Adds Folding support to the specified text area. /// Warning: The folding manager is only valid for the text area's current document. The folding manager /// must be uninstalled before the text area is bound to a different document. /// </summary> /// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns> public static FoldingManager Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); return new FoldingManagerInstallation(textArea); } /// <summary> /// Uninstalls the folding manager. /// </summary> /// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception> public static void Uninstall(FoldingManager manager) { if (manager == null) throw new ArgumentNullException(nameof(manager)); if (manager is FoldingManagerInstallation installation) { installation.Uninstall(); } else { throw new ArgumentException("FoldingManager was not created using FoldingManager.Install"); } } private sealed class FoldingManagerInstallation : FoldingManager { private TextArea _textArea; private FoldingMargin _margin; private FoldingElementGenerator _generator; public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document) { _textArea = textArea; _margin = new FoldingMargin { FoldingManager = this }; _generator = new FoldingElementGenerator { FoldingManager = this }; textArea.LeftMargins.Add(_margin); textArea.TextView.Services.AddService(typeof(FoldingManager), this); // HACK: folding only works correctly when it has highest priority textArea.TextView.ElementGenerators.Insert(0, _generator); textArea.Caret.PositionChanged += TextArea_Caret_PositionChanged; } /* void DemoMode() { foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm }; foldingMargin = new FoldingMargin { FoldingManager = fm }; foldingMarginBorder = new Border { Child = foldingMargin, Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0) }; foldingMarginBorder.SizeChanged += UpdateTextViewClip; textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator); textEditor.TextArea.LeftMargins.Add(foldingMarginBorder); } void UpdateTextViewClip(object sender, SizeChangedEventArgs e) { textEditor.TextArea.TextView.Clip = new RectangleGeometry( new Rect(-foldingMarginBorder.ActualWidth, 0, textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth, textEditor.TextArea.TextView.ActualHeight)); } */ public void Uninstall() { Clear(); if (_textArea != null) { _textArea.Caret.PositionChanged -= TextArea_Caret_PositionChanged; _textArea.LeftMargins.Remove(_margin); _textArea.TextView.ElementGenerators.Remove(_generator); _textArea.TextView.Services.RemoveService(typeof(FoldingManager)); _margin = null; _generator = null; _textArea = null; } } private void TextArea_Caret_PositionChanged(object sender, EventArgs e) { // Expand Foldings when Caret is moved into them. var caretOffset = _textArea.Caret.Offset; foreach (var s in GetFoldingsContaining(caretOffset)) { if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) { s.IsFolded = false; } } } } #endregion } } <MSG> Fix only first fold is preserved when updating foldings #110 https://github.com/icsharpcode/AvalonEdit/pull/110 <DFF> @@ -272,12 +272,12 @@ namespace AvaloniaEdit.Folding if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; - _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } + _isFirstUpdate = false; // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) {
1
Fix only first fold is preserved when updating foldings #110
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062013
<NME> FoldingManager.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Threading; namespace AvaloniaEdit.Folding { /// <summary> /// Stores a list of foldings for a specific TextView and TextDocument. /// </summary> public class FoldingManager { internal TextDocument Document { get; } internal List<TextView> TextViews { get; } = new List<TextView>(); private readonly TextSegmentCollection<FoldingSection> _foldings; private bool _isFirstUpdate = true; #region Constructor /// <summary> /// Creates a new FoldingManager instance. /// </summary> public FoldingManager(TextDocument document) { Document = document ?? throw new ArgumentNullException(nameof(document)); _foldings = new TextSegmentCollection<FoldingSection>(); Dispatcher.UIThread.VerifyAccess(); TextDocumentWeakEventManager.Changed.AddHandler(document, OnDocumentChanged); } #endregion #region ReceiveWeakEvent private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { _foldings.UpdateOffsets(e); var newEndOffset = e.Offset + e.InsertionLength; // extend end offset to the end of the line (including delimiter) var endLine = Document.GetLineByOffset(newEndOffset); newEndOffset = endLine.Offset + endLine.TotalLength; foreach (var affectedFolding in _foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) { if (affectedFolding.Length == 0) { RemoveFolding(affectedFolding); } else { affectedFolding.ValidateCollapsedLineSections(); } } } #endregion #region Manage TextViews internal void AddToTextView(TextView textView) { if (textView == null || TextViews.Contains(textView)) throw new ArgumentException(); TextViews.Add(textView); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { Array.Resize(ref fs.CollapsedSections, TextViews.Count); fs.ValidateCollapsedLineSections(); } } } internal void RemoveFromTextView(TextView textView) { var pos = TextViews.IndexOf(textView); if (pos < 0) throw new ArgumentException(); TextViews.RemoveAt(pos); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { var c = new CollapsedLineSection[TextViews.Count]; Array.Copy(fs.CollapsedSections, 0, c, 0, pos); fs.CollapsedSections[pos].Uncollapse(); Array.Copy(fs.CollapsedSections, pos + 1, c, pos, c.Length - pos); fs.CollapsedSections = c; } } } internal void Redraw() { foreach (var textView in TextViews) textView.Redraw(); } internal void Redraw(FoldingSection fs) { foreach (var textView in TextViews) textView.Redraw(fs); } #endregion #region Create / Remove / Clear /// <summary> /// Creates a folding for the specified text section. /// </summary> public FoldingSection CreateFolding(int startOffset, int endOffset) { if (startOffset >= endOffset) throw new ArgumentException("startOffset must be less than endOffset"); if (startOffset < 0 || endOffset > Document.TextLength) throw new ArgumentException("Folding must be within document boundary"); var fs = new FoldingSection(this, startOffset, endOffset); _foldings.Add(fs); Redraw(fs); return fs; } /// <summary> /// Removes a folding section from this manager. /// </summary> public void RemoveFolding(FoldingSection fs) { if (fs == null) throw new ArgumentNullException(nameof(fs)); fs.IsFolded = false; _foldings.Remove(fs); Redraw(fs); } /// <summary> /// Removes all folding sections. /// </summary> public void Clear() { Dispatcher.UIThread.VerifyAccess(); foreach (var s in _foldings) s.IsFolded = false; _foldings.Clear(); Redraw(); } #endregion #region Get...Folding /// <summary> /// Gets all foldings in this manager. /// The foldings are returned sorted by start offset; /// for multiple foldings at the same offset the order is undefined. /// </summary> public IEnumerable<FoldingSection> AllFoldings => _foldings; /// <summary> /// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts. /// Returns -1 if there are no foldings after <paramref name="startOffset"/>. /// </summary> public int GetNextFoldedFoldingStart(int startOffset) { var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && !fs.IsFolded) fs = _foldings.GetNextSegment(fs); return fs?.StartOffset ?? -1; } /// <summary> /// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to /// <paramref name="startOffset"/>. /// Returns null if there are no foldings after <paramref name="startOffset"/>. /// </summary> public FoldingSection GetNextFolding(int startOffset) { // TODO: returns the longest folding instead of any folding at the first position after startOffset return _foldings.FindFirstSegmentWithStartAfter(startOffset); } /// <summary> /// Gets all foldings that start exactly at <paramref name="startOffset"/>. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset) { var result = new List<FoldingSection>(); var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && fs.StartOffset == startOffset) { result.Add(fs); fs = _foldings.GetNextSegment(fs); } return new ReadOnlyCollection<FoldingSection>(result); } /// <summary> /// Gets all foldings that contain <paramref name="offset" />. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset) { return _foldings.FindSegmentsContaining(offset); } #endregion #region UpdateFoldings /// <summary> /// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings. /// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state /// (<see cref="FoldingSection.IsFolded"/>) for existing foldings. /// </summary> /// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param> /// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after /// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>. /// Use -1 for this parameter if there were no parse errors.</param> public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset) { if (newFoldings == null) throw new ArgumentNullException(nameof(newFoldings)); if (firstErrorOffset < 0) firstErrorOffset = int.MaxValue; var oldFoldings = AllFoldings.ToArray(); var oldFoldingIndex = 0; var previousStartOffset = 0; // merge new foldings into old foldings so that sections keep being collapsed // both oldFoldings and newFoldings are sorted by start offset foreach (var newFolding in newFoldings) { // ensure newFoldings are sorted correctly if (newFolding.StartOffset < previousStartOffset) throw new ArgumentException("newFoldings must be sorted by start offset"); previousStartOffset = newFolding.StartOffset; if (newFolding.StartOffset == newFolding.EndOffset) continue; // ignore zero-length foldings // remove old foldings that were skipped while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) { RemoveFolding(oldFoldings[oldFoldingIndex++]); } FoldingSection section; // reuse current folding if its matching: if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) { section = oldFoldings[oldFoldingIndex++]; section.Length = newFolding.EndOffset - newFolding.StartOffset; } else { // no matching current folding; create a new one: section = CreateFolding(newFolding.StartOffset, newFolding.EndOffset); // auto-close #regions only when opening the document if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) { var oldSection = oldFoldings[oldFoldingIndex++]; if (oldSection.StartOffset >= firstErrorOffset) break; RemoveFolding(oldSection); } } #endregion #region Install /// <summary> /// Adds Folding support to the specified text area. /// Warning: The folding manager is only valid for the text area's current document. The folding manager /// must be uninstalled before the text area is bound to a different document. /// </summary> /// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns> public static FoldingManager Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); return new FoldingManagerInstallation(textArea); } /// <summary> /// Uninstalls the folding manager. /// </summary> /// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception> public static void Uninstall(FoldingManager manager) { if (manager == null) throw new ArgumentNullException(nameof(manager)); if (manager is FoldingManagerInstallation installation) { installation.Uninstall(); } else { throw new ArgumentException("FoldingManager was not created using FoldingManager.Install"); } } private sealed class FoldingManagerInstallation : FoldingManager { private TextArea _textArea; private FoldingMargin _margin; private FoldingElementGenerator _generator; public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document) { _textArea = textArea; _margin = new FoldingMargin { FoldingManager = this }; _generator = new FoldingElementGenerator { FoldingManager = this }; textArea.LeftMargins.Add(_margin); textArea.TextView.Services.AddService(typeof(FoldingManager), this); // HACK: folding only works correctly when it has highest priority textArea.TextView.ElementGenerators.Insert(0, _generator); textArea.Caret.PositionChanged += TextArea_Caret_PositionChanged; } /* void DemoMode() { foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm }; foldingMargin = new FoldingMargin { FoldingManager = fm }; foldingMarginBorder = new Border { Child = foldingMargin, Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0) }; foldingMarginBorder.SizeChanged += UpdateTextViewClip; textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator); textEditor.TextArea.LeftMargins.Add(foldingMarginBorder); } void UpdateTextViewClip(object sender, SizeChangedEventArgs e) { textEditor.TextArea.TextView.Clip = new RectangleGeometry( new Rect(-foldingMarginBorder.ActualWidth, 0, textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth, textEditor.TextArea.TextView.ActualHeight)); } */ public void Uninstall() { Clear(); if (_textArea != null) { _textArea.Caret.PositionChanged -= TextArea_Caret_PositionChanged; _textArea.LeftMargins.Remove(_margin); _textArea.TextView.ElementGenerators.Remove(_generator); _textArea.TextView.Services.RemoveService(typeof(FoldingManager)); _margin = null; _generator = null; _textArea = null; } } private void TextArea_Caret_PositionChanged(object sender, EventArgs e) { // Expand Foldings when Caret is moved into them. var caretOffset = _textArea.Caret.Offset; foreach (var s in GetFoldingsContaining(caretOffset)) { if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) { s.IsFolded = false; } } } } #endregion } } <MSG> Fix only first fold is preserved when updating foldings #110 https://github.com/icsharpcode/AvalonEdit/pull/110 <DFF> @@ -272,12 +272,12 @@ namespace AvaloniaEdit.Folding if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; - _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } + _isFirstUpdate = false; // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) {
1
Fix only first fold is preserved when updating foldings #110
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062014
<NME> FoldingManager.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Threading; namespace AvaloniaEdit.Folding { /// <summary> /// Stores a list of foldings for a specific TextView and TextDocument. /// </summary> public class FoldingManager { internal TextDocument Document { get; } internal List<TextView> TextViews { get; } = new List<TextView>(); private readonly TextSegmentCollection<FoldingSection> _foldings; private bool _isFirstUpdate = true; #region Constructor /// <summary> /// Creates a new FoldingManager instance. /// </summary> public FoldingManager(TextDocument document) { Document = document ?? throw new ArgumentNullException(nameof(document)); _foldings = new TextSegmentCollection<FoldingSection>(); Dispatcher.UIThread.VerifyAccess(); TextDocumentWeakEventManager.Changed.AddHandler(document, OnDocumentChanged); } #endregion #region ReceiveWeakEvent private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { _foldings.UpdateOffsets(e); var newEndOffset = e.Offset + e.InsertionLength; // extend end offset to the end of the line (including delimiter) var endLine = Document.GetLineByOffset(newEndOffset); newEndOffset = endLine.Offset + endLine.TotalLength; foreach (var affectedFolding in _foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) { if (affectedFolding.Length == 0) { RemoveFolding(affectedFolding); } else { affectedFolding.ValidateCollapsedLineSections(); } } } #endregion #region Manage TextViews internal void AddToTextView(TextView textView) { if (textView == null || TextViews.Contains(textView)) throw new ArgumentException(); TextViews.Add(textView); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { Array.Resize(ref fs.CollapsedSections, TextViews.Count); fs.ValidateCollapsedLineSections(); } } } internal void RemoveFromTextView(TextView textView) { var pos = TextViews.IndexOf(textView); if (pos < 0) throw new ArgumentException(); TextViews.RemoveAt(pos); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { var c = new CollapsedLineSection[TextViews.Count]; Array.Copy(fs.CollapsedSections, 0, c, 0, pos); fs.CollapsedSections[pos].Uncollapse(); Array.Copy(fs.CollapsedSections, pos + 1, c, pos, c.Length - pos); fs.CollapsedSections = c; } } } internal void Redraw() { foreach (var textView in TextViews) textView.Redraw(); } internal void Redraw(FoldingSection fs) { foreach (var textView in TextViews) textView.Redraw(fs); } #endregion #region Create / Remove / Clear /// <summary> /// Creates a folding for the specified text section. /// </summary> public FoldingSection CreateFolding(int startOffset, int endOffset) { if (startOffset >= endOffset) throw new ArgumentException("startOffset must be less than endOffset"); if (startOffset < 0 || endOffset > Document.TextLength) throw new ArgumentException("Folding must be within document boundary"); var fs = new FoldingSection(this, startOffset, endOffset); _foldings.Add(fs); Redraw(fs); return fs; } /// <summary> /// Removes a folding section from this manager. /// </summary> public void RemoveFolding(FoldingSection fs) { if (fs == null) throw new ArgumentNullException(nameof(fs)); fs.IsFolded = false; _foldings.Remove(fs); Redraw(fs); } /// <summary> /// Removes all folding sections. /// </summary> public void Clear() { Dispatcher.UIThread.VerifyAccess(); foreach (var s in _foldings) s.IsFolded = false; _foldings.Clear(); Redraw(); } #endregion #region Get...Folding /// <summary> /// Gets all foldings in this manager. /// The foldings are returned sorted by start offset; /// for multiple foldings at the same offset the order is undefined. /// </summary> public IEnumerable<FoldingSection> AllFoldings => _foldings; /// <summary> /// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts. /// Returns -1 if there are no foldings after <paramref name="startOffset"/>. /// </summary> public int GetNextFoldedFoldingStart(int startOffset) { var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && !fs.IsFolded) fs = _foldings.GetNextSegment(fs); return fs?.StartOffset ?? -1; } /// <summary> /// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to /// <paramref name="startOffset"/>. /// Returns null if there are no foldings after <paramref name="startOffset"/>. /// </summary> public FoldingSection GetNextFolding(int startOffset) { // TODO: returns the longest folding instead of any folding at the first position after startOffset return _foldings.FindFirstSegmentWithStartAfter(startOffset); } /// <summary> /// Gets all foldings that start exactly at <paramref name="startOffset"/>. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset) { var result = new List<FoldingSection>(); var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && fs.StartOffset == startOffset) { result.Add(fs); fs = _foldings.GetNextSegment(fs); } return new ReadOnlyCollection<FoldingSection>(result); } /// <summary> /// Gets all foldings that contain <paramref name="offset" />. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset) { return _foldings.FindSegmentsContaining(offset); } #endregion #region UpdateFoldings /// <summary> /// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings. /// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state /// (<see cref="FoldingSection.IsFolded"/>) for existing foldings. /// </summary> /// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param> /// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after /// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>. /// Use -1 for this parameter if there were no parse errors.</param> public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset) { if (newFoldings == null) throw new ArgumentNullException(nameof(newFoldings)); if (firstErrorOffset < 0) firstErrorOffset = int.MaxValue; var oldFoldings = AllFoldings.ToArray(); var oldFoldingIndex = 0; var previousStartOffset = 0; // merge new foldings into old foldings so that sections keep being collapsed // both oldFoldings and newFoldings are sorted by start offset foreach (var newFolding in newFoldings) { // ensure newFoldings are sorted correctly if (newFolding.StartOffset < previousStartOffset) throw new ArgumentException("newFoldings must be sorted by start offset"); previousStartOffset = newFolding.StartOffset; if (newFolding.StartOffset == newFolding.EndOffset) continue; // ignore zero-length foldings // remove old foldings that were skipped while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) { RemoveFolding(oldFoldings[oldFoldingIndex++]); } FoldingSection section; // reuse current folding if its matching: if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) { section = oldFoldings[oldFoldingIndex++]; section.Length = newFolding.EndOffset - newFolding.StartOffset; } else { // no matching current folding; create a new one: section = CreateFolding(newFolding.StartOffset, newFolding.EndOffset); // auto-close #regions only when opening the document if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) { var oldSection = oldFoldings[oldFoldingIndex++]; if (oldSection.StartOffset >= firstErrorOffset) break; RemoveFolding(oldSection); } } #endregion #region Install /// <summary> /// Adds Folding support to the specified text area. /// Warning: The folding manager is only valid for the text area's current document. The folding manager /// must be uninstalled before the text area is bound to a different document. /// </summary> /// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns> public static FoldingManager Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); return new FoldingManagerInstallation(textArea); } /// <summary> /// Uninstalls the folding manager. /// </summary> /// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception> public static void Uninstall(FoldingManager manager) { if (manager == null) throw new ArgumentNullException(nameof(manager)); if (manager is FoldingManagerInstallation installation) { installation.Uninstall(); } else { throw new ArgumentException("FoldingManager was not created using FoldingManager.Install"); } } private sealed class FoldingManagerInstallation : FoldingManager { private TextArea _textArea; private FoldingMargin _margin; private FoldingElementGenerator _generator; public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document) { _textArea = textArea; _margin = new FoldingMargin { FoldingManager = this }; _generator = new FoldingElementGenerator { FoldingManager = this }; textArea.LeftMargins.Add(_margin); textArea.TextView.Services.AddService(typeof(FoldingManager), this); // HACK: folding only works correctly when it has highest priority textArea.TextView.ElementGenerators.Insert(0, _generator); textArea.Caret.PositionChanged += TextArea_Caret_PositionChanged; } /* void DemoMode() { foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm }; foldingMargin = new FoldingMargin { FoldingManager = fm }; foldingMarginBorder = new Border { Child = foldingMargin, Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0) }; foldingMarginBorder.SizeChanged += UpdateTextViewClip; textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator); textEditor.TextArea.LeftMargins.Add(foldingMarginBorder); } void UpdateTextViewClip(object sender, SizeChangedEventArgs e) { textEditor.TextArea.TextView.Clip = new RectangleGeometry( new Rect(-foldingMarginBorder.ActualWidth, 0, textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth, textEditor.TextArea.TextView.ActualHeight)); } */ public void Uninstall() { Clear(); if (_textArea != null) { _textArea.Caret.PositionChanged -= TextArea_Caret_PositionChanged; _textArea.LeftMargins.Remove(_margin); _textArea.TextView.ElementGenerators.Remove(_generator); _textArea.TextView.Services.RemoveService(typeof(FoldingManager)); _margin = null; _generator = null; _textArea = null; } } private void TextArea_Caret_PositionChanged(object sender, EventArgs e) { // Expand Foldings when Caret is moved into them. var caretOffset = _textArea.Caret.Offset; foreach (var s in GetFoldingsContaining(caretOffset)) { if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) { s.IsFolded = false; } } } } #endregion } } <MSG> Fix only first fold is preserved when updating foldings #110 https://github.com/icsharpcode/AvalonEdit/pull/110 <DFF> @@ -272,12 +272,12 @@ namespace AvaloniaEdit.Folding if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; - _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } + _isFirstUpdate = false; // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) {
1
Fix only first fold is preserved when updating foldings #110
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062015
<NME> FoldingManager.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Threading; namespace AvaloniaEdit.Folding { /// <summary> /// Stores a list of foldings for a specific TextView and TextDocument. /// </summary> public class FoldingManager { internal TextDocument Document { get; } internal List<TextView> TextViews { get; } = new List<TextView>(); private readonly TextSegmentCollection<FoldingSection> _foldings; private bool _isFirstUpdate = true; #region Constructor /// <summary> /// Creates a new FoldingManager instance. /// </summary> public FoldingManager(TextDocument document) { Document = document ?? throw new ArgumentNullException(nameof(document)); _foldings = new TextSegmentCollection<FoldingSection>(); Dispatcher.UIThread.VerifyAccess(); TextDocumentWeakEventManager.Changed.AddHandler(document, OnDocumentChanged); } #endregion #region ReceiveWeakEvent private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { _foldings.UpdateOffsets(e); var newEndOffset = e.Offset + e.InsertionLength; // extend end offset to the end of the line (including delimiter) var endLine = Document.GetLineByOffset(newEndOffset); newEndOffset = endLine.Offset + endLine.TotalLength; foreach (var affectedFolding in _foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) { if (affectedFolding.Length == 0) { RemoveFolding(affectedFolding); } else { affectedFolding.ValidateCollapsedLineSections(); } } } #endregion #region Manage TextViews internal void AddToTextView(TextView textView) { if (textView == null || TextViews.Contains(textView)) throw new ArgumentException(); TextViews.Add(textView); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { Array.Resize(ref fs.CollapsedSections, TextViews.Count); fs.ValidateCollapsedLineSections(); } } } internal void RemoveFromTextView(TextView textView) { var pos = TextViews.IndexOf(textView); if (pos < 0) throw new ArgumentException(); TextViews.RemoveAt(pos); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { var c = new CollapsedLineSection[TextViews.Count]; Array.Copy(fs.CollapsedSections, 0, c, 0, pos); fs.CollapsedSections[pos].Uncollapse(); Array.Copy(fs.CollapsedSections, pos + 1, c, pos, c.Length - pos); fs.CollapsedSections = c; } } } internal void Redraw() { foreach (var textView in TextViews) textView.Redraw(); } internal void Redraw(FoldingSection fs) { foreach (var textView in TextViews) textView.Redraw(fs); } #endregion #region Create / Remove / Clear /// <summary> /// Creates a folding for the specified text section. /// </summary> public FoldingSection CreateFolding(int startOffset, int endOffset) { if (startOffset >= endOffset) throw new ArgumentException("startOffset must be less than endOffset"); if (startOffset < 0 || endOffset > Document.TextLength) throw new ArgumentException("Folding must be within document boundary"); var fs = new FoldingSection(this, startOffset, endOffset); _foldings.Add(fs); Redraw(fs); return fs; } /// <summary> /// Removes a folding section from this manager. /// </summary> public void RemoveFolding(FoldingSection fs) { if (fs == null) throw new ArgumentNullException(nameof(fs)); fs.IsFolded = false; _foldings.Remove(fs); Redraw(fs); } /// <summary> /// Removes all folding sections. /// </summary> public void Clear() { Dispatcher.UIThread.VerifyAccess(); foreach (var s in _foldings) s.IsFolded = false; _foldings.Clear(); Redraw(); } #endregion #region Get...Folding /// <summary> /// Gets all foldings in this manager. /// The foldings are returned sorted by start offset; /// for multiple foldings at the same offset the order is undefined. /// </summary> public IEnumerable<FoldingSection> AllFoldings => _foldings; /// <summary> /// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts. /// Returns -1 if there are no foldings after <paramref name="startOffset"/>. /// </summary> public int GetNextFoldedFoldingStart(int startOffset) { var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && !fs.IsFolded) fs = _foldings.GetNextSegment(fs); return fs?.StartOffset ?? -1; } /// <summary> /// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to /// <paramref name="startOffset"/>. /// Returns null if there are no foldings after <paramref name="startOffset"/>. /// </summary> public FoldingSection GetNextFolding(int startOffset) { // TODO: returns the longest folding instead of any folding at the first position after startOffset return _foldings.FindFirstSegmentWithStartAfter(startOffset); } /// <summary> /// Gets all foldings that start exactly at <paramref name="startOffset"/>. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset) { var result = new List<FoldingSection>(); var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && fs.StartOffset == startOffset) { result.Add(fs); fs = _foldings.GetNextSegment(fs); } return new ReadOnlyCollection<FoldingSection>(result); } /// <summary> /// Gets all foldings that contain <paramref name="offset" />. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset) { return _foldings.FindSegmentsContaining(offset); } #endregion #region UpdateFoldings /// <summary> /// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings. /// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state /// (<see cref="FoldingSection.IsFolded"/>) for existing foldings. /// </summary> /// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param> /// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after /// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>. /// Use -1 for this parameter if there were no parse errors.</param> public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset) { if (newFoldings == null) throw new ArgumentNullException(nameof(newFoldings)); if (firstErrorOffset < 0) firstErrorOffset = int.MaxValue; var oldFoldings = AllFoldings.ToArray(); var oldFoldingIndex = 0; var previousStartOffset = 0; // merge new foldings into old foldings so that sections keep being collapsed // both oldFoldings and newFoldings are sorted by start offset foreach (var newFolding in newFoldings) { // ensure newFoldings are sorted correctly if (newFolding.StartOffset < previousStartOffset) throw new ArgumentException("newFoldings must be sorted by start offset"); previousStartOffset = newFolding.StartOffset; if (newFolding.StartOffset == newFolding.EndOffset) continue; // ignore zero-length foldings // remove old foldings that were skipped while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) { RemoveFolding(oldFoldings[oldFoldingIndex++]); } FoldingSection section; // reuse current folding if its matching: if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) { section = oldFoldings[oldFoldingIndex++]; section.Length = newFolding.EndOffset - newFolding.StartOffset; } else { // no matching current folding; create a new one: section = CreateFolding(newFolding.StartOffset, newFolding.EndOffset); // auto-close #regions only when opening the document if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) { var oldSection = oldFoldings[oldFoldingIndex++]; if (oldSection.StartOffset >= firstErrorOffset) break; RemoveFolding(oldSection); } } #endregion #region Install /// <summary> /// Adds Folding support to the specified text area. /// Warning: The folding manager is only valid for the text area's current document. The folding manager /// must be uninstalled before the text area is bound to a different document. /// </summary> /// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns> public static FoldingManager Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); return new FoldingManagerInstallation(textArea); } /// <summary> /// Uninstalls the folding manager. /// </summary> /// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception> public static void Uninstall(FoldingManager manager) { if (manager == null) throw new ArgumentNullException(nameof(manager)); if (manager is FoldingManagerInstallation installation) { installation.Uninstall(); } else { throw new ArgumentException("FoldingManager was not created using FoldingManager.Install"); } } private sealed class FoldingManagerInstallation : FoldingManager { private TextArea _textArea; private FoldingMargin _margin; private FoldingElementGenerator _generator; public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document) { _textArea = textArea; _margin = new FoldingMargin { FoldingManager = this }; _generator = new FoldingElementGenerator { FoldingManager = this }; textArea.LeftMargins.Add(_margin); textArea.TextView.Services.AddService(typeof(FoldingManager), this); // HACK: folding only works correctly when it has highest priority textArea.TextView.ElementGenerators.Insert(0, _generator); textArea.Caret.PositionChanged += TextArea_Caret_PositionChanged; } /* void DemoMode() { foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm }; foldingMargin = new FoldingMargin { FoldingManager = fm }; foldingMarginBorder = new Border { Child = foldingMargin, Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0) }; foldingMarginBorder.SizeChanged += UpdateTextViewClip; textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator); textEditor.TextArea.LeftMargins.Add(foldingMarginBorder); } void UpdateTextViewClip(object sender, SizeChangedEventArgs e) { textEditor.TextArea.TextView.Clip = new RectangleGeometry( new Rect(-foldingMarginBorder.ActualWidth, 0, textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth, textEditor.TextArea.TextView.ActualHeight)); } */ public void Uninstall() { Clear(); if (_textArea != null) { _textArea.Caret.PositionChanged -= TextArea_Caret_PositionChanged; _textArea.LeftMargins.Remove(_margin); _textArea.TextView.ElementGenerators.Remove(_generator); _textArea.TextView.Services.RemoveService(typeof(FoldingManager)); _margin = null; _generator = null; _textArea = null; } } private void TextArea_Caret_PositionChanged(object sender, EventArgs e) { // Expand Foldings when Caret is moved into them. var caretOffset = _textArea.Caret.Offset; foreach (var s in GetFoldingsContaining(caretOffset)) { if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) { s.IsFolded = false; } } } } #endregion } } <MSG> Fix only first fold is preserved when updating foldings #110 https://github.com/icsharpcode/AvalonEdit/pull/110 <DFF> @@ -272,12 +272,12 @@ namespace AvaloniaEdit.Folding if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; - _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } + _isFirstUpdate = false; // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) {
1
Fix only first fold is preserved when updating foldings #110
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062016
<NME> FoldingManager.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Threading; namespace AvaloniaEdit.Folding { /// <summary> /// Stores a list of foldings for a specific TextView and TextDocument. /// </summary> public class FoldingManager { internal TextDocument Document { get; } internal List<TextView> TextViews { get; } = new List<TextView>(); private readonly TextSegmentCollection<FoldingSection> _foldings; private bool _isFirstUpdate = true; #region Constructor /// <summary> /// Creates a new FoldingManager instance. /// </summary> public FoldingManager(TextDocument document) { Document = document ?? throw new ArgumentNullException(nameof(document)); _foldings = new TextSegmentCollection<FoldingSection>(); Dispatcher.UIThread.VerifyAccess(); TextDocumentWeakEventManager.Changed.AddHandler(document, OnDocumentChanged); } #endregion #region ReceiveWeakEvent private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { _foldings.UpdateOffsets(e); var newEndOffset = e.Offset + e.InsertionLength; // extend end offset to the end of the line (including delimiter) var endLine = Document.GetLineByOffset(newEndOffset); newEndOffset = endLine.Offset + endLine.TotalLength; foreach (var affectedFolding in _foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) { if (affectedFolding.Length == 0) { RemoveFolding(affectedFolding); } else { affectedFolding.ValidateCollapsedLineSections(); } } } #endregion #region Manage TextViews internal void AddToTextView(TextView textView) { if (textView == null || TextViews.Contains(textView)) throw new ArgumentException(); TextViews.Add(textView); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { Array.Resize(ref fs.CollapsedSections, TextViews.Count); fs.ValidateCollapsedLineSections(); } } } internal void RemoveFromTextView(TextView textView) { var pos = TextViews.IndexOf(textView); if (pos < 0) throw new ArgumentException(); TextViews.RemoveAt(pos); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { var c = new CollapsedLineSection[TextViews.Count]; Array.Copy(fs.CollapsedSections, 0, c, 0, pos); fs.CollapsedSections[pos].Uncollapse(); Array.Copy(fs.CollapsedSections, pos + 1, c, pos, c.Length - pos); fs.CollapsedSections = c; } } } internal void Redraw() { foreach (var textView in TextViews) textView.Redraw(); } internal void Redraw(FoldingSection fs) { foreach (var textView in TextViews) textView.Redraw(fs); } #endregion #region Create / Remove / Clear /// <summary> /// Creates a folding for the specified text section. /// </summary> public FoldingSection CreateFolding(int startOffset, int endOffset) { if (startOffset >= endOffset) throw new ArgumentException("startOffset must be less than endOffset"); if (startOffset < 0 || endOffset > Document.TextLength) throw new ArgumentException("Folding must be within document boundary"); var fs = new FoldingSection(this, startOffset, endOffset); _foldings.Add(fs); Redraw(fs); return fs; } /// <summary> /// Removes a folding section from this manager. /// </summary> public void RemoveFolding(FoldingSection fs) { if (fs == null) throw new ArgumentNullException(nameof(fs)); fs.IsFolded = false; _foldings.Remove(fs); Redraw(fs); } /// <summary> /// Removes all folding sections. /// </summary> public void Clear() { Dispatcher.UIThread.VerifyAccess(); foreach (var s in _foldings) s.IsFolded = false; _foldings.Clear(); Redraw(); } #endregion #region Get...Folding /// <summary> /// Gets all foldings in this manager. /// The foldings are returned sorted by start offset; /// for multiple foldings at the same offset the order is undefined. /// </summary> public IEnumerable<FoldingSection> AllFoldings => _foldings; /// <summary> /// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts. /// Returns -1 if there are no foldings after <paramref name="startOffset"/>. /// </summary> public int GetNextFoldedFoldingStart(int startOffset) { var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && !fs.IsFolded) fs = _foldings.GetNextSegment(fs); return fs?.StartOffset ?? -1; } /// <summary> /// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to /// <paramref name="startOffset"/>. /// Returns null if there are no foldings after <paramref name="startOffset"/>. /// </summary> public FoldingSection GetNextFolding(int startOffset) { // TODO: returns the longest folding instead of any folding at the first position after startOffset return _foldings.FindFirstSegmentWithStartAfter(startOffset); } /// <summary> /// Gets all foldings that start exactly at <paramref name="startOffset"/>. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset) { var result = new List<FoldingSection>(); var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && fs.StartOffset == startOffset) { result.Add(fs); fs = _foldings.GetNextSegment(fs); } return new ReadOnlyCollection<FoldingSection>(result); } /// <summary> /// Gets all foldings that contain <paramref name="offset" />. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset) { return _foldings.FindSegmentsContaining(offset); } #endregion #region UpdateFoldings /// <summary> /// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings. /// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state /// (<see cref="FoldingSection.IsFolded"/>) for existing foldings. /// </summary> /// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param> /// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after /// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>. /// Use -1 for this parameter if there were no parse errors.</param> public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset) { if (newFoldings == null) throw new ArgumentNullException(nameof(newFoldings)); if (firstErrorOffset < 0) firstErrorOffset = int.MaxValue; var oldFoldings = AllFoldings.ToArray(); var oldFoldingIndex = 0; var previousStartOffset = 0; // merge new foldings into old foldings so that sections keep being collapsed // both oldFoldings and newFoldings are sorted by start offset foreach (var newFolding in newFoldings) { // ensure newFoldings are sorted correctly if (newFolding.StartOffset < previousStartOffset) throw new ArgumentException("newFoldings must be sorted by start offset"); previousStartOffset = newFolding.StartOffset; if (newFolding.StartOffset == newFolding.EndOffset) continue; // ignore zero-length foldings // remove old foldings that were skipped while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) { RemoveFolding(oldFoldings[oldFoldingIndex++]); } FoldingSection section; // reuse current folding if its matching: if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) { section = oldFoldings[oldFoldingIndex++]; section.Length = newFolding.EndOffset - newFolding.StartOffset; } else { // no matching current folding; create a new one: section = CreateFolding(newFolding.StartOffset, newFolding.EndOffset); // auto-close #regions only when opening the document if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) { var oldSection = oldFoldings[oldFoldingIndex++]; if (oldSection.StartOffset >= firstErrorOffset) break; RemoveFolding(oldSection); } } #endregion #region Install /// <summary> /// Adds Folding support to the specified text area. /// Warning: The folding manager is only valid for the text area's current document. The folding manager /// must be uninstalled before the text area is bound to a different document. /// </summary> /// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns> public static FoldingManager Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); return new FoldingManagerInstallation(textArea); } /// <summary> /// Uninstalls the folding manager. /// </summary> /// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception> public static void Uninstall(FoldingManager manager) { if (manager == null) throw new ArgumentNullException(nameof(manager)); if (manager is FoldingManagerInstallation installation) { installation.Uninstall(); } else { throw new ArgumentException("FoldingManager was not created using FoldingManager.Install"); } } private sealed class FoldingManagerInstallation : FoldingManager { private TextArea _textArea; private FoldingMargin _margin; private FoldingElementGenerator _generator; public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document) { _textArea = textArea; _margin = new FoldingMargin { FoldingManager = this }; _generator = new FoldingElementGenerator { FoldingManager = this }; textArea.LeftMargins.Add(_margin); textArea.TextView.Services.AddService(typeof(FoldingManager), this); // HACK: folding only works correctly when it has highest priority textArea.TextView.ElementGenerators.Insert(0, _generator); textArea.Caret.PositionChanged += TextArea_Caret_PositionChanged; } /* void DemoMode() { foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm }; foldingMargin = new FoldingMargin { FoldingManager = fm }; foldingMarginBorder = new Border { Child = foldingMargin, Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0) }; foldingMarginBorder.SizeChanged += UpdateTextViewClip; textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator); textEditor.TextArea.LeftMargins.Add(foldingMarginBorder); } void UpdateTextViewClip(object sender, SizeChangedEventArgs e) { textEditor.TextArea.TextView.Clip = new RectangleGeometry( new Rect(-foldingMarginBorder.ActualWidth, 0, textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth, textEditor.TextArea.TextView.ActualHeight)); } */ public void Uninstall() { Clear(); if (_textArea != null) { _textArea.Caret.PositionChanged -= TextArea_Caret_PositionChanged; _textArea.LeftMargins.Remove(_margin); _textArea.TextView.ElementGenerators.Remove(_generator); _textArea.TextView.Services.RemoveService(typeof(FoldingManager)); _margin = null; _generator = null; _textArea = null; } } private void TextArea_Caret_PositionChanged(object sender, EventArgs e) { // Expand Foldings when Caret is moved into them. var caretOffset = _textArea.Caret.Offset; foreach (var s in GetFoldingsContaining(caretOffset)) { if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) { s.IsFolded = false; } } } } #endregion } } <MSG> Fix only first fold is preserved when updating foldings #110 https://github.com/icsharpcode/AvalonEdit/pull/110 <DFF> @@ -272,12 +272,12 @@ namespace AvaloniaEdit.Folding if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; - _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } + _isFirstUpdate = false; // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) {
1
Fix only first fold is preserved when updating foldings #110
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062017
<NME> FoldingManager.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Threading; namespace AvaloniaEdit.Folding { /// <summary> /// Stores a list of foldings for a specific TextView and TextDocument. /// </summary> public class FoldingManager { internal TextDocument Document { get; } internal List<TextView> TextViews { get; } = new List<TextView>(); private readonly TextSegmentCollection<FoldingSection> _foldings; private bool _isFirstUpdate = true; #region Constructor /// <summary> /// Creates a new FoldingManager instance. /// </summary> public FoldingManager(TextDocument document) { Document = document ?? throw new ArgumentNullException(nameof(document)); _foldings = new TextSegmentCollection<FoldingSection>(); Dispatcher.UIThread.VerifyAccess(); TextDocumentWeakEventManager.Changed.AddHandler(document, OnDocumentChanged); } #endregion #region ReceiveWeakEvent private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { _foldings.UpdateOffsets(e); var newEndOffset = e.Offset + e.InsertionLength; // extend end offset to the end of the line (including delimiter) var endLine = Document.GetLineByOffset(newEndOffset); newEndOffset = endLine.Offset + endLine.TotalLength; foreach (var affectedFolding in _foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) { if (affectedFolding.Length == 0) { RemoveFolding(affectedFolding); } else { affectedFolding.ValidateCollapsedLineSections(); } } } #endregion #region Manage TextViews internal void AddToTextView(TextView textView) { if (textView == null || TextViews.Contains(textView)) throw new ArgumentException(); TextViews.Add(textView); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { Array.Resize(ref fs.CollapsedSections, TextViews.Count); fs.ValidateCollapsedLineSections(); } } } internal void RemoveFromTextView(TextView textView) { var pos = TextViews.IndexOf(textView); if (pos < 0) throw new ArgumentException(); TextViews.RemoveAt(pos); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { var c = new CollapsedLineSection[TextViews.Count]; Array.Copy(fs.CollapsedSections, 0, c, 0, pos); fs.CollapsedSections[pos].Uncollapse(); Array.Copy(fs.CollapsedSections, pos + 1, c, pos, c.Length - pos); fs.CollapsedSections = c; } } } internal void Redraw() { foreach (var textView in TextViews) textView.Redraw(); } internal void Redraw(FoldingSection fs) { foreach (var textView in TextViews) textView.Redraw(fs); } #endregion #region Create / Remove / Clear /// <summary> /// Creates a folding for the specified text section. /// </summary> public FoldingSection CreateFolding(int startOffset, int endOffset) { if (startOffset >= endOffset) throw new ArgumentException("startOffset must be less than endOffset"); if (startOffset < 0 || endOffset > Document.TextLength) throw new ArgumentException("Folding must be within document boundary"); var fs = new FoldingSection(this, startOffset, endOffset); _foldings.Add(fs); Redraw(fs); return fs; } /// <summary> /// Removes a folding section from this manager. /// </summary> public void RemoveFolding(FoldingSection fs) { if (fs == null) throw new ArgumentNullException(nameof(fs)); fs.IsFolded = false; _foldings.Remove(fs); Redraw(fs); } /// <summary> /// Removes all folding sections. /// </summary> public void Clear() { Dispatcher.UIThread.VerifyAccess(); foreach (var s in _foldings) s.IsFolded = false; _foldings.Clear(); Redraw(); } #endregion #region Get...Folding /// <summary> /// Gets all foldings in this manager. /// The foldings are returned sorted by start offset; /// for multiple foldings at the same offset the order is undefined. /// </summary> public IEnumerable<FoldingSection> AllFoldings => _foldings; /// <summary> /// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts. /// Returns -1 if there are no foldings after <paramref name="startOffset"/>. /// </summary> public int GetNextFoldedFoldingStart(int startOffset) { var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && !fs.IsFolded) fs = _foldings.GetNextSegment(fs); return fs?.StartOffset ?? -1; } /// <summary> /// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to /// <paramref name="startOffset"/>. /// Returns null if there are no foldings after <paramref name="startOffset"/>. /// </summary> public FoldingSection GetNextFolding(int startOffset) { // TODO: returns the longest folding instead of any folding at the first position after startOffset return _foldings.FindFirstSegmentWithStartAfter(startOffset); } /// <summary> /// Gets all foldings that start exactly at <paramref name="startOffset"/>. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset) { var result = new List<FoldingSection>(); var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && fs.StartOffset == startOffset) { result.Add(fs); fs = _foldings.GetNextSegment(fs); } return new ReadOnlyCollection<FoldingSection>(result); } /// <summary> /// Gets all foldings that contain <paramref name="offset" />. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset) { return _foldings.FindSegmentsContaining(offset); } #endregion #region UpdateFoldings /// <summary> /// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings. /// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state /// (<see cref="FoldingSection.IsFolded"/>) for existing foldings. /// </summary> /// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param> /// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after /// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>. /// Use -1 for this parameter if there were no parse errors.</param> public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset) { if (newFoldings == null) throw new ArgumentNullException(nameof(newFoldings)); if (firstErrorOffset < 0) firstErrorOffset = int.MaxValue; var oldFoldings = AllFoldings.ToArray(); var oldFoldingIndex = 0; var previousStartOffset = 0; // merge new foldings into old foldings so that sections keep being collapsed // both oldFoldings and newFoldings are sorted by start offset foreach (var newFolding in newFoldings) { // ensure newFoldings are sorted correctly if (newFolding.StartOffset < previousStartOffset) throw new ArgumentException("newFoldings must be sorted by start offset"); previousStartOffset = newFolding.StartOffset; if (newFolding.StartOffset == newFolding.EndOffset) continue; // ignore zero-length foldings // remove old foldings that were skipped while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) { RemoveFolding(oldFoldings[oldFoldingIndex++]); } FoldingSection section; // reuse current folding if its matching: if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) { section = oldFoldings[oldFoldingIndex++]; section.Length = newFolding.EndOffset - newFolding.StartOffset; } else { // no matching current folding; create a new one: section = CreateFolding(newFolding.StartOffset, newFolding.EndOffset); // auto-close #regions only when opening the document if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) { var oldSection = oldFoldings[oldFoldingIndex++]; if (oldSection.StartOffset >= firstErrorOffset) break; RemoveFolding(oldSection); } } #endregion #region Install /// <summary> /// Adds Folding support to the specified text area. /// Warning: The folding manager is only valid for the text area's current document. The folding manager /// must be uninstalled before the text area is bound to a different document. /// </summary> /// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns> public static FoldingManager Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); return new FoldingManagerInstallation(textArea); } /// <summary> /// Uninstalls the folding manager. /// </summary> /// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception> public static void Uninstall(FoldingManager manager) { if (manager == null) throw new ArgumentNullException(nameof(manager)); if (manager is FoldingManagerInstallation installation) { installation.Uninstall(); } else { throw new ArgumentException("FoldingManager was not created using FoldingManager.Install"); } } private sealed class FoldingManagerInstallation : FoldingManager { private TextArea _textArea; private FoldingMargin _margin; private FoldingElementGenerator _generator; public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document) { _textArea = textArea; _margin = new FoldingMargin { FoldingManager = this }; _generator = new FoldingElementGenerator { FoldingManager = this }; textArea.LeftMargins.Add(_margin); textArea.TextView.Services.AddService(typeof(FoldingManager), this); // HACK: folding only works correctly when it has highest priority textArea.TextView.ElementGenerators.Insert(0, _generator); textArea.Caret.PositionChanged += TextArea_Caret_PositionChanged; } /* void DemoMode() { foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm }; foldingMargin = new FoldingMargin { FoldingManager = fm }; foldingMarginBorder = new Border { Child = foldingMargin, Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0) }; foldingMarginBorder.SizeChanged += UpdateTextViewClip; textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator); textEditor.TextArea.LeftMargins.Add(foldingMarginBorder); } void UpdateTextViewClip(object sender, SizeChangedEventArgs e) { textEditor.TextArea.TextView.Clip = new RectangleGeometry( new Rect(-foldingMarginBorder.ActualWidth, 0, textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth, textEditor.TextArea.TextView.ActualHeight)); } */ public void Uninstall() { Clear(); if (_textArea != null) { _textArea.Caret.PositionChanged -= TextArea_Caret_PositionChanged; _textArea.LeftMargins.Remove(_margin); _textArea.TextView.ElementGenerators.Remove(_generator); _textArea.TextView.Services.RemoveService(typeof(FoldingManager)); _margin = null; _generator = null; _textArea = null; } } private void TextArea_Caret_PositionChanged(object sender, EventArgs e) { // Expand Foldings when Caret is moved into them. var caretOffset = _textArea.Caret.Offset; foreach (var s in GetFoldingsContaining(caretOffset)) { if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) { s.IsFolded = false; } } } } #endregion } } <MSG> Fix only first fold is preserved when updating foldings #110 https://github.com/icsharpcode/AvalonEdit/pull/110 <DFF> @@ -272,12 +272,12 @@ namespace AvaloniaEdit.Folding if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; - _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } + _isFirstUpdate = false; // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) {
1
Fix only first fold is preserved when updating foldings #110
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062018
<NME> FoldingManager.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Threading; namespace AvaloniaEdit.Folding { /// <summary> /// Stores a list of foldings for a specific TextView and TextDocument. /// </summary> public class FoldingManager { internal TextDocument Document { get; } internal List<TextView> TextViews { get; } = new List<TextView>(); private readonly TextSegmentCollection<FoldingSection> _foldings; private bool _isFirstUpdate = true; #region Constructor /// <summary> /// Creates a new FoldingManager instance. /// </summary> public FoldingManager(TextDocument document) { Document = document ?? throw new ArgumentNullException(nameof(document)); _foldings = new TextSegmentCollection<FoldingSection>(); Dispatcher.UIThread.VerifyAccess(); TextDocumentWeakEventManager.Changed.AddHandler(document, OnDocumentChanged); } #endregion #region ReceiveWeakEvent private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { _foldings.UpdateOffsets(e); var newEndOffset = e.Offset + e.InsertionLength; // extend end offset to the end of the line (including delimiter) var endLine = Document.GetLineByOffset(newEndOffset); newEndOffset = endLine.Offset + endLine.TotalLength; foreach (var affectedFolding in _foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) { if (affectedFolding.Length == 0) { RemoveFolding(affectedFolding); } else { affectedFolding.ValidateCollapsedLineSections(); } } } #endregion #region Manage TextViews internal void AddToTextView(TextView textView) { if (textView == null || TextViews.Contains(textView)) throw new ArgumentException(); TextViews.Add(textView); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { Array.Resize(ref fs.CollapsedSections, TextViews.Count); fs.ValidateCollapsedLineSections(); } } } internal void RemoveFromTextView(TextView textView) { var pos = TextViews.IndexOf(textView); if (pos < 0) throw new ArgumentException(); TextViews.RemoveAt(pos); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { var c = new CollapsedLineSection[TextViews.Count]; Array.Copy(fs.CollapsedSections, 0, c, 0, pos); fs.CollapsedSections[pos].Uncollapse(); Array.Copy(fs.CollapsedSections, pos + 1, c, pos, c.Length - pos); fs.CollapsedSections = c; } } } internal void Redraw() { foreach (var textView in TextViews) textView.Redraw(); } internal void Redraw(FoldingSection fs) { foreach (var textView in TextViews) textView.Redraw(fs); } #endregion #region Create / Remove / Clear /// <summary> /// Creates a folding for the specified text section. /// </summary> public FoldingSection CreateFolding(int startOffset, int endOffset) { if (startOffset >= endOffset) throw new ArgumentException("startOffset must be less than endOffset"); if (startOffset < 0 || endOffset > Document.TextLength) throw new ArgumentException("Folding must be within document boundary"); var fs = new FoldingSection(this, startOffset, endOffset); _foldings.Add(fs); Redraw(fs); return fs; } /// <summary> /// Removes a folding section from this manager. /// </summary> public void RemoveFolding(FoldingSection fs) { if (fs == null) throw new ArgumentNullException(nameof(fs)); fs.IsFolded = false; _foldings.Remove(fs); Redraw(fs); } /// <summary> /// Removes all folding sections. /// </summary> public void Clear() { Dispatcher.UIThread.VerifyAccess(); foreach (var s in _foldings) s.IsFolded = false; _foldings.Clear(); Redraw(); } #endregion #region Get...Folding /// <summary> /// Gets all foldings in this manager. /// The foldings are returned sorted by start offset; /// for multiple foldings at the same offset the order is undefined. /// </summary> public IEnumerable<FoldingSection> AllFoldings => _foldings; /// <summary> /// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts. /// Returns -1 if there are no foldings after <paramref name="startOffset"/>. /// </summary> public int GetNextFoldedFoldingStart(int startOffset) { var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && !fs.IsFolded) fs = _foldings.GetNextSegment(fs); return fs?.StartOffset ?? -1; } /// <summary> /// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to /// <paramref name="startOffset"/>. /// Returns null if there are no foldings after <paramref name="startOffset"/>. /// </summary> public FoldingSection GetNextFolding(int startOffset) { // TODO: returns the longest folding instead of any folding at the first position after startOffset return _foldings.FindFirstSegmentWithStartAfter(startOffset); } /// <summary> /// Gets all foldings that start exactly at <paramref name="startOffset"/>. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset) { var result = new List<FoldingSection>(); var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && fs.StartOffset == startOffset) { result.Add(fs); fs = _foldings.GetNextSegment(fs); } return new ReadOnlyCollection<FoldingSection>(result); } /// <summary> /// Gets all foldings that contain <paramref name="offset" />. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset) { return _foldings.FindSegmentsContaining(offset); } #endregion #region UpdateFoldings /// <summary> /// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings. /// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state /// (<see cref="FoldingSection.IsFolded"/>) for existing foldings. /// </summary> /// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param> /// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after /// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>. /// Use -1 for this parameter if there were no parse errors.</param> public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset) { if (newFoldings == null) throw new ArgumentNullException(nameof(newFoldings)); if (firstErrorOffset < 0) firstErrorOffset = int.MaxValue; var oldFoldings = AllFoldings.ToArray(); var oldFoldingIndex = 0; var previousStartOffset = 0; // merge new foldings into old foldings so that sections keep being collapsed // both oldFoldings and newFoldings are sorted by start offset foreach (var newFolding in newFoldings) { // ensure newFoldings are sorted correctly if (newFolding.StartOffset < previousStartOffset) throw new ArgumentException("newFoldings must be sorted by start offset"); previousStartOffset = newFolding.StartOffset; if (newFolding.StartOffset == newFolding.EndOffset) continue; // ignore zero-length foldings // remove old foldings that were skipped while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) { RemoveFolding(oldFoldings[oldFoldingIndex++]); } FoldingSection section; // reuse current folding if its matching: if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) { section = oldFoldings[oldFoldingIndex++]; section.Length = newFolding.EndOffset - newFolding.StartOffset; } else { // no matching current folding; create a new one: section = CreateFolding(newFolding.StartOffset, newFolding.EndOffset); // auto-close #regions only when opening the document if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) { var oldSection = oldFoldings[oldFoldingIndex++]; if (oldSection.StartOffset >= firstErrorOffset) break; RemoveFolding(oldSection); } } #endregion #region Install /// <summary> /// Adds Folding support to the specified text area. /// Warning: The folding manager is only valid for the text area's current document. The folding manager /// must be uninstalled before the text area is bound to a different document. /// </summary> /// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns> public static FoldingManager Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); return new FoldingManagerInstallation(textArea); } /// <summary> /// Uninstalls the folding manager. /// </summary> /// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception> public static void Uninstall(FoldingManager manager) { if (manager == null) throw new ArgumentNullException(nameof(manager)); if (manager is FoldingManagerInstallation installation) { installation.Uninstall(); } else { throw new ArgumentException("FoldingManager was not created using FoldingManager.Install"); } } private sealed class FoldingManagerInstallation : FoldingManager { private TextArea _textArea; private FoldingMargin _margin; private FoldingElementGenerator _generator; public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document) { _textArea = textArea; _margin = new FoldingMargin { FoldingManager = this }; _generator = new FoldingElementGenerator { FoldingManager = this }; textArea.LeftMargins.Add(_margin); textArea.TextView.Services.AddService(typeof(FoldingManager), this); // HACK: folding only works correctly when it has highest priority textArea.TextView.ElementGenerators.Insert(0, _generator); textArea.Caret.PositionChanged += TextArea_Caret_PositionChanged; } /* void DemoMode() { foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm }; foldingMargin = new FoldingMargin { FoldingManager = fm }; foldingMarginBorder = new Border { Child = foldingMargin, Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0) }; foldingMarginBorder.SizeChanged += UpdateTextViewClip; textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator); textEditor.TextArea.LeftMargins.Add(foldingMarginBorder); } void UpdateTextViewClip(object sender, SizeChangedEventArgs e) { textEditor.TextArea.TextView.Clip = new RectangleGeometry( new Rect(-foldingMarginBorder.ActualWidth, 0, textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth, textEditor.TextArea.TextView.ActualHeight)); } */ public void Uninstall() { Clear(); if (_textArea != null) { _textArea.Caret.PositionChanged -= TextArea_Caret_PositionChanged; _textArea.LeftMargins.Remove(_margin); _textArea.TextView.ElementGenerators.Remove(_generator); _textArea.TextView.Services.RemoveService(typeof(FoldingManager)); _margin = null; _generator = null; _textArea = null; } } private void TextArea_Caret_PositionChanged(object sender, EventArgs e) { // Expand Foldings when Caret is moved into them. var caretOffset = _textArea.Caret.Offset; foreach (var s in GetFoldingsContaining(caretOffset)) { if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) { s.IsFolded = false; } } } } #endregion } } <MSG> Fix only first fold is preserved when updating foldings #110 https://github.com/icsharpcode/AvalonEdit/pull/110 <DFF> @@ -272,12 +272,12 @@ namespace AvaloniaEdit.Folding if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; - _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } + _isFirstUpdate = false; // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) {
1
Fix only first fold is preserved when updating foldings #110
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062019
<NME> FoldingManager.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Threading; namespace AvaloniaEdit.Folding { /// <summary> /// Stores a list of foldings for a specific TextView and TextDocument. /// </summary> public class FoldingManager { internal TextDocument Document { get; } internal List<TextView> TextViews { get; } = new List<TextView>(); private readonly TextSegmentCollection<FoldingSection> _foldings; private bool _isFirstUpdate = true; #region Constructor /// <summary> /// Creates a new FoldingManager instance. /// </summary> public FoldingManager(TextDocument document) { Document = document ?? throw new ArgumentNullException(nameof(document)); _foldings = new TextSegmentCollection<FoldingSection>(); Dispatcher.UIThread.VerifyAccess(); TextDocumentWeakEventManager.Changed.AddHandler(document, OnDocumentChanged); } #endregion #region ReceiveWeakEvent private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { _foldings.UpdateOffsets(e); var newEndOffset = e.Offset + e.InsertionLength; // extend end offset to the end of the line (including delimiter) var endLine = Document.GetLineByOffset(newEndOffset); newEndOffset = endLine.Offset + endLine.TotalLength; foreach (var affectedFolding in _foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) { if (affectedFolding.Length == 0) { RemoveFolding(affectedFolding); } else { affectedFolding.ValidateCollapsedLineSections(); } } } #endregion #region Manage TextViews internal void AddToTextView(TextView textView) { if (textView == null || TextViews.Contains(textView)) throw new ArgumentException(); TextViews.Add(textView); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { Array.Resize(ref fs.CollapsedSections, TextViews.Count); fs.ValidateCollapsedLineSections(); } } } internal void RemoveFromTextView(TextView textView) { var pos = TextViews.IndexOf(textView); if (pos < 0) throw new ArgumentException(); TextViews.RemoveAt(pos); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { var c = new CollapsedLineSection[TextViews.Count]; Array.Copy(fs.CollapsedSections, 0, c, 0, pos); fs.CollapsedSections[pos].Uncollapse(); Array.Copy(fs.CollapsedSections, pos + 1, c, pos, c.Length - pos); fs.CollapsedSections = c; } } } internal void Redraw() { foreach (var textView in TextViews) textView.Redraw(); } internal void Redraw(FoldingSection fs) { foreach (var textView in TextViews) textView.Redraw(fs); } #endregion #region Create / Remove / Clear /// <summary> /// Creates a folding for the specified text section. /// </summary> public FoldingSection CreateFolding(int startOffset, int endOffset) { if (startOffset >= endOffset) throw new ArgumentException("startOffset must be less than endOffset"); if (startOffset < 0 || endOffset > Document.TextLength) throw new ArgumentException("Folding must be within document boundary"); var fs = new FoldingSection(this, startOffset, endOffset); _foldings.Add(fs); Redraw(fs); return fs; } /// <summary> /// Removes a folding section from this manager. /// </summary> public void RemoveFolding(FoldingSection fs) { if (fs == null) throw new ArgumentNullException(nameof(fs)); fs.IsFolded = false; _foldings.Remove(fs); Redraw(fs); } /// <summary> /// Removes all folding sections. /// </summary> public void Clear() { Dispatcher.UIThread.VerifyAccess(); foreach (var s in _foldings) s.IsFolded = false; _foldings.Clear(); Redraw(); } #endregion #region Get...Folding /// <summary> /// Gets all foldings in this manager. /// The foldings are returned sorted by start offset; /// for multiple foldings at the same offset the order is undefined. /// </summary> public IEnumerable<FoldingSection> AllFoldings => _foldings; /// <summary> /// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts. /// Returns -1 if there are no foldings after <paramref name="startOffset"/>. /// </summary> public int GetNextFoldedFoldingStart(int startOffset) { var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && !fs.IsFolded) fs = _foldings.GetNextSegment(fs); return fs?.StartOffset ?? -1; } /// <summary> /// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to /// <paramref name="startOffset"/>. /// Returns null if there are no foldings after <paramref name="startOffset"/>. /// </summary> public FoldingSection GetNextFolding(int startOffset) { // TODO: returns the longest folding instead of any folding at the first position after startOffset return _foldings.FindFirstSegmentWithStartAfter(startOffset); } /// <summary> /// Gets all foldings that start exactly at <paramref name="startOffset"/>. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset) { var result = new List<FoldingSection>(); var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && fs.StartOffset == startOffset) { result.Add(fs); fs = _foldings.GetNextSegment(fs); } return new ReadOnlyCollection<FoldingSection>(result); } /// <summary> /// Gets all foldings that contain <paramref name="offset" />. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset) { return _foldings.FindSegmentsContaining(offset); } #endregion #region UpdateFoldings /// <summary> /// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings. /// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state /// (<see cref="FoldingSection.IsFolded"/>) for existing foldings. /// </summary> /// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param> /// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after /// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>. /// Use -1 for this parameter if there were no parse errors.</param> public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset) { if (newFoldings == null) throw new ArgumentNullException(nameof(newFoldings)); if (firstErrorOffset < 0) firstErrorOffset = int.MaxValue; var oldFoldings = AllFoldings.ToArray(); var oldFoldingIndex = 0; var previousStartOffset = 0; // merge new foldings into old foldings so that sections keep being collapsed // both oldFoldings and newFoldings are sorted by start offset foreach (var newFolding in newFoldings) { // ensure newFoldings are sorted correctly if (newFolding.StartOffset < previousStartOffset) throw new ArgumentException("newFoldings must be sorted by start offset"); previousStartOffset = newFolding.StartOffset; if (newFolding.StartOffset == newFolding.EndOffset) continue; // ignore zero-length foldings // remove old foldings that were skipped while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) { RemoveFolding(oldFoldings[oldFoldingIndex++]); } FoldingSection section; // reuse current folding if its matching: if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) { section = oldFoldings[oldFoldingIndex++]; section.Length = newFolding.EndOffset - newFolding.StartOffset; } else { // no matching current folding; create a new one: section = CreateFolding(newFolding.StartOffset, newFolding.EndOffset); // auto-close #regions only when opening the document if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) { var oldSection = oldFoldings[oldFoldingIndex++]; if (oldSection.StartOffset >= firstErrorOffset) break; RemoveFolding(oldSection); } } #endregion #region Install /// <summary> /// Adds Folding support to the specified text area. /// Warning: The folding manager is only valid for the text area's current document. The folding manager /// must be uninstalled before the text area is bound to a different document. /// </summary> /// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns> public static FoldingManager Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); return new FoldingManagerInstallation(textArea); } /// <summary> /// Uninstalls the folding manager. /// </summary> /// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception> public static void Uninstall(FoldingManager manager) { if (manager == null) throw new ArgumentNullException(nameof(manager)); if (manager is FoldingManagerInstallation installation) { installation.Uninstall(); } else { throw new ArgumentException("FoldingManager was not created using FoldingManager.Install"); } } private sealed class FoldingManagerInstallation : FoldingManager { private TextArea _textArea; private FoldingMargin _margin; private FoldingElementGenerator _generator; public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document) { _textArea = textArea; _margin = new FoldingMargin { FoldingManager = this }; _generator = new FoldingElementGenerator { FoldingManager = this }; textArea.LeftMargins.Add(_margin); textArea.TextView.Services.AddService(typeof(FoldingManager), this); // HACK: folding only works correctly when it has highest priority textArea.TextView.ElementGenerators.Insert(0, _generator); textArea.Caret.PositionChanged += TextArea_Caret_PositionChanged; } /* void DemoMode() { foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm }; foldingMargin = new FoldingMargin { FoldingManager = fm }; foldingMarginBorder = new Border { Child = foldingMargin, Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0) }; foldingMarginBorder.SizeChanged += UpdateTextViewClip; textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator); textEditor.TextArea.LeftMargins.Add(foldingMarginBorder); } void UpdateTextViewClip(object sender, SizeChangedEventArgs e) { textEditor.TextArea.TextView.Clip = new RectangleGeometry( new Rect(-foldingMarginBorder.ActualWidth, 0, textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth, textEditor.TextArea.TextView.ActualHeight)); } */ public void Uninstall() { Clear(); if (_textArea != null) { _textArea.Caret.PositionChanged -= TextArea_Caret_PositionChanged; _textArea.LeftMargins.Remove(_margin); _textArea.TextView.ElementGenerators.Remove(_generator); _textArea.TextView.Services.RemoveService(typeof(FoldingManager)); _margin = null; _generator = null; _textArea = null; } } private void TextArea_Caret_PositionChanged(object sender, EventArgs e) { // Expand Foldings when Caret is moved into them. var caretOffset = _textArea.Caret.Offset; foreach (var s in GetFoldingsContaining(caretOffset)) { if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) { s.IsFolded = false; } } } } #endregion } } <MSG> Fix only first fold is preserved when updating foldings #110 https://github.com/icsharpcode/AvalonEdit/pull/110 <DFF> @@ -272,12 +272,12 @@ namespace AvaloniaEdit.Folding if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; - _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } + _isFirstUpdate = false; // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) {
1
Fix only first fold is preserved when updating foldings #110
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062020
<NME> FoldingManager.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Threading; namespace AvaloniaEdit.Folding { /// <summary> /// Stores a list of foldings for a specific TextView and TextDocument. /// </summary> public class FoldingManager { internal TextDocument Document { get; } internal List<TextView> TextViews { get; } = new List<TextView>(); private readonly TextSegmentCollection<FoldingSection> _foldings; private bool _isFirstUpdate = true; #region Constructor /// <summary> /// Creates a new FoldingManager instance. /// </summary> public FoldingManager(TextDocument document) { Document = document ?? throw new ArgumentNullException(nameof(document)); _foldings = new TextSegmentCollection<FoldingSection>(); Dispatcher.UIThread.VerifyAccess(); TextDocumentWeakEventManager.Changed.AddHandler(document, OnDocumentChanged); } #endregion #region ReceiveWeakEvent private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { _foldings.UpdateOffsets(e); var newEndOffset = e.Offset + e.InsertionLength; // extend end offset to the end of the line (including delimiter) var endLine = Document.GetLineByOffset(newEndOffset); newEndOffset = endLine.Offset + endLine.TotalLength; foreach (var affectedFolding in _foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) { if (affectedFolding.Length == 0) { RemoveFolding(affectedFolding); } else { affectedFolding.ValidateCollapsedLineSections(); } } } #endregion #region Manage TextViews internal void AddToTextView(TextView textView) { if (textView == null || TextViews.Contains(textView)) throw new ArgumentException(); TextViews.Add(textView); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { Array.Resize(ref fs.CollapsedSections, TextViews.Count); fs.ValidateCollapsedLineSections(); } } } internal void RemoveFromTextView(TextView textView) { var pos = TextViews.IndexOf(textView); if (pos < 0) throw new ArgumentException(); TextViews.RemoveAt(pos); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { var c = new CollapsedLineSection[TextViews.Count]; Array.Copy(fs.CollapsedSections, 0, c, 0, pos); fs.CollapsedSections[pos].Uncollapse(); Array.Copy(fs.CollapsedSections, pos + 1, c, pos, c.Length - pos); fs.CollapsedSections = c; } } } internal void Redraw() { foreach (var textView in TextViews) textView.Redraw(); } internal void Redraw(FoldingSection fs) { foreach (var textView in TextViews) textView.Redraw(fs); } #endregion #region Create / Remove / Clear /// <summary> /// Creates a folding for the specified text section. /// </summary> public FoldingSection CreateFolding(int startOffset, int endOffset) { if (startOffset >= endOffset) throw new ArgumentException("startOffset must be less than endOffset"); if (startOffset < 0 || endOffset > Document.TextLength) throw new ArgumentException("Folding must be within document boundary"); var fs = new FoldingSection(this, startOffset, endOffset); _foldings.Add(fs); Redraw(fs); return fs; } /// <summary> /// Removes a folding section from this manager. /// </summary> public void RemoveFolding(FoldingSection fs) { if (fs == null) throw new ArgumentNullException(nameof(fs)); fs.IsFolded = false; _foldings.Remove(fs); Redraw(fs); } /// <summary> /// Removes all folding sections. /// </summary> public void Clear() { Dispatcher.UIThread.VerifyAccess(); foreach (var s in _foldings) s.IsFolded = false; _foldings.Clear(); Redraw(); } #endregion #region Get...Folding /// <summary> /// Gets all foldings in this manager. /// The foldings are returned sorted by start offset; /// for multiple foldings at the same offset the order is undefined. /// </summary> public IEnumerable<FoldingSection> AllFoldings => _foldings; /// <summary> /// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts. /// Returns -1 if there are no foldings after <paramref name="startOffset"/>. /// </summary> public int GetNextFoldedFoldingStart(int startOffset) { var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && !fs.IsFolded) fs = _foldings.GetNextSegment(fs); return fs?.StartOffset ?? -1; } /// <summary> /// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to /// <paramref name="startOffset"/>. /// Returns null if there are no foldings after <paramref name="startOffset"/>. /// </summary> public FoldingSection GetNextFolding(int startOffset) { // TODO: returns the longest folding instead of any folding at the first position after startOffset return _foldings.FindFirstSegmentWithStartAfter(startOffset); } /// <summary> /// Gets all foldings that start exactly at <paramref name="startOffset"/>. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset) { var result = new List<FoldingSection>(); var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && fs.StartOffset == startOffset) { result.Add(fs); fs = _foldings.GetNextSegment(fs); } return new ReadOnlyCollection<FoldingSection>(result); } /// <summary> /// Gets all foldings that contain <paramref name="offset" />. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset) { return _foldings.FindSegmentsContaining(offset); } #endregion #region UpdateFoldings /// <summary> /// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings. /// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state /// (<see cref="FoldingSection.IsFolded"/>) for existing foldings. /// </summary> /// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param> /// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after /// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>. /// Use -1 for this parameter if there were no parse errors.</param> public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset) { if (newFoldings == null) throw new ArgumentNullException(nameof(newFoldings)); if (firstErrorOffset < 0) firstErrorOffset = int.MaxValue; var oldFoldings = AllFoldings.ToArray(); var oldFoldingIndex = 0; var previousStartOffset = 0; // merge new foldings into old foldings so that sections keep being collapsed // both oldFoldings and newFoldings are sorted by start offset foreach (var newFolding in newFoldings) { // ensure newFoldings are sorted correctly if (newFolding.StartOffset < previousStartOffset) throw new ArgumentException("newFoldings must be sorted by start offset"); previousStartOffset = newFolding.StartOffset; if (newFolding.StartOffset == newFolding.EndOffset) continue; // ignore zero-length foldings // remove old foldings that were skipped while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) { RemoveFolding(oldFoldings[oldFoldingIndex++]); } FoldingSection section; // reuse current folding if its matching: if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) { section = oldFoldings[oldFoldingIndex++]; section.Length = newFolding.EndOffset - newFolding.StartOffset; } else { // no matching current folding; create a new one: section = CreateFolding(newFolding.StartOffset, newFolding.EndOffset); // auto-close #regions only when opening the document if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) { var oldSection = oldFoldings[oldFoldingIndex++]; if (oldSection.StartOffset >= firstErrorOffset) break; RemoveFolding(oldSection); } } #endregion #region Install /// <summary> /// Adds Folding support to the specified text area. /// Warning: The folding manager is only valid for the text area's current document. The folding manager /// must be uninstalled before the text area is bound to a different document. /// </summary> /// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns> public static FoldingManager Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); return new FoldingManagerInstallation(textArea); } /// <summary> /// Uninstalls the folding manager. /// </summary> /// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception> public static void Uninstall(FoldingManager manager) { if (manager == null) throw new ArgumentNullException(nameof(manager)); if (manager is FoldingManagerInstallation installation) { installation.Uninstall(); } else { throw new ArgumentException("FoldingManager was not created using FoldingManager.Install"); } } private sealed class FoldingManagerInstallation : FoldingManager { private TextArea _textArea; private FoldingMargin _margin; private FoldingElementGenerator _generator; public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document) { _textArea = textArea; _margin = new FoldingMargin { FoldingManager = this }; _generator = new FoldingElementGenerator { FoldingManager = this }; textArea.LeftMargins.Add(_margin); textArea.TextView.Services.AddService(typeof(FoldingManager), this); // HACK: folding only works correctly when it has highest priority textArea.TextView.ElementGenerators.Insert(0, _generator); textArea.Caret.PositionChanged += TextArea_Caret_PositionChanged; } /* void DemoMode() { foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm }; foldingMargin = new FoldingMargin { FoldingManager = fm }; foldingMarginBorder = new Border { Child = foldingMargin, Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0) }; foldingMarginBorder.SizeChanged += UpdateTextViewClip; textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator); textEditor.TextArea.LeftMargins.Add(foldingMarginBorder); } void UpdateTextViewClip(object sender, SizeChangedEventArgs e) { textEditor.TextArea.TextView.Clip = new RectangleGeometry( new Rect(-foldingMarginBorder.ActualWidth, 0, textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth, textEditor.TextArea.TextView.ActualHeight)); } */ public void Uninstall() { Clear(); if (_textArea != null) { _textArea.Caret.PositionChanged -= TextArea_Caret_PositionChanged; _textArea.LeftMargins.Remove(_margin); _textArea.TextView.ElementGenerators.Remove(_generator); _textArea.TextView.Services.RemoveService(typeof(FoldingManager)); _margin = null; _generator = null; _textArea = null; } } private void TextArea_Caret_PositionChanged(object sender, EventArgs e) { // Expand Foldings when Caret is moved into them. var caretOffset = _textArea.Caret.Offset; foreach (var s in GetFoldingsContaining(caretOffset)) { if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) { s.IsFolded = false; } } } } #endregion } } <MSG> Fix only first fold is preserved when updating foldings #110 https://github.com/icsharpcode/AvalonEdit/pull/110 <DFF> @@ -272,12 +272,12 @@ namespace AvaloniaEdit.Folding if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; - _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } + _isFirstUpdate = false; // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) {
1
Fix only first fold is preserved when updating foldings #110
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062021
<NME> FoldingManager.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Threading; namespace AvaloniaEdit.Folding { /// <summary> /// Stores a list of foldings for a specific TextView and TextDocument. /// </summary> public class FoldingManager { internal TextDocument Document { get; } internal List<TextView> TextViews { get; } = new List<TextView>(); private readonly TextSegmentCollection<FoldingSection> _foldings; private bool _isFirstUpdate = true; #region Constructor /// <summary> /// Creates a new FoldingManager instance. /// </summary> public FoldingManager(TextDocument document) { Document = document ?? throw new ArgumentNullException(nameof(document)); _foldings = new TextSegmentCollection<FoldingSection>(); Dispatcher.UIThread.VerifyAccess(); TextDocumentWeakEventManager.Changed.AddHandler(document, OnDocumentChanged); } #endregion #region ReceiveWeakEvent private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { _foldings.UpdateOffsets(e); var newEndOffset = e.Offset + e.InsertionLength; // extend end offset to the end of the line (including delimiter) var endLine = Document.GetLineByOffset(newEndOffset); newEndOffset = endLine.Offset + endLine.TotalLength; foreach (var affectedFolding in _foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) { if (affectedFolding.Length == 0) { RemoveFolding(affectedFolding); } else { affectedFolding.ValidateCollapsedLineSections(); } } } #endregion #region Manage TextViews internal void AddToTextView(TextView textView) { if (textView == null || TextViews.Contains(textView)) throw new ArgumentException(); TextViews.Add(textView); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { Array.Resize(ref fs.CollapsedSections, TextViews.Count); fs.ValidateCollapsedLineSections(); } } } internal void RemoveFromTextView(TextView textView) { var pos = TextViews.IndexOf(textView); if (pos < 0) throw new ArgumentException(); TextViews.RemoveAt(pos); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { var c = new CollapsedLineSection[TextViews.Count]; Array.Copy(fs.CollapsedSections, 0, c, 0, pos); fs.CollapsedSections[pos].Uncollapse(); Array.Copy(fs.CollapsedSections, pos + 1, c, pos, c.Length - pos); fs.CollapsedSections = c; } } } internal void Redraw() { foreach (var textView in TextViews) textView.Redraw(); } internal void Redraw(FoldingSection fs) { foreach (var textView in TextViews) textView.Redraw(fs); } #endregion #region Create / Remove / Clear /// <summary> /// Creates a folding for the specified text section. /// </summary> public FoldingSection CreateFolding(int startOffset, int endOffset) { if (startOffset >= endOffset) throw new ArgumentException("startOffset must be less than endOffset"); if (startOffset < 0 || endOffset > Document.TextLength) throw new ArgumentException("Folding must be within document boundary"); var fs = new FoldingSection(this, startOffset, endOffset); _foldings.Add(fs); Redraw(fs); return fs; } /// <summary> /// Removes a folding section from this manager. /// </summary> public void RemoveFolding(FoldingSection fs) { if (fs == null) throw new ArgumentNullException(nameof(fs)); fs.IsFolded = false; _foldings.Remove(fs); Redraw(fs); } /// <summary> /// Removes all folding sections. /// </summary> public void Clear() { Dispatcher.UIThread.VerifyAccess(); foreach (var s in _foldings) s.IsFolded = false; _foldings.Clear(); Redraw(); } #endregion #region Get...Folding /// <summary> /// Gets all foldings in this manager. /// The foldings are returned sorted by start offset; /// for multiple foldings at the same offset the order is undefined. /// </summary> public IEnumerable<FoldingSection> AllFoldings => _foldings; /// <summary> /// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts. /// Returns -1 if there are no foldings after <paramref name="startOffset"/>. /// </summary> public int GetNextFoldedFoldingStart(int startOffset) { var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && !fs.IsFolded) fs = _foldings.GetNextSegment(fs); return fs?.StartOffset ?? -1; } /// <summary> /// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to /// <paramref name="startOffset"/>. /// Returns null if there are no foldings after <paramref name="startOffset"/>. /// </summary> public FoldingSection GetNextFolding(int startOffset) { // TODO: returns the longest folding instead of any folding at the first position after startOffset return _foldings.FindFirstSegmentWithStartAfter(startOffset); } /// <summary> /// Gets all foldings that start exactly at <paramref name="startOffset"/>. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset) { var result = new List<FoldingSection>(); var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && fs.StartOffset == startOffset) { result.Add(fs); fs = _foldings.GetNextSegment(fs); } return new ReadOnlyCollection<FoldingSection>(result); } /// <summary> /// Gets all foldings that contain <paramref name="offset" />. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset) { return _foldings.FindSegmentsContaining(offset); } #endregion #region UpdateFoldings /// <summary> /// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings. /// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state /// (<see cref="FoldingSection.IsFolded"/>) for existing foldings. /// </summary> /// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param> /// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after /// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>. /// Use -1 for this parameter if there were no parse errors.</param> public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset) { if (newFoldings == null) throw new ArgumentNullException(nameof(newFoldings)); if (firstErrorOffset < 0) firstErrorOffset = int.MaxValue; var oldFoldings = AllFoldings.ToArray(); var oldFoldingIndex = 0; var previousStartOffset = 0; // merge new foldings into old foldings so that sections keep being collapsed // both oldFoldings and newFoldings are sorted by start offset foreach (var newFolding in newFoldings) { // ensure newFoldings are sorted correctly if (newFolding.StartOffset < previousStartOffset) throw new ArgumentException("newFoldings must be sorted by start offset"); previousStartOffset = newFolding.StartOffset; if (newFolding.StartOffset == newFolding.EndOffset) continue; // ignore zero-length foldings // remove old foldings that were skipped while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) { RemoveFolding(oldFoldings[oldFoldingIndex++]); } FoldingSection section; // reuse current folding if its matching: if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) { section = oldFoldings[oldFoldingIndex++]; section.Length = newFolding.EndOffset - newFolding.StartOffset; } else { // no matching current folding; create a new one: section = CreateFolding(newFolding.StartOffset, newFolding.EndOffset); // auto-close #regions only when opening the document if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) { var oldSection = oldFoldings[oldFoldingIndex++]; if (oldSection.StartOffset >= firstErrorOffset) break; RemoveFolding(oldSection); } } #endregion #region Install /// <summary> /// Adds Folding support to the specified text area. /// Warning: The folding manager is only valid for the text area's current document. The folding manager /// must be uninstalled before the text area is bound to a different document. /// </summary> /// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns> public static FoldingManager Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); return new FoldingManagerInstallation(textArea); } /// <summary> /// Uninstalls the folding manager. /// </summary> /// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception> public static void Uninstall(FoldingManager manager) { if (manager == null) throw new ArgumentNullException(nameof(manager)); if (manager is FoldingManagerInstallation installation) { installation.Uninstall(); } else { throw new ArgumentException("FoldingManager was not created using FoldingManager.Install"); } } private sealed class FoldingManagerInstallation : FoldingManager { private TextArea _textArea; private FoldingMargin _margin; private FoldingElementGenerator _generator; public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document) { _textArea = textArea; _margin = new FoldingMargin { FoldingManager = this }; _generator = new FoldingElementGenerator { FoldingManager = this }; textArea.LeftMargins.Add(_margin); textArea.TextView.Services.AddService(typeof(FoldingManager), this); // HACK: folding only works correctly when it has highest priority textArea.TextView.ElementGenerators.Insert(0, _generator); textArea.Caret.PositionChanged += TextArea_Caret_PositionChanged; } /* void DemoMode() { foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm }; foldingMargin = new FoldingMargin { FoldingManager = fm }; foldingMarginBorder = new Border { Child = foldingMargin, Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0) }; foldingMarginBorder.SizeChanged += UpdateTextViewClip; textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator); textEditor.TextArea.LeftMargins.Add(foldingMarginBorder); } void UpdateTextViewClip(object sender, SizeChangedEventArgs e) { textEditor.TextArea.TextView.Clip = new RectangleGeometry( new Rect(-foldingMarginBorder.ActualWidth, 0, textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth, textEditor.TextArea.TextView.ActualHeight)); } */ public void Uninstall() { Clear(); if (_textArea != null) { _textArea.Caret.PositionChanged -= TextArea_Caret_PositionChanged; _textArea.LeftMargins.Remove(_margin); _textArea.TextView.ElementGenerators.Remove(_generator); _textArea.TextView.Services.RemoveService(typeof(FoldingManager)); _margin = null; _generator = null; _textArea = null; } } private void TextArea_Caret_PositionChanged(object sender, EventArgs e) { // Expand Foldings when Caret is moved into them. var caretOffset = _textArea.Caret.Offset; foreach (var s in GetFoldingsContaining(caretOffset)) { if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) { s.IsFolded = false; } } } } #endregion } } <MSG> Fix only first fold is preserved when updating foldings #110 https://github.com/icsharpcode/AvalonEdit/pull/110 <DFF> @@ -272,12 +272,12 @@ namespace AvaloniaEdit.Folding if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; - _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } + _isFirstUpdate = false; // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) {
1
Fix only first fold is preserved when updating foldings #110
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062022
<NME> FoldingManager.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Threading; namespace AvaloniaEdit.Folding { /// <summary> /// Stores a list of foldings for a specific TextView and TextDocument. /// </summary> public class FoldingManager { internal TextDocument Document { get; } internal List<TextView> TextViews { get; } = new List<TextView>(); private readonly TextSegmentCollection<FoldingSection> _foldings; private bool _isFirstUpdate = true; #region Constructor /// <summary> /// Creates a new FoldingManager instance. /// </summary> public FoldingManager(TextDocument document) { Document = document ?? throw new ArgumentNullException(nameof(document)); _foldings = new TextSegmentCollection<FoldingSection>(); Dispatcher.UIThread.VerifyAccess(); TextDocumentWeakEventManager.Changed.AddHandler(document, OnDocumentChanged); } #endregion #region ReceiveWeakEvent private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { _foldings.UpdateOffsets(e); var newEndOffset = e.Offset + e.InsertionLength; // extend end offset to the end of the line (including delimiter) var endLine = Document.GetLineByOffset(newEndOffset); newEndOffset = endLine.Offset + endLine.TotalLength; foreach (var affectedFolding in _foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) { if (affectedFolding.Length == 0) { RemoveFolding(affectedFolding); } else { affectedFolding.ValidateCollapsedLineSections(); } } } #endregion #region Manage TextViews internal void AddToTextView(TextView textView) { if (textView == null || TextViews.Contains(textView)) throw new ArgumentException(); TextViews.Add(textView); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { Array.Resize(ref fs.CollapsedSections, TextViews.Count); fs.ValidateCollapsedLineSections(); } } } internal void RemoveFromTextView(TextView textView) { var pos = TextViews.IndexOf(textView); if (pos < 0) throw new ArgumentException(); TextViews.RemoveAt(pos); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { var c = new CollapsedLineSection[TextViews.Count]; Array.Copy(fs.CollapsedSections, 0, c, 0, pos); fs.CollapsedSections[pos].Uncollapse(); Array.Copy(fs.CollapsedSections, pos + 1, c, pos, c.Length - pos); fs.CollapsedSections = c; } } } internal void Redraw() { foreach (var textView in TextViews) textView.Redraw(); } internal void Redraw(FoldingSection fs) { foreach (var textView in TextViews) textView.Redraw(fs); } #endregion #region Create / Remove / Clear /// <summary> /// Creates a folding for the specified text section. /// </summary> public FoldingSection CreateFolding(int startOffset, int endOffset) { if (startOffset >= endOffset) throw new ArgumentException("startOffset must be less than endOffset"); if (startOffset < 0 || endOffset > Document.TextLength) throw new ArgumentException("Folding must be within document boundary"); var fs = new FoldingSection(this, startOffset, endOffset); _foldings.Add(fs); Redraw(fs); return fs; } /// <summary> /// Removes a folding section from this manager. /// </summary> public void RemoveFolding(FoldingSection fs) { if (fs == null) throw new ArgumentNullException(nameof(fs)); fs.IsFolded = false; _foldings.Remove(fs); Redraw(fs); } /// <summary> /// Removes all folding sections. /// </summary> public void Clear() { Dispatcher.UIThread.VerifyAccess(); foreach (var s in _foldings) s.IsFolded = false; _foldings.Clear(); Redraw(); } #endregion #region Get...Folding /// <summary> /// Gets all foldings in this manager. /// The foldings are returned sorted by start offset; /// for multiple foldings at the same offset the order is undefined. /// </summary> public IEnumerable<FoldingSection> AllFoldings => _foldings; /// <summary> /// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts. /// Returns -1 if there are no foldings after <paramref name="startOffset"/>. /// </summary> public int GetNextFoldedFoldingStart(int startOffset) { var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && !fs.IsFolded) fs = _foldings.GetNextSegment(fs); return fs?.StartOffset ?? -1; } /// <summary> /// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to /// <paramref name="startOffset"/>. /// Returns null if there are no foldings after <paramref name="startOffset"/>. /// </summary> public FoldingSection GetNextFolding(int startOffset) { // TODO: returns the longest folding instead of any folding at the first position after startOffset return _foldings.FindFirstSegmentWithStartAfter(startOffset); } /// <summary> /// Gets all foldings that start exactly at <paramref name="startOffset"/>. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset) { var result = new List<FoldingSection>(); var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && fs.StartOffset == startOffset) { result.Add(fs); fs = _foldings.GetNextSegment(fs); } return new ReadOnlyCollection<FoldingSection>(result); } /// <summary> /// Gets all foldings that contain <paramref name="offset" />. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset) { return _foldings.FindSegmentsContaining(offset); } #endregion #region UpdateFoldings /// <summary> /// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings. /// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state /// (<see cref="FoldingSection.IsFolded"/>) for existing foldings. /// </summary> /// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param> /// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after /// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>. /// Use -1 for this parameter if there were no parse errors.</param> public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset) { if (newFoldings == null) throw new ArgumentNullException(nameof(newFoldings)); if (firstErrorOffset < 0) firstErrorOffset = int.MaxValue; var oldFoldings = AllFoldings.ToArray(); var oldFoldingIndex = 0; var previousStartOffset = 0; // merge new foldings into old foldings so that sections keep being collapsed // both oldFoldings and newFoldings are sorted by start offset foreach (var newFolding in newFoldings) { // ensure newFoldings are sorted correctly if (newFolding.StartOffset < previousStartOffset) throw new ArgumentException("newFoldings must be sorted by start offset"); previousStartOffset = newFolding.StartOffset; if (newFolding.StartOffset == newFolding.EndOffset) continue; // ignore zero-length foldings // remove old foldings that were skipped while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) { RemoveFolding(oldFoldings[oldFoldingIndex++]); } FoldingSection section; // reuse current folding if its matching: if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) { section = oldFoldings[oldFoldingIndex++]; section.Length = newFolding.EndOffset - newFolding.StartOffset; } else { // no matching current folding; create a new one: section = CreateFolding(newFolding.StartOffset, newFolding.EndOffset); // auto-close #regions only when opening the document if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) { var oldSection = oldFoldings[oldFoldingIndex++]; if (oldSection.StartOffset >= firstErrorOffset) break; RemoveFolding(oldSection); } } #endregion #region Install /// <summary> /// Adds Folding support to the specified text area. /// Warning: The folding manager is only valid for the text area's current document. The folding manager /// must be uninstalled before the text area is bound to a different document. /// </summary> /// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns> public static FoldingManager Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); return new FoldingManagerInstallation(textArea); } /// <summary> /// Uninstalls the folding manager. /// </summary> /// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception> public static void Uninstall(FoldingManager manager) { if (manager == null) throw new ArgumentNullException(nameof(manager)); if (manager is FoldingManagerInstallation installation) { installation.Uninstall(); } else { throw new ArgumentException("FoldingManager was not created using FoldingManager.Install"); } } private sealed class FoldingManagerInstallation : FoldingManager { private TextArea _textArea; private FoldingMargin _margin; private FoldingElementGenerator _generator; public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document) { _textArea = textArea; _margin = new FoldingMargin { FoldingManager = this }; _generator = new FoldingElementGenerator { FoldingManager = this }; textArea.LeftMargins.Add(_margin); textArea.TextView.Services.AddService(typeof(FoldingManager), this); // HACK: folding only works correctly when it has highest priority textArea.TextView.ElementGenerators.Insert(0, _generator); textArea.Caret.PositionChanged += TextArea_Caret_PositionChanged; } /* void DemoMode() { foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm }; foldingMargin = new FoldingMargin { FoldingManager = fm }; foldingMarginBorder = new Border { Child = foldingMargin, Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0) }; foldingMarginBorder.SizeChanged += UpdateTextViewClip; textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator); textEditor.TextArea.LeftMargins.Add(foldingMarginBorder); } void UpdateTextViewClip(object sender, SizeChangedEventArgs e) { textEditor.TextArea.TextView.Clip = new RectangleGeometry( new Rect(-foldingMarginBorder.ActualWidth, 0, textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth, textEditor.TextArea.TextView.ActualHeight)); } */ public void Uninstall() { Clear(); if (_textArea != null) { _textArea.Caret.PositionChanged -= TextArea_Caret_PositionChanged; _textArea.LeftMargins.Remove(_margin); _textArea.TextView.ElementGenerators.Remove(_generator); _textArea.TextView.Services.RemoveService(typeof(FoldingManager)); _margin = null; _generator = null; _textArea = null; } } private void TextArea_Caret_PositionChanged(object sender, EventArgs e) { // Expand Foldings when Caret is moved into them. var caretOffset = _textArea.Caret.Offset; foreach (var s in GetFoldingsContaining(caretOffset)) { if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) { s.IsFolded = false; } } } } #endregion } } <MSG> Fix only first fold is preserved when updating foldings #110 https://github.com/icsharpcode/AvalonEdit/pull/110 <DFF> @@ -272,12 +272,12 @@ namespace AvaloniaEdit.Folding if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; - _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } + _isFirstUpdate = false; // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) {
1
Fix only first fold is preserved when updating foldings #110
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062023
<NME> FoldingManager.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Threading; namespace AvaloniaEdit.Folding { /// <summary> /// Stores a list of foldings for a specific TextView and TextDocument. /// </summary> public class FoldingManager { internal TextDocument Document { get; } internal List<TextView> TextViews { get; } = new List<TextView>(); private readonly TextSegmentCollection<FoldingSection> _foldings; private bool _isFirstUpdate = true; #region Constructor /// <summary> /// Creates a new FoldingManager instance. /// </summary> public FoldingManager(TextDocument document) { Document = document ?? throw new ArgumentNullException(nameof(document)); _foldings = new TextSegmentCollection<FoldingSection>(); Dispatcher.UIThread.VerifyAccess(); TextDocumentWeakEventManager.Changed.AddHandler(document, OnDocumentChanged); } #endregion #region ReceiveWeakEvent private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { _foldings.UpdateOffsets(e); var newEndOffset = e.Offset + e.InsertionLength; // extend end offset to the end of the line (including delimiter) var endLine = Document.GetLineByOffset(newEndOffset); newEndOffset = endLine.Offset + endLine.TotalLength; foreach (var affectedFolding in _foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) { if (affectedFolding.Length == 0) { RemoveFolding(affectedFolding); } else { affectedFolding.ValidateCollapsedLineSections(); } } } #endregion #region Manage TextViews internal void AddToTextView(TextView textView) { if (textView == null || TextViews.Contains(textView)) throw new ArgumentException(); TextViews.Add(textView); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { Array.Resize(ref fs.CollapsedSections, TextViews.Count); fs.ValidateCollapsedLineSections(); } } } internal void RemoveFromTextView(TextView textView) { var pos = TextViews.IndexOf(textView); if (pos < 0) throw new ArgumentException(); TextViews.RemoveAt(pos); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { var c = new CollapsedLineSection[TextViews.Count]; Array.Copy(fs.CollapsedSections, 0, c, 0, pos); fs.CollapsedSections[pos].Uncollapse(); Array.Copy(fs.CollapsedSections, pos + 1, c, pos, c.Length - pos); fs.CollapsedSections = c; } } } internal void Redraw() { foreach (var textView in TextViews) textView.Redraw(); } internal void Redraw(FoldingSection fs) { foreach (var textView in TextViews) textView.Redraw(fs); } #endregion #region Create / Remove / Clear /// <summary> /// Creates a folding for the specified text section. /// </summary> public FoldingSection CreateFolding(int startOffset, int endOffset) { if (startOffset >= endOffset) throw new ArgumentException("startOffset must be less than endOffset"); if (startOffset < 0 || endOffset > Document.TextLength) throw new ArgumentException("Folding must be within document boundary"); var fs = new FoldingSection(this, startOffset, endOffset); _foldings.Add(fs); Redraw(fs); return fs; } /// <summary> /// Removes a folding section from this manager. /// </summary> public void RemoveFolding(FoldingSection fs) { if (fs == null) throw new ArgumentNullException(nameof(fs)); fs.IsFolded = false; _foldings.Remove(fs); Redraw(fs); } /// <summary> /// Removes all folding sections. /// </summary> public void Clear() { Dispatcher.UIThread.VerifyAccess(); foreach (var s in _foldings) s.IsFolded = false; _foldings.Clear(); Redraw(); } #endregion #region Get...Folding /// <summary> /// Gets all foldings in this manager. /// The foldings are returned sorted by start offset; /// for multiple foldings at the same offset the order is undefined. /// </summary> public IEnumerable<FoldingSection> AllFoldings => _foldings; /// <summary> /// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts. /// Returns -1 if there are no foldings after <paramref name="startOffset"/>. /// </summary> public int GetNextFoldedFoldingStart(int startOffset) { var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && !fs.IsFolded) fs = _foldings.GetNextSegment(fs); return fs?.StartOffset ?? -1; } /// <summary> /// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to /// <paramref name="startOffset"/>. /// Returns null if there are no foldings after <paramref name="startOffset"/>. /// </summary> public FoldingSection GetNextFolding(int startOffset) { // TODO: returns the longest folding instead of any folding at the first position after startOffset return _foldings.FindFirstSegmentWithStartAfter(startOffset); } /// <summary> /// Gets all foldings that start exactly at <paramref name="startOffset"/>. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset) { var result = new List<FoldingSection>(); var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && fs.StartOffset == startOffset) { result.Add(fs); fs = _foldings.GetNextSegment(fs); } return new ReadOnlyCollection<FoldingSection>(result); } /// <summary> /// Gets all foldings that contain <paramref name="offset" />. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset) { return _foldings.FindSegmentsContaining(offset); } #endregion #region UpdateFoldings /// <summary> /// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings. /// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state /// (<see cref="FoldingSection.IsFolded"/>) for existing foldings. /// </summary> /// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param> /// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after /// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>. /// Use -1 for this parameter if there were no parse errors.</param> public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset) { if (newFoldings == null) throw new ArgumentNullException(nameof(newFoldings)); if (firstErrorOffset < 0) firstErrorOffset = int.MaxValue; var oldFoldings = AllFoldings.ToArray(); var oldFoldingIndex = 0; var previousStartOffset = 0; // merge new foldings into old foldings so that sections keep being collapsed // both oldFoldings and newFoldings are sorted by start offset foreach (var newFolding in newFoldings) { // ensure newFoldings are sorted correctly if (newFolding.StartOffset < previousStartOffset) throw new ArgumentException("newFoldings must be sorted by start offset"); previousStartOffset = newFolding.StartOffset; if (newFolding.StartOffset == newFolding.EndOffset) continue; // ignore zero-length foldings // remove old foldings that were skipped while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) { RemoveFolding(oldFoldings[oldFoldingIndex++]); } FoldingSection section; // reuse current folding if its matching: if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) { section = oldFoldings[oldFoldingIndex++]; section.Length = newFolding.EndOffset - newFolding.StartOffset; } else { // no matching current folding; create a new one: section = CreateFolding(newFolding.StartOffset, newFolding.EndOffset); // auto-close #regions only when opening the document if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) { var oldSection = oldFoldings[oldFoldingIndex++]; if (oldSection.StartOffset >= firstErrorOffset) break; RemoveFolding(oldSection); } } #endregion #region Install /// <summary> /// Adds Folding support to the specified text area. /// Warning: The folding manager is only valid for the text area's current document. The folding manager /// must be uninstalled before the text area is bound to a different document. /// </summary> /// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns> public static FoldingManager Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); return new FoldingManagerInstallation(textArea); } /// <summary> /// Uninstalls the folding manager. /// </summary> /// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception> public static void Uninstall(FoldingManager manager) { if (manager == null) throw new ArgumentNullException(nameof(manager)); if (manager is FoldingManagerInstallation installation) { installation.Uninstall(); } else { throw new ArgumentException("FoldingManager was not created using FoldingManager.Install"); } } private sealed class FoldingManagerInstallation : FoldingManager { private TextArea _textArea; private FoldingMargin _margin; private FoldingElementGenerator _generator; public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document) { _textArea = textArea; _margin = new FoldingMargin { FoldingManager = this }; _generator = new FoldingElementGenerator { FoldingManager = this }; textArea.LeftMargins.Add(_margin); textArea.TextView.Services.AddService(typeof(FoldingManager), this); // HACK: folding only works correctly when it has highest priority textArea.TextView.ElementGenerators.Insert(0, _generator); textArea.Caret.PositionChanged += TextArea_Caret_PositionChanged; } /* void DemoMode() { foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm }; foldingMargin = new FoldingMargin { FoldingManager = fm }; foldingMarginBorder = new Border { Child = foldingMargin, Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0) }; foldingMarginBorder.SizeChanged += UpdateTextViewClip; textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator); textEditor.TextArea.LeftMargins.Add(foldingMarginBorder); } void UpdateTextViewClip(object sender, SizeChangedEventArgs e) { textEditor.TextArea.TextView.Clip = new RectangleGeometry( new Rect(-foldingMarginBorder.ActualWidth, 0, textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth, textEditor.TextArea.TextView.ActualHeight)); } */ public void Uninstall() { Clear(); if (_textArea != null) { _textArea.Caret.PositionChanged -= TextArea_Caret_PositionChanged; _textArea.LeftMargins.Remove(_margin); _textArea.TextView.ElementGenerators.Remove(_generator); _textArea.TextView.Services.RemoveService(typeof(FoldingManager)); _margin = null; _generator = null; _textArea = null; } } private void TextArea_Caret_PositionChanged(object sender, EventArgs e) { // Expand Foldings when Caret is moved into them. var caretOffset = _textArea.Caret.Offset; foreach (var s in GetFoldingsContaining(caretOffset)) { if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) { s.IsFolded = false; } } } } #endregion } } <MSG> Fix only first fold is preserved when updating foldings #110 https://github.com/icsharpcode/AvalonEdit/pull/110 <DFF> @@ -272,12 +272,12 @@ namespace AvaloniaEdit.Folding if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; - _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } + _isFirstUpdate = false; // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) {
1
Fix only first fold is preserved when updating foldings #110
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062024
<NME> FoldingManager.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Threading; namespace AvaloniaEdit.Folding { /// <summary> /// Stores a list of foldings for a specific TextView and TextDocument. /// </summary> public class FoldingManager { internal TextDocument Document { get; } internal List<TextView> TextViews { get; } = new List<TextView>(); private readonly TextSegmentCollection<FoldingSection> _foldings; private bool _isFirstUpdate = true; #region Constructor /// <summary> /// Creates a new FoldingManager instance. /// </summary> public FoldingManager(TextDocument document) { Document = document ?? throw new ArgumentNullException(nameof(document)); _foldings = new TextSegmentCollection<FoldingSection>(); Dispatcher.UIThread.VerifyAccess(); TextDocumentWeakEventManager.Changed.AddHandler(document, OnDocumentChanged); } #endregion #region ReceiveWeakEvent private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { _foldings.UpdateOffsets(e); var newEndOffset = e.Offset + e.InsertionLength; // extend end offset to the end of the line (including delimiter) var endLine = Document.GetLineByOffset(newEndOffset); newEndOffset = endLine.Offset + endLine.TotalLength; foreach (var affectedFolding in _foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) { if (affectedFolding.Length == 0) { RemoveFolding(affectedFolding); } else { affectedFolding.ValidateCollapsedLineSections(); } } } #endregion #region Manage TextViews internal void AddToTextView(TextView textView) { if (textView == null || TextViews.Contains(textView)) throw new ArgumentException(); TextViews.Add(textView); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { Array.Resize(ref fs.CollapsedSections, TextViews.Count); fs.ValidateCollapsedLineSections(); } } } internal void RemoveFromTextView(TextView textView) { var pos = TextViews.IndexOf(textView); if (pos < 0) throw new ArgumentException(); TextViews.RemoveAt(pos); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { var c = new CollapsedLineSection[TextViews.Count]; Array.Copy(fs.CollapsedSections, 0, c, 0, pos); fs.CollapsedSections[pos].Uncollapse(); Array.Copy(fs.CollapsedSections, pos + 1, c, pos, c.Length - pos); fs.CollapsedSections = c; } } } internal void Redraw() { foreach (var textView in TextViews) textView.Redraw(); } internal void Redraw(FoldingSection fs) { foreach (var textView in TextViews) textView.Redraw(fs); } #endregion #region Create / Remove / Clear /// <summary> /// Creates a folding for the specified text section. /// </summary> public FoldingSection CreateFolding(int startOffset, int endOffset) { if (startOffset >= endOffset) throw new ArgumentException("startOffset must be less than endOffset"); if (startOffset < 0 || endOffset > Document.TextLength) throw new ArgumentException("Folding must be within document boundary"); var fs = new FoldingSection(this, startOffset, endOffset); _foldings.Add(fs); Redraw(fs); return fs; } /// <summary> /// Removes a folding section from this manager. /// </summary> public void RemoveFolding(FoldingSection fs) { if (fs == null) throw new ArgumentNullException(nameof(fs)); fs.IsFolded = false; _foldings.Remove(fs); Redraw(fs); } /// <summary> /// Removes all folding sections. /// </summary> public void Clear() { Dispatcher.UIThread.VerifyAccess(); foreach (var s in _foldings) s.IsFolded = false; _foldings.Clear(); Redraw(); } #endregion #region Get...Folding /// <summary> /// Gets all foldings in this manager. /// The foldings are returned sorted by start offset; /// for multiple foldings at the same offset the order is undefined. /// </summary> public IEnumerable<FoldingSection> AllFoldings => _foldings; /// <summary> /// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts. /// Returns -1 if there are no foldings after <paramref name="startOffset"/>. /// </summary> public int GetNextFoldedFoldingStart(int startOffset) { var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && !fs.IsFolded) fs = _foldings.GetNextSegment(fs); return fs?.StartOffset ?? -1; } /// <summary> /// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to /// <paramref name="startOffset"/>. /// Returns null if there are no foldings after <paramref name="startOffset"/>. /// </summary> public FoldingSection GetNextFolding(int startOffset) { // TODO: returns the longest folding instead of any folding at the first position after startOffset return _foldings.FindFirstSegmentWithStartAfter(startOffset); } /// <summary> /// Gets all foldings that start exactly at <paramref name="startOffset"/>. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset) { var result = new List<FoldingSection>(); var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && fs.StartOffset == startOffset) { result.Add(fs); fs = _foldings.GetNextSegment(fs); } return new ReadOnlyCollection<FoldingSection>(result); } /// <summary> /// Gets all foldings that contain <paramref name="offset" />. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset) { return _foldings.FindSegmentsContaining(offset); } #endregion #region UpdateFoldings /// <summary> /// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings. /// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state /// (<see cref="FoldingSection.IsFolded"/>) for existing foldings. /// </summary> /// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param> /// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after /// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>. /// Use -1 for this parameter if there were no parse errors.</param> public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset) { if (newFoldings == null) throw new ArgumentNullException(nameof(newFoldings)); if (firstErrorOffset < 0) firstErrorOffset = int.MaxValue; var oldFoldings = AllFoldings.ToArray(); var oldFoldingIndex = 0; var previousStartOffset = 0; // merge new foldings into old foldings so that sections keep being collapsed // both oldFoldings and newFoldings are sorted by start offset foreach (var newFolding in newFoldings) { // ensure newFoldings are sorted correctly if (newFolding.StartOffset < previousStartOffset) throw new ArgumentException("newFoldings must be sorted by start offset"); previousStartOffset = newFolding.StartOffset; if (newFolding.StartOffset == newFolding.EndOffset) continue; // ignore zero-length foldings // remove old foldings that were skipped while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) { RemoveFolding(oldFoldings[oldFoldingIndex++]); } FoldingSection section; // reuse current folding if its matching: if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) { section = oldFoldings[oldFoldingIndex++]; section.Length = newFolding.EndOffset - newFolding.StartOffset; } else { // no matching current folding; create a new one: section = CreateFolding(newFolding.StartOffset, newFolding.EndOffset); // auto-close #regions only when opening the document if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) { var oldSection = oldFoldings[oldFoldingIndex++]; if (oldSection.StartOffset >= firstErrorOffset) break; RemoveFolding(oldSection); } } #endregion #region Install /// <summary> /// Adds Folding support to the specified text area. /// Warning: The folding manager is only valid for the text area's current document. The folding manager /// must be uninstalled before the text area is bound to a different document. /// </summary> /// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns> public static FoldingManager Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); return new FoldingManagerInstallation(textArea); } /// <summary> /// Uninstalls the folding manager. /// </summary> /// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception> public static void Uninstall(FoldingManager manager) { if (manager == null) throw new ArgumentNullException(nameof(manager)); if (manager is FoldingManagerInstallation installation) { installation.Uninstall(); } else { throw new ArgumentException("FoldingManager was not created using FoldingManager.Install"); } } private sealed class FoldingManagerInstallation : FoldingManager { private TextArea _textArea; private FoldingMargin _margin; private FoldingElementGenerator _generator; public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document) { _textArea = textArea; _margin = new FoldingMargin { FoldingManager = this }; _generator = new FoldingElementGenerator { FoldingManager = this }; textArea.LeftMargins.Add(_margin); textArea.TextView.Services.AddService(typeof(FoldingManager), this); // HACK: folding only works correctly when it has highest priority textArea.TextView.ElementGenerators.Insert(0, _generator); textArea.Caret.PositionChanged += TextArea_Caret_PositionChanged; } /* void DemoMode() { foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm }; foldingMargin = new FoldingMargin { FoldingManager = fm }; foldingMarginBorder = new Border { Child = foldingMargin, Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0) }; foldingMarginBorder.SizeChanged += UpdateTextViewClip; textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator); textEditor.TextArea.LeftMargins.Add(foldingMarginBorder); } void UpdateTextViewClip(object sender, SizeChangedEventArgs e) { textEditor.TextArea.TextView.Clip = new RectangleGeometry( new Rect(-foldingMarginBorder.ActualWidth, 0, textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth, textEditor.TextArea.TextView.ActualHeight)); } */ public void Uninstall() { Clear(); if (_textArea != null) { _textArea.Caret.PositionChanged -= TextArea_Caret_PositionChanged; _textArea.LeftMargins.Remove(_margin); _textArea.TextView.ElementGenerators.Remove(_generator); _textArea.TextView.Services.RemoveService(typeof(FoldingManager)); _margin = null; _generator = null; _textArea = null; } } private void TextArea_Caret_PositionChanged(object sender, EventArgs e) { // Expand Foldings when Caret is moved into them. var caretOffset = _textArea.Caret.Offset; foreach (var s in GetFoldingsContaining(caretOffset)) { if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) { s.IsFolded = false; } } } } #endregion } } <MSG> Fix only first fold is preserved when updating foldings #110 https://github.com/icsharpcode/AvalonEdit/pull/110 <DFF> @@ -272,12 +272,12 @@ namespace AvaloniaEdit.Folding if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; - _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } + _isFirstUpdate = false; // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) {
1
Fix only first fold is preserved when updating foldings #110
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062025
<NME> FoldingManager.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Threading; namespace AvaloniaEdit.Folding { /// <summary> /// Stores a list of foldings for a specific TextView and TextDocument. /// </summary> public class FoldingManager { internal TextDocument Document { get; } internal List<TextView> TextViews { get; } = new List<TextView>(); private readonly TextSegmentCollection<FoldingSection> _foldings; private bool _isFirstUpdate = true; #region Constructor /// <summary> /// Creates a new FoldingManager instance. /// </summary> public FoldingManager(TextDocument document) { Document = document ?? throw new ArgumentNullException(nameof(document)); _foldings = new TextSegmentCollection<FoldingSection>(); Dispatcher.UIThread.VerifyAccess(); TextDocumentWeakEventManager.Changed.AddHandler(document, OnDocumentChanged); } #endregion #region ReceiveWeakEvent private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { _foldings.UpdateOffsets(e); var newEndOffset = e.Offset + e.InsertionLength; // extend end offset to the end of the line (including delimiter) var endLine = Document.GetLineByOffset(newEndOffset); newEndOffset = endLine.Offset + endLine.TotalLength; foreach (var affectedFolding in _foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) { if (affectedFolding.Length == 0) { RemoveFolding(affectedFolding); } else { affectedFolding.ValidateCollapsedLineSections(); } } } #endregion #region Manage TextViews internal void AddToTextView(TextView textView) { if (textView == null || TextViews.Contains(textView)) throw new ArgumentException(); TextViews.Add(textView); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { Array.Resize(ref fs.CollapsedSections, TextViews.Count); fs.ValidateCollapsedLineSections(); } } } internal void RemoveFromTextView(TextView textView) { var pos = TextViews.IndexOf(textView); if (pos < 0) throw new ArgumentException(); TextViews.RemoveAt(pos); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { var c = new CollapsedLineSection[TextViews.Count]; Array.Copy(fs.CollapsedSections, 0, c, 0, pos); fs.CollapsedSections[pos].Uncollapse(); Array.Copy(fs.CollapsedSections, pos + 1, c, pos, c.Length - pos); fs.CollapsedSections = c; } } } internal void Redraw() { foreach (var textView in TextViews) textView.Redraw(); } internal void Redraw(FoldingSection fs) { foreach (var textView in TextViews) textView.Redraw(fs); } #endregion #region Create / Remove / Clear /// <summary> /// Creates a folding for the specified text section. /// </summary> public FoldingSection CreateFolding(int startOffset, int endOffset) { if (startOffset >= endOffset) throw new ArgumentException("startOffset must be less than endOffset"); if (startOffset < 0 || endOffset > Document.TextLength) throw new ArgumentException("Folding must be within document boundary"); var fs = new FoldingSection(this, startOffset, endOffset); _foldings.Add(fs); Redraw(fs); return fs; } /// <summary> /// Removes a folding section from this manager. /// </summary> public void RemoveFolding(FoldingSection fs) { if (fs == null) throw new ArgumentNullException(nameof(fs)); fs.IsFolded = false; _foldings.Remove(fs); Redraw(fs); } /// <summary> /// Removes all folding sections. /// </summary> public void Clear() { Dispatcher.UIThread.VerifyAccess(); foreach (var s in _foldings) s.IsFolded = false; _foldings.Clear(); Redraw(); } #endregion #region Get...Folding /// <summary> /// Gets all foldings in this manager. /// The foldings are returned sorted by start offset; /// for multiple foldings at the same offset the order is undefined. /// </summary> public IEnumerable<FoldingSection> AllFoldings => _foldings; /// <summary> /// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts. /// Returns -1 if there are no foldings after <paramref name="startOffset"/>. /// </summary> public int GetNextFoldedFoldingStart(int startOffset) { var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && !fs.IsFolded) fs = _foldings.GetNextSegment(fs); return fs?.StartOffset ?? -1; } /// <summary> /// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to /// <paramref name="startOffset"/>. /// Returns null if there are no foldings after <paramref name="startOffset"/>. /// </summary> public FoldingSection GetNextFolding(int startOffset) { // TODO: returns the longest folding instead of any folding at the first position after startOffset return _foldings.FindFirstSegmentWithStartAfter(startOffset); } /// <summary> /// Gets all foldings that start exactly at <paramref name="startOffset"/>. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset) { var result = new List<FoldingSection>(); var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && fs.StartOffset == startOffset) { result.Add(fs); fs = _foldings.GetNextSegment(fs); } return new ReadOnlyCollection<FoldingSection>(result); } /// <summary> /// Gets all foldings that contain <paramref name="offset" />. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset) { return _foldings.FindSegmentsContaining(offset); } #endregion #region UpdateFoldings /// <summary> /// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings. /// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state /// (<see cref="FoldingSection.IsFolded"/>) for existing foldings. /// </summary> /// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param> /// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after /// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>. /// Use -1 for this parameter if there were no parse errors.</param> public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset) { if (newFoldings == null) throw new ArgumentNullException(nameof(newFoldings)); if (firstErrorOffset < 0) firstErrorOffset = int.MaxValue; var oldFoldings = AllFoldings.ToArray(); var oldFoldingIndex = 0; var previousStartOffset = 0; // merge new foldings into old foldings so that sections keep being collapsed // both oldFoldings and newFoldings are sorted by start offset foreach (var newFolding in newFoldings) { // ensure newFoldings are sorted correctly if (newFolding.StartOffset < previousStartOffset) throw new ArgumentException("newFoldings must be sorted by start offset"); previousStartOffset = newFolding.StartOffset; if (newFolding.StartOffset == newFolding.EndOffset) continue; // ignore zero-length foldings // remove old foldings that were skipped while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) { RemoveFolding(oldFoldings[oldFoldingIndex++]); } FoldingSection section; // reuse current folding if its matching: if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) { section = oldFoldings[oldFoldingIndex++]; section.Length = newFolding.EndOffset - newFolding.StartOffset; } else { // no matching current folding; create a new one: section = CreateFolding(newFolding.StartOffset, newFolding.EndOffset); // auto-close #regions only when opening the document if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) { var oldSection = oldFoldings[oldFoldingIndex++]; if (oldSection.StartOffset >= firstErrorOffset) break; RemoveFolding(oldSection); } } #endregion #region Install /// <summary> /// Adds Folding support to the specified text area. /// Warning: The folding manager is only valid for the text area's current document. The folding manager /// must be uninstalled before the text area is bound to a different document. /// </summary> /// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns> public static FoldingManager Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); return new FoldingManagerInstallation(textArea); } /// <summary> /// Uninstalls the folding manager. /// </summary> /// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception> public static void Uninstall(FoldingManager manager) { if (manager == null) throw new ArgumentNullException(nameof(manager)); if (manager is FoldingManagerInstallation installation) { installation.Uninstall(); } else { throw new ArgumentException("FoldingManager was not created using FoldingManager.Install"); } } private sealed class FoldingManagerInstallation : FoldingManager { private TextArea _textArea; private FoldingMargin _margin; private FoldingElementGenerator _generator; public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document) { _textArea = textArea; _margin = new FoldingMargin { FoldingManager = this }; _generator = new FoldingElementGenerator { FoldingManager = this }; textArea.LeftMargins.Add(_margin); textArea.TextView.Services.AddService(typeof(FoldingManager), this); // HACK: folding only works correctly when it has highest priority textArea.TextView.ElementGenerators.Insert(0, _generator); textArea.Caret.PositionChanged += TextArea_Caret_PositionChanged; } /* void DemoMode() { foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm }; foldingMargin = new FoldingMargin { FoldingManager = fm }; foldingMarginBorder = new Border { Child = foldingMargin, Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0) }; foldingMarginBorder.SizeChanged += UpdateTextViewClip; textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator); textEditor.TextArea.LeftMargins.Add(foldingMarginBorder); } void UpdateTextViewClip(object sender, SizeChangedEventArgs e) { textEditor.TextArea.TextView.Clip = new RectangleGeometry( new Rect(-foldingMarginBorder.ActualWidth, 0, textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth, textEditor.TextArea.TextView.ActualHeight)); } */ public void Uninstall() { Clear(); if (_textArea != null) { _textArea.Caret.PositionChanged -= TextArea_Caret_PositionChanged; _textArea.LeftMargins.Remove(_margin); _textArea.TextView.ElementGenerators.Remove(_generator); _textArea.TextView.Services.RemoveService(typeof(FoldingManager)); _margin = null; _generator = null; _textArea = null; } } private void TextArea_Caret_PositionChanged(object sender, EventArgs e) { // Expand Foldings when Caret is moved into them. var caretOffset = _textArea.Caret.Offset; foreach (var s in GetFoldingsContaining(caretOffset)) { if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) { s.IsFolded = false; } } } } #endregion } } <MSG> Fix only first fold is preserved when updating foldings #110 https://github.com/icsharpcode/AvalonEdit/pull/110 <DFF> @@ -272,12 +272,12 @@ namespace AvaloniaEdit.Folding if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; - _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } + _isFirstUpdate = false; // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) {
1
Fix only first fold is preserved when updating foldings #110
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062026
<NME> FoldingManager.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using Avalonia.Threading; namespace AvaloniaEdit.Folding { /// <summary> /// Stores a list of foldings for a specific TextView and TextDocument. /// </summary> public class FoldingManager { internal TextDocument Document { get; } internal List<TextView> TextViews { get; } = new List<TextView>(); private readonly TextSegmentCollection<FoldingSection> _foldings; private bool _isFirstUpdate = true; #region Constructor /// <summary> /// Creates a new FoldingManager instance. /// </summary> public FoldingManager(TextDocument document) { Document = document ?? throw new ArgumentNullException(nameof(document)); _foldings = new TextSegmentCollection<FoldingSection>(); Dispatcher.UIThread.VerifyAccess(); TextDocumentWeakEventManager.Changed.AddHandler(document, OnDocumentChanged); } #endregion #region ReceiveWeakEvent private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { _foldings.UpdateOffsets(e); var newEndOffset = e.Offset + e.InsertionLength; // extend end offset to the end of the line (including delimiter) var endLine = Document.GetLineByOffset(newEndOffset); newEndOffset = endLine.Offset + endLine.TotalLength; foreach (var affectedFolding in _foldings.FindOverlappingSegments(e.Offset, newEndOffset - e.Offset)) { if (affectedFolding.Length == 0) { RemoveFolding(affectedFolding); } else { affectedFolding.ValidateCollapsedLineSections(); } } } #endregion #region Manage TextViews internal void AddToTextView(TextView textView) { if (textView == null || TextViews.Contains(textView)) throw new ArgumentException(); TextViews.Add(textView); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { Array.Resize(ref fs.CollapsedSections, TextViews.Count); fs.ValidateCollapsedLineSections(); } } } internal void RemoveFromTextView(TextView textView) { var pos = TextViews.IndexOf(textView); if (pos < 0) throw new ArgumentException(); TextViews.RemoveAt(pos); foreach (var fs in _foldings) { if (fs.CollapsedSections != null) { var c = new CollapsedLineSection[TextViews.Count]; Array.Copy(fs.CollapsedSections, 0, c, 0, pos); fs.CollapsedSections[pos].Uncollapse(); Array.Copy(fs.CollapsedSections, pos + 1, c, pos, c.Length - pos); fs.CollapsedSections = c; } } } internal void Redraw() { foreach (var textView in TextViews) textView.Redraw(); } internal void Redraw(FoldingSection fs) { foreach (var textView in TextViews) textView.Redraw(fs); } #endregion #region Create / Remove / Clear /// <summary> /// Creates a folding for the specified text section. /// </summary> public FoldingSection CreateFolding(int startOffset, int endOffset) { if (startOffset >= endOffset) throw new ArgumentException("startOffset must be less than endOffset"); if (startOffset < 0 || endOffset > Document.TextLength) throw new ArgumentException("Folding must be within document boundary"); var fs = new FoldingSection(this, startOffset, endOffset); _foldings.Add(fs); Redraw(fs); return fs; } /// <summary> /// Removes a folding section from this manager. /// </summary> public void RemoveFolding(FoldingSection fs) { if (fs == null) throw new ArgumentNullException(nameof(fs)); fs.IsFolded = false; _foldings.Remove(fs); Redraw(fs); } /// <summary> /// Removes all folding sections. /// </summary> public void Clear() { Dispatcher.UIThread.VerifyAccess(); foreach (var s in _foldings) s.IsFolded = false; _foldings.Clear(); Redraw(); } #endregion #region Get...Folding /// <summary> /// Gets all foldings in this manager. /// The foldings are returned sorted by start offset; /// for multiple foldings at the same offset the order is undefined. /// </summary> public IEnumerable<FoldingSection> AllFoldings => _foldings; /// <summary> /// Gets the first offset greater or equal to <paramref name="startOffset"/> where a folded folding starts. /// Returns -1 if there are no foldings after <paramref name="startOffset"/>. /// </summary> public int GetNextFoldedFoldingStart(int startOffset) { var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && !fs.IsFolded) fs = _foldings.GetNextSegment(fs); return fs?.StartOffset ?? -1; } /// <summary> /// Gets the first folding with a <see cref="TextSegment.StartOffset"/> greater or equal to /// <paramref name="startOffset"/>. /// Returns null if there are no foldings after <paramref name="startOffset"/>. /// </summary> public FoldingSection GetNextFolding(int startOffset) { // TODO: returns the longest folding instead of any folding at the first position after startOffset return _foldings.FindFirstSegmentWithStartAfter(startOffset); } /// <summary> /// Gets all foldings that start exactly at <paramref name="startOffset"/>. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsAt(int startOffset) { var result = new List<FoldingSection>(); var fs = _foldings.FindFirstSegmentWithStartAfter(startOffset); while (fs != null && fs.StartOffset == startOffset) { result.Add(fs); fs = _foldings.GetNextSegment(fs); } return new ReadOnlyCollection<FoldingSection>(result); } /// <summary> /// Gets all foldings that contain <paramref name="offset" />. /// </summary> public ReadOnlyCollection<FoldingSection> GetFoldingsContaining(int offset) { return _foldings.FindSegmentsContaining(offset); } #endregion #region UpdateFoldings /// <summary> /// Updates the foldings in this <see cref="FoldingManager"/> using the given new foldings. /// This method will try to detect which new foldings correspond to which existing foldings; and will keep the state /// (<see cref="FoldingSection.IsFolded"/>) for existing foldings. /// </summary> /// <param name="newFoldings">The new set of foldings. These must be sorted by starting offset.</param> /// <param name="firstErrorOffset">The first position of a parse error. Existing foldings starting after /// this offset will be kept even if they don't appear in <paramref name="newFoldings"/>. /// Use -1 for this parameter if there were no parse errors.</param> public void UpdateFoldings(IEnumerable<NewFolding> newFoldings, int firstErrorOffset) { if (newFoldings == null) throw new ArgumentNullException(nameof(newFoldings)); if (firstErrorOffset < 0) firstErrorOffset = int.MaxValue; var oldFoldings = AllFoldings.ToArray(); var oldFoldingIndex = 0; var previousStartOffset = 0; // merge new foldings into old foldings so that sections keep being collapsed // both oldFoldings and newFoldings are sorted by start offset foreach (var newFolding in newFoldings) { // ensure newFoldings are sorted correctly if (newFolding.StartOffset < previousStartOffset) throw new ArgumentException("newFoldings must be sorted by start offset"); previousStartOffset = newFolding.StartOffset; if (newFolding.StartOffset == newFolding.EndOffset) continue; // ignore zero-length foldings // remove old foldings that were skipped while (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset > oldFoldings[oldFoldingIndex].StartOffset) { RemoveFolding(oldFoldings[oldFoldingIndex++]); } FoldingSection section; // reuse current folding if its matching: if (oldFoldingIndex < oldFoldings.Length && newFolding.StartOffset == oldFoldings[oldFoldingIndex].StartOffset) { section = oldFoldings[oldFoldingIndex++]; section.Length = newFolding.EndOffset - newFolding.StartOffset; } else { // no matching current folding; create a new one: section = CreateFolding(newFolding.StartOffset, newFolding.EndOffset); // auto-close #regions only when opening the document if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) { var oldSection = oldFoldings[oldFoldingIndex++]; if (oldSection.StartOffset >= firstErrorOffset) break; RemoveFolding(oldSection); } } #endregion #region Install /// <summary> /// Adds Folding support to the specified text area. /// Warning: The folding manager is only valid for the text area's current document. The folding manager /// must be uninstalled before the text area is bound to a different document. /// </summary> /// <returns>The <see cref="FoldingManager"/> that manages the list of foldings inside the text area.</returns> public static FoldingManager Install(TextArea textArea) { if (textArea == null) throw new ArgumentNullException(nameof(textArea)); return new FoldingManagerInstallation(textArea); } /// <summary> /// Uninstalls the folding manager. /// </summary> /// <exception cref="ArgumentException">The specified manager was not created using <see cref="Install"/>.</exception> public static void Uninstall(FoldingManager manager) { if (manager == null) throw new ArgumentNullException(nameof(manager)); if (manager is FoldingManagerInstallation installation) { installation.Uninstall(); } else { throw new ArgumentException("FoldingManager was not created using FoldingManager.Install"); } } private sealed class FoldingManagerInstallation : FoldingManager { private TextArea _textArea; private FoldingMargin _margin; private FoldingElementGenerator _generator; public FoldingManagerInstallation(TextArea textArea) : base(textArea.Document) { _textArea = textArea; _margin = new FoldingMargin { FoldingManager = this }; _generator = new FoldingElementGenerator { FoldingManager = this }; textArea.LeftMargins.Add(_margin); textArea.TextView.Services.AddService(typeof(FoldingManager), this); // HACK: folding only works correctly when it has highest priority textArea.TextView.ElementGenerators.Insert(0, _generator); textArea.Caret.PositionChanged += TextArea_Caret_PositionChanged; } /* void DemoMode() { foldingGenerator = new FoldingElementGenerator() { FoldingManager = fm }; foldingMargin = new FoldingMargin { FoldingManager = fm }; foldingMarginBorder = new Border { Child = foldingMargin, Background = new LinearGradientBrush(Colors.White, Colors.Transparent, 0) }; foldingMarginBorder.SizeChanged += UpdateTextViewClip; textEditor.TextArea.TextView.ElementGenerators.Add(foldingGenerator); textEditor.TextArea.LeftMargins.Add(foldingMarginBorder); } void UpdateTextViewClip(object sender, SizeChangedEventArgs e) { textEditor.TextArea.TextView.Clip = new RectangleGeometry( new Rect(-foldingMarginBorder.ActualWidth, 0, textEditor.TextArea.TextView.ActualWidth + foldingMarginBorder.ActualWidth, textEditor.TextArea.TextView.ActualHeight)); } */ public void Uninstall() { Clear(); if (_textArea != null) { _textArea.Caret.PositionChanged -= TextArea_Caret_PositionChanged; _textArea.LeftMargins.Remove(_margin); _textArea.TextView.ElementGenerators.Remove(_generator); _textArea.TextView.Services.RemoveService(typeof(FoldingManager)); _margin = null; _generator = null; _textArea = null; } } private void TextArea_Caret_PositionChanged(object sender, EventArgs e) { // Expand Foldings when Caret is moved into them. var caretOffset = _textArea.Caret.Offset; foreach (var s in GetFoldingsContaining(caretOffset)) { if (s.IsFolded && s.StartOffset < caretOffset && caretOffset < s.EndOffset) { s.IsFolded = false; } } } } #endregion } } <MSG> Fix only first fold is preserved when updating foldings #110 https://github.com/icsharpcode/AvalonEdit/pull/110 <DFF> @@ -272,12 +272,12 @@ namespace AvaloniaEdit.Folding if (_isFirstUpdate) { section.IsFolded = newFolding.DefaultClosed; - _isFirstUpdate = false; } section.Tag = newFolding; } section.Title = newFolding.Name; } + _isFirstUpdate = false; // remove all outstanding old foldings: while (oldFoldingIndex < oldFoldings.Length) {
1
Fix only first fold is preserved when updating foldings #110
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062027
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; using System.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private Thread ownerThread = Thread.CurrentThread; private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Allow TextDocument to transfer ownership <DFF> @@ -132,6 +132,27 @@ namespace AvaloniaEdit.Document private Thread ownerThread = Thread.CurrentThread; + /// <summary> + /// Transfers ownership of the document to another thread. + /// </summary> + /// <remarks> + /// <para> + /// The owner can be set to null, which means that no thread can access the document. But, if the document + /// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>. + /// </para> + /// </remarks> + public void SetOwnerThread(Thread newOwner) + { + // We need to lock here to ensure that in the null owner case, + // only one thread succeeds in taking ownership. + lock (_lockObject) { + if (ownerThread != null) { + VerifyAccess(); + } + ownerThread = newOwner; + } + } + private void VerifyAccess() { if(Thread.CurrentThread != ownerThread)
21
Allow TextDocument to transfer ownership
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062028
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; using System.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private Thread ownerThread = Thread.CurrentThread; private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Allow TextDocument to transfer ownership <DFF> @@ -132,6 +132,27 @@ namespace AvaloniaEdit.Document private Thread ownerThread = Thread.CurrentThread; + /// <summary> + /// Transfers ownership of the document to another thread. + /// </summary> + /// <remarks> + /// <para> + /// The owner can be set to null, which means that no thread can access the document. But, if the document + /// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>. + /// </para> + /// </remarks> + public void SetOwnerThread(Thread newOwner) + { + // We need to lock here to ensure that in the null owner case, + // only one thread succeeds in taking ownership. + lock (_lockObject) { + if (ownerThread != null) { + VerifyAccess(); + } + ownerThread = newOwner; + } + } + private void VerifyAccess() { if(Thread.CurrentThread != ownerThread)
21
Allow TextDocument to transfer ownership
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062029
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; using System.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private Thread ownerThread = Thread.CurrentThread; private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Allow TextDocument to transfer ownership <DFF> @@ -132,6 +132,27 @@ namespace AvaloniaEdit.Document private Thread ownerThread = Thread.CurrentThread; + /// <summary> + /// Transfers ownership of the document to another thread. + /// </summary> + /// <remarks> + /// <para> + /// The owner can be set to null, which means that no thread can access the document. But, if the document + /// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>. + /// </para> + /// </remarks> + public void SetOwnerThread(Thread newOwner) + { + // We need to lock here to ensure that in the null owner case, + // only one thread succeeds in taking ownership. + lock (_lockObject) { + if (ownerThread != null) { + VerifyAccess(); + } + ownerThread = newOwner; + } + } + private void VerifyAccess() { if(Thread.CurrentThread != ownerThread)
21
Allow TextDocument to transfer ownership
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062030
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; using System.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private Thread ownerThread = Thread.CurrentThread; private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Allow TextDocument to transfer ownership <DFF> @@ -132,6 +132,27 @@ namespace AvaloniaEdit.Document private Thread ownerThread = Thread.CurrentThread; + /// <summary> + /// Transfers ownership of the document to another thread. + /// </summary> + /// <remarks> + /// <para> + /// The owner can be set to null, which means that no thread can access the document. But, if the document + /// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>. + /// </para> + /// </remarks> + public void SetOwnerThread(Thread newOwner) + { + // We need to lock here to ensure that in the null owner case, + // only one thread succeeds in taking ownership. + lock (_lockObject) { + if (ownerThread != null) { + VerifyAccess(); + } + ownerThread = newOwner; + } + } + private void VerifyAccess() { if(Thread.CurrentThread != ownerThread)
21
Allow TextDocument to transfer ownership
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062031
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; using System.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private Thread ownerThread = Thread.CurrentThread; private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Allow TextDocument to transfer ownership <DFF> @@ -132,6 +132,27 @@ namespace AvaloniaEdit.Document private Thread ownerThread = Thread.CurrentThread; + /// <summary> + /// Transfers ownership of the document to another thread. + /// </summary> + /// <remarks> + /// <para> + /// The owner can be set to null, which means that no thread can access the document. But, if the document + /// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>. + /// </para> + /// </remarks> + public void SetOwnerThread(Thread newOwner) + { + // We need to lock here to ensure that in the null owner case, + // only one thread succeeds in taking ownership. + lock (_lockObject) { + if (ownerThread != null) { + VerifyAccess(); + } + ownerThread = newOwner; + } + } + private void VerifyAccess() { if(Thread.CurrentThread != ownerThread)
21
Allow TextDocument to transfer ownership
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062032
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; using System.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private Thread ownerThread = Thread.CurrentThread; private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Allow TextDocument to transfer ownership <DFF> @@ -132,6 +132,27 @@ namespace AvaloniaEdit.Document private Thread ownerThread = Thread.CurrentThread; + /// <summary> + /// Transfers ownership of the document to another thread. + /// </summary> + /// <remarks> + /// <para> + /// The owner can be set to null, which means that no thread can access the document. But, if the document + /// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>. + /// </para> + /// </remarks> + public void SetOwnerThread(Thread newOwner) + { + // We need to lock here to ensure that in the null owner case, + // only one thread succeeds in taking ownership. + lock (_lockObject) { + if (ownerThread != null) { + VerifyAccess(); + } + ownerThread = newOwner; + } + } + private void VerifyAccess() { if(Thread.CurrentThread != ownerThread)
21
Allow TextDocument to transfer ownership
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062033
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; using System.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private Thread ownerThread = Thread.CurrentThread; private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Allow TextDocument to transfer ownership <DFF> @@ -132,6 +132,27 @@ namespace AvaloniaEdit.Document private Thread ownerThread = Thread.CurrentThread; + /// <summary> + /// Transfers ownership of the document to another thread. + /// </summary> + /// <remarks> + /// <para> + /// The owner can be set to null, which means that no thread can access the document. But, if the document + /// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>. + /// </para> + /// </remarks> + public void SetOwnerThread(Thread newOwner) + { + // We need to lock here to ensure that in the null owner case, + // only one thread succeeds in taking ownership. + lock (_lockObject) { + if (ownerThread != null) { + VerifyAccess(); + } + ownerThread = newOwner; + } + } + private void VerifyAccess() { if(Thread.CurrentThread != ownerThread)
21
Allow TextDocument to transfer ownership
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062034
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; using System.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private Thread ownerThread = Thread.CurrentThread; private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Allow TextDocument to transfer ownership <DFF> @@ -132,6 +132,27 @@ namespace AvaloniaEdit.Document private Thread ownerThread = Thread.CurrentThread; + /// <summary> + /// Transfers ownership of the document to another thread. + /// </summary> + /// <remarks> + /// <para> + /// The owner can be set to null, which means that no thread can access the document. But, if the document + /// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>. + /// </para> + /// </remarks> + public void SetOwnerThread(Thread newOwner) + { + // We need to lock here to ensure that in the null owner case, + // only one thread succeeds in taking ownership. + lock (_lockObject) { + if (ownerThread != null) { + VerifyAccess(); + } + ownerThread = newOwner; + } + } + private void VerifyAccess() { if(Thread.CurrentThread != ownerThread)
21
Allow TextDocument to transfer ownership
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062035
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; using System.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private Thread ownerThread = Thread.CurrentThread; private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Allow TextDocument to transfer ownership <DFF> @@ -132,6 +132,27 @@ namespace AvaloniaEdit.Document private Thread ownerThread = Thread.CurrentThread; + /// <summary> + /// Transfers ownership of the document to another thread. + /// </summary> + /// <remarks> + /// <para> + /// The owner can be set to null, which means that no thread can access the document. But, if the document + /// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>. + /// </para> + /// </remarks> + public void SetOwnerThread(Thread newOwner) + { + // We need to lock here to ensure that in the null owner case, + // only one thread succeeds in taking ownership. + lock (_lockObject) { + if (ownerThread != null) { + VerifyAccess(); + } + ownerThread = newOwner; + } + } + private void VerifyAccess() { if(Thread.CurrentThread != ownerThread)
21
Allow TextDocument to transfer ownership
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062036
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; using System.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private Thread ownerThread = Thread.CurrentThread; private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Allow TextDocument to transfer ownership <DFF> @@ -132,6 +132,27 @@ namespace AvaloniaEdit.Document private Thread ownerThread = Thread.CurrentThread; + /// <summary> + /// Transfers ownership of the document to another thread. + /// </summary> + /// <remarks> + /// <para> + /// The owner can be set to null, which means that no thread can access the document. But, if the document + /// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>. + /// </para> + /// </remarks> + public void SetOwnerThread(Thread newOwner) + { + // We need to lock here to ensure that in the null owner case, + // only one thread succeeds in taking ownership. + lock (_lockObject) { + if (ownerThread != null) { + VerifyAccess(); + } + ownerThread = newOwner; + } + } + private void VerifyAccess() { if(Thread.CurrentThread != ownerThread)
21
Allow TextDocument to transfer ownership
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062037
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; using System.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private Thread ownerThread = Thread.CurrentThread; private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Allow TextDocument to transfer ownership <DFF> @@ -132,6 +132,27 @@ namespace AvaloniaEdit.Document private Thread ownerThread = Thread.CurrentThread; + /// <summary> + /// Transfers ownership of the document to another thread. + /// </summary> + /// <remarks> + /// <para> + /// The owner can be set to null, which means that no thread can access the document. But, if the document + /// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>. + /// </para> + /// </remarks> + public void SetOwnerThread(Thread newOwner) + { + // We need to lock here to ensure that in the null owner case, + // only one thread succeeds in taking ownership. + lock (_lockObject) { + if (ownerThread != null) { + VerifyAccess(); + } + ownerThread = newOwner; + } + } + private void VerifyAccess() { if(Thread.CurrentThread != ownerThread)
21
Allow TextDocument to transfer ownership
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062038
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; using System.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private Thread ownerThread = Thread.CurrentThread; private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Allow TextDocument to transfer ownership <DFF> @@ -132,6 +132,27 @@ namespace AvaloniaEdit.Document private Thread ownerThread = Thread.CurrentThread; + /// <summary> + /// Transfers ownership of the document to another thread. + /// </summary> + /// <remarks> + /// <para> + /// The owner can be set to null, which means that no thread can access the document. But, if the document + /// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>. + /// </para> + /// </remarks> + public void SetOwnerThread(Thread newOwner) + { + // We need to lock here to ensure that in the null owner case, + // only one thread succeeds in taking ownership. + lock (_lockObject) { + if (ownerThread != null) { + VerifyAccess(); + } + ownerThread = newOwner; + } + } + private void VerifyAccess() { if(Thread.CurrentThread != ownerThread)
21
Allow TextDocument to transfer ownership
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062039
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; using System.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private Thread ownerThread = Thread.CurrentThread; private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Allow TextDocument to transfer ownership <DFF> @@ -132,6 +132,27 @@ namespace AvaloniaEdit.Document private Thread ownerThread = Thread.CurrentThread; + /// <summary> + /// Transfers ownership of the document to another thread. + /// </summary> + /// <remarks> + /// <para> + /// The owner can be set to null, which means that no thread can access the document. But, if the document + /// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>. + /// </para> + /// </remarks> + public void SetOwnerThread(Thread newOwner) + { + // We need to lock here to ensure that in the null owner case, + // only one thread succeeds in taking ownership. + lock (_lockObject) { + if (ownerThread != null) { + VerifyAccess(); + } + ownerThread = newOwner; + } + } + private void VerifyAccess() { if(Thread.CurrentThread != ownerThread)
21
Allow TextDocument to transfer ownership
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062040
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; using System.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private Thread ownerThread = Thread.CurrentThread; private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Allow TextDocument to transfer ownership <DFF> @@ -132,6 +132,27 @@ namespace AvaloniaEdit.Document private Thread ownerThread = Thread.CurrentThread; + /// <summary> + /// Transfers ownership of the document to another thread. + /// </summary> + /// <remarks> + /// <para> + /// The owner can be set to null, which means that no thread can access the document. But, if the document + /// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>. + /// </para> + /// </remarks> + public void SetOwnerThread(Thread newOwner) + { + // We need to lock here to ensure that in the null owner case, + // only one thread succeeds in taking ownership. + lock (_lockObject) { + if (ownerThread != null) { + VerifyAccess(); + } + ownerThread = newOwner; + } + } + private void VerifyAccess() { if(Thread.CurrentThread != ownerThread)
21
Allow TextDocument to transfer ownership
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062041
<NME> TextDocument.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using AvaloniaEdit.Utils; using Avalonia.Threading; using System.Threading; namespace AvaloniaEdit.Document { /// <summary> /// This class is the main class of the text model. Basically, it is a <see cref="System.Text.StringBuilder"/> with events. /// </summary> /// <remarks> /// <b>Thread safety:</b> /// <inheritdoc cref="VerifyAccess"/> /// <para>However, there is a single method that is thread-safe: <see cref="CreateSnapshot()"/> (and its overloads).</para> /// </remarks> public sealed class TextDocument : IDocument, INotifyPropertyChanged { #region Thread ownership private readonly object _lockObject = new object(); #endregion #region Fields + Constructor private readonly Rope<char> _rope; private readonly DocumentLineTree _lineTree; private readonly LineManager _lineManager; private readonly TextAnchorTree _anchorTree; private readonly TextSourceVersionProvider _versionProvider = new TextSourceVersionProvider(); /// <summary> /// Create an empty text document. /// </summary> public TextDocument() : this(string.Empty.ToCharArray()) { } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(IEnumerable<char> initialText) { if (initialText == null) throw new ArgumentNullException(nameof(initialText)); _rope = new Rope<char>(initialText); _lineTree = new DocumentLineTree(this); _lineManager = new LineManager(_lineTree, this); _lineTrackers.CollectionChanged += delegate { _lineManager.UpdateListOfLineTrackers(); }; _anchorTree = new TextAnchorTree(this); _undoStack = new UndoStack(); FireChangeEvents(); } /// <summary> /// Create a new text document with the specified initial text. /// </summary> public TextDocument(ITextSource initialText) : this(GetTextFromTextSource(initialText)) { } // gets the text from a text source, directly retrieving the underlying rope where possible private static IEnumerable<char> GetTextFromTextSource(ITextSource textSource) { if (textSource == null) throw new ArgumentNullException(nameof(textSource)); if (textSource is RopeTextSource rts) { return rts.GetRope(); } if (textSource is TextDocument doc) { return doc._rope; } return textSource.Text.ToCharArray(); } #endregion #region Text private void ThrowIfRangeInvalid(int offset, int length) { if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } if (length < 0 || offset + length > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(length), length, "0 <= length, offset(" + offset + ")+length <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } } /// <inheritdoc/> public string GetText(int offset, int length) { VerifyAccess(); return _rope.ToString(offset, length); } private Thread ownerThread = Thread.CurrentThread; private void VerifyAccess() { if(Thread.CurrentThread != ownerThread) { throw new InvalidOperationException("Call from invalid thread."); } } /// <summary> /// Retrieves the text for a portion of the document. /// </summary> public string GetText(ISegment segment) { if (segment == null) throw new ArgumentNullException(nameof(segment)); return GetText(segment.Offset, segment.Length); } /// <inheritdoc/> public int IndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.IndexOf(c, startIndex, count); } /// <inheritdoc/> public int LastIndexOf(char c, int startIndex, int count) { DebugVerifyAccess(); return _rope.LastIndexOf(c, startIndex, count); } /// <inheritdoc/> public int IndexOfAny(char[] anyOf, int startIndex, int count) { DebugVerifyAccess(); // frequently called (NewLineFinder), so must be fast in release builds return _rope.IndexOfAny(anyOf, startIndex, count); } /// <inheritdoc/> public int IndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.IndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public int LastIndexOf(string searchText, int startIndex, int count, StringComparison comparisonType) { DebugVerifyAccess(); return _rope.LastIndexOf(searchText, startIndex, count, comparisonType); } /// <inheritdoc/> public char GetCharAt(int offset) { DebugVerifyAccess(); // frequently called, so must be fast in release builds return _rope[offset]; } private WeakReference _cachedText; /// <summary> /// Gets/Sets the text of the whole document. /// </summary> public string Text { get { VerifyAccess(); var completeText = _cachedText?.Target as string; if (completeText == null) { completeText = _rope.ToString(); _cachedText = new WeakReference(completeText); } return completeText; } set { VerifyAccess(); if (value == null) throw new ArgumentNullException(nameof(value)); Replace(0, _rope.Length, value); } } /// <summary> /// This event is called after a group of changes is completed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextChanged; event EventHandler IDocument.ChangeCompleted { add => TextChanged += value; remove => TextChanged -= value; } /// <inheritdoc/> public int TextLength { get { VerifyAccess(); return _rope.Length; } } /// <summary> /// Is raised when the TextLength property changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler TextLengthChanged; /// <summary> /// Is raised before the document changes. /// </summary> /// <remarks> /// <para>Here is the order in which events are raised during a document update:</para> /// <list type="bullet"> /// <item><description><b><see cref="BeginUpdate">BeginUpdate()</see></b></description> /// <list type="bullet"> /// <item><description>Start of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateStarted"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="Insert(int,string)">Insert()</see> / <see cref="Remove(int,int)">Remove()</see> / <see cref="Replace(int,int,string)">Replace()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="Changing"/> event is raised</description></item> /// <item><description>The document is changed</description></item> /// <item><description><see cref="TextAnchor.Deleted">TextAnchor.Deleted</see> event is raised if anchors were /// in the deleted text portion</description></item> /// <item><description><see cref="Changed"/> event is raised</description></item> /// </list></item> /// <item><description><b><see cref="EndUpdate">EndUpdate()</see></b></description> /// <list type="bullet"> /// <item><description><see cref="TextChanged"/> event is raised</description></item> /// <item><description><see cref="PropertyChanged"/> event is raised (for the Text, TextLength, LineCount properties, in that order)</description></item> /// <item><description>End of change group (on undo stack)</description></item> /// <item><description><see cref="UpdateFinished"/> event is raised</description></item> /// </list></item> /// </list> /// <para> /// If the insert/remove/replace methods are called without a call to <c>BeginUpdate()</c>, /// they will call <c>BeginUpdate()</c> and <c>EndUpdate()</c> to ensure no change happens outside of <c>UpdateStarted</c>/<c>UpdateFinished</c>. /// </para><para> /// There can be multiple document changes between the <c>BeginUpdate()</c> and <c>EndUpdate()</c> calls. /// In this case, the events associated with EndUpdate will be raised only once after the whole document update is done. /// </para><para> /// The <see cref="UndoStack"/> listens to the <c>UpdateStarted</c> and <c>UpdateFinished</c> events to group all changes into a single undo step. /// </para> /// </remarks> public event EventHandler<DocumentChangeEventArgs> Changing; // Unfortunately EventHandler<T> is invariant, so we have to use two separate events private event EventHandler<TextChangeEventArgs> TextChangingInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanging { add => TextChangingInternal += value; remove => TextChangingInternal -= value; } /// <summary> /// Is raised after the document has changed. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler<DocumentChangeEventArgs> Changed; private event EventHandler<TextChangeEventArgs> TextChangedInternal; event EventHandler<TextChangeEventArgs> IDocument.TextChanged { add => TextChangedInternal += value; remove => TextChangedInternal -= value; } /// <summary> /// Creates a snapshot of the current text. /// </summary> /// <remarks> /// <para>This method returns an immutable snapshot of the document, and may be safely called even when /// the document's owner thread is concurrently modifying the document. /// </para><para> /// This special thread-safety guarantee is valid only for TextDocument.CreateSnapshot(), not necessarily for other /// classes implementing ITextSource.CreateSnapshot(). /// </para><para> /// </para> /// </remarks> public ITextSource CreateSnapshot() { lock (_lockObject) { return new RopeTextSource(_rope, _versionProvider.CurrentVersion); } } /// <summary> /// Creates a snapshot of a part of the current text. /// </summary> /// <remarks><inheritdoc cref="CreateSnapshot()"/></remarks> public ITextSource CreateSnapshot(int offset, int length) { lock (_lockObject) { return new RopeTextSource(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public ITextSourceVersion Version => _versionProvider.CurrentVersion; /// <inheritdoc/> public TextReader CreateReader() { lock (_lockObject) { return new RopeTextReader(_rope); } } /// <inheritdoc/> public TextReader CreateReader(int offset, int length) { lock (_lockObject) { return new RopeTextReader(_rope.GetRange(offset, length)); } } /// <inheritdoc/> public void WriteTextTo(TextWriter writer) { VerifyAccess(); _rope.WriteTo(writer, 0, _rope.Length); } /// <inheritdoc/> public void WriteTextTo(TextWriter writer, int offset, int length) { VerifyAccess(); _rope.WriteTo(writer, offset, length); } private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; #endregion #region BeginUpdate / EndUpdate private int _beginUpdateCount; /// <summary> /// Gets if an update is running. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public bool IsInUpdate { get { VerifyAccess(); return _beginUpdateCount > 0; } } /// <summary> /// Immediately calls <see cref="BeginUpdate()"/>, /// and returns an IDisposable that calls <see cref="EndUpdate()"/>. /// </summary> /// <remarks><inheritdoc cref="BeginUpdate"/></remarks> public IDisposable RunUpdate() { BeginUpdate(); return new CallbackOnDispose(EndUpdate); } /// <summary> /// <para>Begins a group of document changes.</para> /// <para>Some events are suspended until EndUpdate is called, and the <see cref="UndoStack"/> will /// group all changes into a single action.</para> /// <para>Calling BeginUpdate several times increments a counter, only after the appropriate number /// of EndUpdate calls the events resume their work.</para> /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void BeginUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot change document within another document change."); _beginUpdateCount++; if (_beginUpdateCount == 1) { _undoStack.StartUndoGroup(); UpdateStarted?.Invoke(this, EventArgs.Empty); } } /// <summary> /// Ends a group of document changes. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public void EndUpdate() { VerifyAccess(); if (InDocumentChanging) throw new InvalidOperationException("Cannot end update within document change."); if (_beginUpdateCount == 0) throw new InvalidOperationException("No update is active."); if (_beginUpdateCount == 1) { // fire change events inside the change group - event handlers might add additional // document changes to the change group FireChangeEvents(); _undoStack.EndUndoGroup(); _beginUpdateCount = 0; UpdateFinished?.Invoke(this, EventArgs.Empty); } else { _beginUpdateCount -= 1; } } /// <summary> /// Occurs when a document change starts. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateStarted; /// <summary> /// Occurs when a document change is finished. /// </summary> /// <remarks><inheritdoc cref="Changing"/></remarks> public event EventHandler UpdateFinished; void IDocument.StartUndoableAction() { BeginUpdate(); } void IDocument.EndUndoableAction() { EndUpdate(); } IDisposable IDocument.OpenUndoGroup() { return RunUpdate(); } #endregion #region Fire events after update private int _oldTextLength; private int _oldLineCount; private bool _fireTextChanged; /// <summary> /// Fires TextChanged, TextLengthChanged, LineCountChanged if required. /// </summary> internal void FireChangeEvents() { // it may be necessary to fire the event multiple times if the document is changed // from inside the event handlers while (_fireTextChanged) { _fireTextChanged = false; TextChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("Text"); var textLength = _rope.Length; if (textLength != _oldTextLength) { _oldTextLength = textLength; TextLengthChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("TextLength"); } var lineCount = _lineTree.LineCount; if (lineCount != _oldLineCount) { _oldLineCount = lineCount; LineCountChanged?.Invoke(this, EventArgs.Empty); OnPropertyChanged("LineCount"); } } } #endregion #region Insert / Remove / Replace /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, string text) { Replace(offset, 0, new StringTextSource(text), null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <remarks> /// Anchors positioned exactly at the insertion offset will move according to their movement type. /// For AnchorMovementType.Default, they will move behind the inserted text. /// The caret will also move behind the inserted text. /// </remarks> public void Insert(int offset, ITextSource text) { Replace(offset, 0, text, null); } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, string text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, new StringTextSource(text), OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, new StringTextSource(text), null); } } /// <summary> /// Inserts text. /// </summary> /// <param name="offset">The offset at which the text is inserted.</param> /// <param name="text">The new text.</param> /// <param name="defaultAnchorMovementType"> /// Anchors positioned exactly at the insertion offset will move according to the anchor's movement type. /// For AnchorMovementType.Default, they will move according to the movement type specified by this parameter. /// The caret will also move according to the <paramref name="defaultAnchorMovementType"/> parameter. /// </param> public void Insert(int offset, ITextSource text, AnchorMovementType defaultAnchorMovementType) { if (defaultAnchorMovementType == AnchorMovementType.BeforeInsertion) { Replace(offset, 0, text, OffsetChangeMappingType.KeepAnchorBeforeInsertion); } else { Replace(offset, 0, text, null); } } /// <summary> /// Removes text. /// </summary> public void Remove(ISegment segment) { Replace(segment, string.Empty); } /// <summary> /// Removes text. /// </summary> /// <param name="offset">Starting offset of the text to be removed.</param> /// <param name="length">Length of the text to be removed.</param> public void Remove(int offset, int length) { Replace(offset, length, StringTextSource.Empty); } internal bool InDocumentChanging; /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, string text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> public void Replace(ISegment segment, ITextSource text) { if (segment == null) throw new ArgumentNullException(nameof(segment)); Replace(segment.Offset, segment.Length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, string text) { Replace(offset, length, new StringTextSource(text), null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> public void Replace(int offset, int length, ITextSource text) { Replace(offset, length, text, null); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, string text, OffsetChangeMappingType offsetChangeMappingType) { Replace(offset, length, new StringTextSource(text), offsetChangeMappingType); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMappingType">The offsetChangeMappingType determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave.</param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMappingType offsetChangeMappingType) { if (text == null) throw new ArgumentNullException(nameof(text)); // Please see OffsetChangeMappingType XML comments for details on how these modes work. switch (offsetChangeMappingType) { case OffsetChangeMappingType.Normal: Replace(offset, length, text, null); break; case OffsetChangeMappingType.KeepAnchorBeforeInsertion: Replace(offset, length, text, OffsetChangeMap.FromSingleElement( new OffsetChangeMapEntry(offset, length, text.TextLength, false, true))); break; case OffsetChangeMappingType.RemoveAndInsert: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else { var map = new OffsetChangeMap(2) { new OffsetChangeMapEntry(offset, length, 0), new OffsetChangeMapEntry(offset, 0, text.TextLength) }; map.Freeze(); Replace(offset, length, text, map); } break; case OffsetChangeMappingType.CharacterReplace: if (length == 0 || text.TextLength == 0) { // only insertion or only removal? // OffsetChangeMappingType doesn't matter, just use Normal. Replace(offset, length, text, null); } else if (text.TextLength > length) { // look at OffsetChangeMappingType.CharacterReplace XML comments on why we need to replace // the last character var entry = new OffsetChangeMapEntry(offset + length - 1, 1, 1 + text.TextLength - length); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else if (text.TextLength < length) { var entry = new OffsetChangeMapEntry(offset + text.TextLength, length - text.TextLength, 0, true, false); Replace(offset, length, text, OffsetChangeMap.FromSingleElement(entry)); } else { Replace(offset, length, text, OffsetChangeMap.Empty); } break; default: throw new ArgumentOutOfRangeException(nameof(offsetChangeMappingType), offsetChangeMappingType, "Invalid enum value"); } } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, string text, OffsetChangeMap offsetChangeMap) { Replace(offset, length, new StringTextSource(text), offsetChangeMap); } /// <summary> /// Replaces text. /// </summary> /// <param name="offset">The starting offset of the text to be replaced.</param> /// <param name="length">The length of the text to be replaced.</param> /// <param name="text">The new text.</param> /// <param name="offsetChangeMap">The offsetChangeMap determines how offsets inside the old text are mapped to the new text. /// This affects how the anchors and segments inside the replaced region behave. /// If you pass null (the default when using one of the other overloads), the offsets are changed as /// in OffsetChangeMappingType.Normal mode. /// If you pass OffsetChangeMap.Empty, then everything will stay in its old place (OffsetChangeMappingType.CharacterReplace mode). /// The offsetChangeMap must be a valid 'explanation' for the document change. See <see cref="OffsetChangeMap.IsValidForDocumentChange"/>. /// Passing an OffsetChangeMap to the Replace method will automatically freeze it to ensure the thread safety of the resulting /// DocumentChangeEventArgs instance. /// </param> public void Replace(int offset, int length, ITextSource text, OffsetChangeMap offsetChangeMap) { text = text?.CreateSnapshot() ?? throw new ArgumentNullException(nameof(text)); offsetChangeMap?.Freeze(); // Ensure that all changes take place inside an update group. // Will also take care of throwing an exception if inDocumentChanging is set. BeginUpdate(); try { // protect document change against corruption by other changes inside the event handlers InDocumentChanging = true; try { // The range verification must wait until after the BeginUpdate() call because the document // might be modified inside the UpdateStarted event. ThrowIfRangeInvalid(offset, length); DoReplace(offset, length, text, offsetChangeMap); } finally { InDocumentChanging = false; } } finally { EndUpdate(); } } private void DoReplace(int offset, int length, ITextSource newText, OffsetChangeMap offsetChangeMap) { if (length == 0 && newText.TextLength == 0) return; // trying to replace a single character in 'Normal' mode? // for single characters, 'CharacterReplace' mode is equivalent, but more performant // (we don't have to touch the anchorTree at all in 'CharacterReplace' mode) if (length == 1 && newText.TextLength == 1 && offsetChangeMap == null) offsetChangeMap = OffsetChangeMap.Empty; ITextSource removedText; if (length == 0) { removedText = StringTextSource.Empty; } else if (length < 100) { removedText = new StringTextSource(_rope.ToString(offset, length)); } else { // use a rope if the removed string is long removedText = new RopeTextSource(_rope.GetRange(offset, length)); } var args = new DocumentChangeEventArgs(offset, removedText, newText, offsetChangeMap); // fire DocumentChanging event Changing?.Invoke(this, args); TextChangingInternal?.Invoke(this, args); _undoStack.Push(this, args); _cachedText = null; // reset cache of complete document text _fireTextChanged = true; var delayedEvents = new DelayedEvents(); lock (_lockObject) { // create linked list of checkpoints _versionProvider.AppendChange(args); // now update the textBuffer and lineTree if (offset == 0 && length == _rope.Length) { // optimize replacing the whole document _rope.Clear(); if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(0, newRopeTextSource.GetRope()); else _rope.InsertText(0, newText.Text); _lineManager.Rebuild(); } else { _rope.RemoveRange(offset, length); _lineManager.Remove(offset, length); #if DEBUG _lineTree.CheckProperties(); #endif if (newText is RopeTextSource newRopeTextSource) _rope.InsertRange(offset, newRopeTextSource.GetRope()); else _rope.InsertText(offset, newText.Text); _lineManager.Insert(offset, newText); #if DEBUG _lineTree.CheckProperties(); #endif } } // update text anchors if (offsetChangeMap == null) { _anchorTree.HandleTextChange(args.CreateSingleChangeMapEntry(), delayedEvents); } else { foreach (var entry in offsetChangeMap) { _anchorTree.HandleTextChange(entry, delayedEvents); } } _lineManager.ChangeComplete(args); // raise delayed events after our data structures are consistent again delayedEvents.RaiseEvents(); // fire DocumentChanged event Changed?.Invoke(this, args); TextChangedInternal?.Invoke(this, args); } #endregion #region GetLineBy... /// <summary> /// Gets a read-only list of lines. /// </summary> /// <remarks><inheritdoc cref="DocumentLine"/></remarks> public IList<DocumentLine> Lines => _lineTree; /// <summary> /// Gets a line by the line number: O(log n) /// </summary> public DocumentLine GetLineByNumber(int number) { VerifyAccess(); if (number < 1 || number > _lineTree.LineCount) throw new ArgumentOutOfRangeException(nameof(number), number, "Value must be between 1 and " + _lineTree.LineCount); return _lineTree.GetByNumber(number); } IDocumentLine IDocument.GetLineByNumber(int lineNumber) { return GetLineByNumber(lineNumber); } /// <summary> /// Gets a document lines by offset. /// Runtime: O(log n) /// </summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.Int32.ToString")] public DocumentLine GetLineByOffset(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length); } return _lineTree.GetByOffset(offset); } IDocumentLine IDocument.GetLineByOffset(int offset) { return GetLineByOffset(offset); } #endregion #region GetOffset / GetLocation /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(TextLocation location) { return GetOffset(location.Line, location.Column); } /// <summary> /// Gets the offset from a text location. /// </summary> /// <seealso cref="GetLocation"/> public int GetOffset(int line, int column) { var docLine = GetLineByNumber(line); if (column <= 0) return docLine.Offset; if (column > docLine.Length) return docLine.EndOffset; return docLine.Offset + column - 1; } /// <summary> /// Gets the location from an offset. /// </summary> /// <seealso cref="GetOffset(TextLocation)"/> public TextLocation GetLocation(int offset) { var line = GetLineByOffset(offset); return new TextLocation(line.LineNumber, offset - line.Offset + 1); } #endregion #region Line Trackers private readonly ObservableCollection<ILineTracker> _lineTrackers = new ObservableCollection<ILineTracker>(); /// <summary> /// Gets the list of <see cref="ILineTracker"/>s attached to this document. /// You can add custom line trackers to this list. /// </summary> public IList<ILineTracker> LineTrackers { get { VerifyAccess(); return _lineTrackers; } } #endregion #region UndoStack public UndoStack _undoStack; /// <summary> /// Gets the <see cref="UndoStack"/> of the document. /// </summary> /// <remarks>This property can also be used to set the undo stack, e.g. for sharing a common undo stack between multiple documents.</remarks> public UndoStack UndoStack { get => _undoStack; set { if (value == null) throw new ArgumentNullException(); if (value != _undoStack) { _undoStack.ClearAll(); // first clear old undo stack, so that it can't be used to perform unexpected changes on this document // ClearAll() will also throw an exception when it's not safe to replace the undo stack (e.g. update is currently in progress) _undoStack = value; OnPropertyChanged("UndoStack"); } } } #endregion #region CreateAnchor /// <summary> /// Creates a new <see cref="TextAnchor"/> at the specified offset. /// </summary> /// <inheritdoc cref="TextAnchor" select="remarks|example"/> public TextAnchor CreateAnchor(int offset) { VerifyAccess(); if (offset < 0 || offset > _rope.Length) { throw new ArgumentOutOfRangeException(nameof(offset), offset, "0 <= offset <= " + _rope.Length.ToString(CultureInfo.InvariantCulture)); } return _anchorTree.CreateAnchor(offset); } ITextAnchor IDocument.CreateAnchor(int offset) { return CreateAnchor(offset); } #endregion #region LineCount /// <summary> /// Gets the total number of lines in the document. /// Runtime: O(1). /// </summary> public int LineCount { get { VerifyAccess(); return _lineTree.LineCount; } } /// <summary> /// Is raised when the LineCount property changes. /// </summary> public event EventHandler LineCountChanged; #endregion #region Debugging [Conditional("DEBUG")] internal void DebugVerifyAccess() { VerifyAccess(); } /// <summary> /// Gets the document lines tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetLineTreeAsString() { #if DEBUG return _lineTree.GetTreeAsString(); #else return "Not available in release build."; #endif } /// <summary> /// Gets the text anchor tree in string form. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] internal string GetTextAnchorTreeAsString() { #if DEBUG return _anchorTree.GetTreeAsString(); #else return "Not available in release build."; #endif } #endregion #region Service Provider private IServiceProvider _serviceProvider; internal IServiceProvider ServiceProvider { get { VerifyAccess(); if (_serviceProvider == null) { var container = new ServiceContainer(); container.AddService(this); container.AddService<IDocument>(this); _serviceProvider = container; } return _serviceProvider; } set { VerifyAccess(); _serviceProvider = value ?? throw new ArgumentNullException(nameof(value)); } } object IServiceProvider.GetService(Type serviceType) { return ServiceProvider.GetService(serviceType); } #endregion #region FileName private string _fileName; /// <inheritdoc/> public event EventHandler FileNameChanged; private void OnFileNameChanged(EventArgs e) { FileNameChanged?.Invoke(this, e); } /// <inheritdoc/> public string FileName { get { return _fileName; } set { if (_fileName != value) { _fileName = value; OnFileNameChanged(EventArgs.Empty); } } } #endregion } } <MSG> Allow TextDocument to transfer ownership <DFF> @@ -132,6 +132,27 @@ namespace AvaloniaEdit.Document private Thread ownerThread = Thread.CurrentThread; + /// <summary> + /// Transfers ownership of the document to another thread. + /// </summary> + /// <remarks> + /// <para> + /// The owner can be set to null, which means that no thread can access the document. But, if the document + /// has no owner thread, any thread may take ownership by calling <see cref="SetOwnerThread"/>. + /// </para> + /// </remarks> + public void SetOwnerThread(Thread newOwner) + { + // We need to lock here to ensure that in the null owner case, + // only one thread succeeds in taking ownership. + lock (_lockObject) { + if (ownerThread != null) { + VerifyAccess(); + } + ownerThread = newOwner; + } + } + private void VerifyAccess() { if(Thread.CurrentThread != ownerThread)
21
Allow TextDocument to transfer ownership
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10062042
<NME> define.js <BEF> /*jslint browser:true, node:true, laxbreak:true*/ 'use strict'; module.exports = function(fm) { /** * Defines a module. * * Options: * * - `name {String}` the name of the module * - `tag {String}` the tagName to use for the root element * - `classes {Array}` a list of classes to add to the root element * - `template {Function}` the template function to use when rendering */ module.exports = function(fm) { return function(props) { var view = ('function' !== typeof props) ? fm.View.extend(props) : props; // Store the module by module type // so that module can be referred to // by just a string in layout definitions fm.modules[view.prototype._module] = view; return fm.modules[view.prototype._module]; }; }; var proto = Module.prototype; var name = proto.name || proto._module; // Store the module by module type // so that module can be referred to // by just a string in layout definitions if (name) fm.modules[name] = Module; return Module; }; }; <MSG> Don't define a module if no module name as been given <DFF> @@ -17,14 +17,17 @@ */ module.exports = function(fm) { return function(props) { - var view = ('function' !== typeof props) + var view = ('object' === typeof props) ? fm.View.extend(props) : props; + var module = view.prototype._module; + // Store the module by module type // so that module can be referred to // by just a string in layout definitions - fm.modules[view.prototype._module] = view; - return fm.modules[view.prototype._module]; + if (module) fm.modules[module] = view; + + return view; }; };
6
Don't define a module if no module name as been given
3
.js
js
mit
ftlabs/fruitmachine
10062043
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062044
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062045
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062046
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062047
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062048
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10062049
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(object tag, int startOffset, int endOffset) { Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, startOffset, endOffset) { Foreground = foreground; } public IBrush Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); } } } catch(Exception ex) { ExceptionHandler?.Invoke(ex); } } AM.FontStyle GetFontStyle() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return AM.FontStyle.Italic; return AM.FontStyle.Normal; } AM.FontWeight GetFontWeight() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return AM.FontWeight.Bold; return AM.FontWeight.Regular; } bool IsUnderline() { if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support <DFF> @@ -1,34 +1,33 @@ using System; +using System.Collections.Generic; using Avalonia.Media; using AvaloniaEdit.Document; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { - public abstract class TextTransformation : TextSegment { - public TextTransformation(object tag, int startOffset, int endOffset) + public TextTransformation(int startOffset, int endOffset) { - Tag = tag; StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); - - public object Tag { get; } } public class ForegroundTextTransformation : TextTransformation { - public ForegroundTextTransformation(object tag, int startOffset, int endOffset, IBrush foreground) : base(tag, - startOffset, endOffset) + private readonly Dictionary<int, IBrush> _brushCache; + + public ForegroundTextTransformation(Dictionary<int, IBrush> brushCache, int startOffset, int endOffset, int brushId) : base(startOffset, endOffset) { - Foreground = foreground; + _brushCache = brushCache; + Foreground = brushId; } - public IBrush Foreground { get; set; } + public int Foreground { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -50,7 +49,7 @@ namespace AvaloniaEdit.TextMate endOffset = EndOffset; } - transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, Foreground); + transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _brushCache[Foreground]); } } } \ No newline at end of file
9
Merge branch 'feature/textmate-support-text-segment-collection' into feature/textmate-support
10
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit